@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,308 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import ts from 'typescript-js'
4
+ import { normalizeCrudFormFieldRules, type CrudFormDeclarativeFieldConstraint } from '@open-mercato/shared/lib/crud/form-sections/field-rules'
5
+ import { symbolicIdSchema } from '@open-mercato/shared/lib/crud/form-sections/protocol'
6
+ import type { CrudFormSectionAddress } from '@open-mercato/shared/modules/form-section-facts'
7
+ import { arrayField, fieldsOf, literalData, literalValue, getLocalSectionInitializer, readSectionBuilder, unwrap } from './form-section-ast'
8
+ import { MODULE_CODE_EXTENSIONS, stripModuleCodeExtension } from './scanner'
9
+
10
+ type Invalid = (reason: string) => never
11
+ type SourceTarget = Pick<CrudFormSectionAddress, 'formVariant' | 'formOperation'>
12
+ export type SectionBrowserLoader = { importPath: string; source: ts.SourceFile }
13
+ export type SectionExtensionStore = { kind: 'customField' | 'table' | 'sink' | 'external'; key?: string; entityId?: string; fieldOverride: boolean }
14
+
15
+ export type SectionExtensionField = {
16
+ id: string
17
+ operation: 'add' | 'patch' | 'remove'
18
+ browser: Record<string, unknown>
19
+ loaders: Partial<Record<'options' | 'clientRule' | 'component', SectionBrowserLoader>>
20
+ rules: ReturnType<typeof normalizeCrudFormFieldRules>
21
+ server: boolean
22
+ store?: SectionExtensionStore
23
+ }
24
+
25
+ export type SectionExtensionChange = {
26
+ id: string
27
+ operation: 'add' | 'hide' | 'modify' | 'replace'
28
+ before?: string
29
+ after?: string
30
+ titleKey?: string
31
+ replacement?: SectionBrowserLoader
32
+ fields: SectionExtensionField[]
33
+ syntax: ts.Expression
34
+ }
35
+
36
+ export type SectionExtensionSource = {
37
+ index: number
38
+ id: string
39
+ hostId: string
40
+ targets: SourceTarget[]
41
+ changes: SectionExtensionChange[]
42
+ defaults: readonly { payloadPath: string; syntax: ts.Expression; readsPayloadPaths: readonly string[]; targets?: readonly SourceTarget[] }[]
43
+ syntax: ts.Expression
44
+ }
45
+
46
+ export function sectionSymbol(value: unknown, label: string, invalid: Invalid): string {
47
+ const parsed = symbolicIdSchema.safeParse(value)
48
+ return parsed.success ? parsed.data : invalid(`invalid ${label}`)
49
+ }
50
+
51
+ function formLeaf(value: unknown, label: string, invalid: Invalid): string {
52
+ return typeof value === 'string' && /^[A-Za-z0-9_:-]+(?:\.[A-Za-z0-9_:-]+)*$/.test(value)
53
+ && value.length <= 160 && !value.split('.').some((part) => ['constructor', 'prototype', '__proto__'].includes(part))
54
+ ? value : invalid(`invalid ${label}`)
55
+ }
56
+
57
+ function labelKey(value: unknown, invalid: Invalid): string {
58
+ return typeof value === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,191}$/.test(value)
59
+ ? value : invalid('expected an i18n key')
60
+ }
61
+
62
+ function optionalLiteral(value: ts.Expression | undefined, invalid: Invalid): unknown {
63
+ return value === undefined ? undefined : literalData(value, invalid)
64
+ }
65
+
66
+ function safePlacement(fields: Map<string, ts.Expression>, invalid: Invalid): { before?: string; after?: string } {
67
+ if (fields.has('before') && fields.has('after')) return invalid('before and after cannot both be specified')
68
+ return Object.fromEntries(['before', 'after'].flatMap((key) => fields.has(key)
69
+ ? [[key, sectionSymbol(optionalLiteral(fields.get(key), invalid), key, invalid)]] : []))
70
+ }
71
+
72
+ function browserLoader(
73
+ input: ts.Expression, sourceBase: string, importBase: string, invalid: Invalid,
74
+ ): SectionBrowserLoader {
75
+ const arrow = unwrap(input)
76
+ if (!ts.isArrowFunction(arrow) || arrow.parameters.length || ts.isBlock(arrow.body)) {
77
+ return invalid('browser loaders must be zero-argument arrows returning literal imports')
78
+ }
79
+ const call = unwrap(arrow.body)
80
+ if (!ts.isCallExpression(call) || call.expression.kind !== ts.SyntaxKind.ImportKeyword || call.arguments.length !== 1) {
81
+ return invalid('browser loader must use a literal dynamic import')
82
+ }
83
+ const specifier = literalValue(call.arguments[0], 'browser loader', invalid)
84
+ const relative = stripModuleCodeExtension(path.posix.normalize(specifier))
85
+ if (!specifier.startsWith('./') || specifier.includes('\\') || relative.startsWith('../') || !relative.endsWith('.client')) {
86
+ return invalid(`browser import "${specifier}" must resolve to an owning-module .client file`)
87
+ }
88
+ const candidate = MODULE_CODE_EXTENSIONS.map((extension) => path.join(sourceBase, relative + extension))
89
+ .find((filename) => fs.existsSync(filename))
90
+ if (!candidate) return invalid(`browser import "${specifier}" does not exist`)
91
+ const fromBase = path.relative(fs.realpathSync(sourceBase), fs.realpathSync(candidate))
92
+ if (fromBase.startsWith('..' + path.sep) || path.isAbsolute(fromBase)) return invalid('browser import escapes its module')
93
+ return {
94
+ importPath: importBase + '/' + relative,
95
+ source: ts.createSourceFile(candidate, fs.readFileSync(candidate, 'utf8'), ts.ScriptTarget.Latest, true),
96
+ }
97
+ }
98
+
99
+ function readStore(input: ts.Expression, fieldOverride: boolean, invalid: Invalid): SectionExtensionStore {
100
+ const { name, args } = readSectionBuilder(input, invalid)
101
+ switch (name) {
102
+ case 'store.customField':
103
+ if (args.length <= 1) return { kind: 'customField', fieldOverride,
104
+ ...(args[0] ? { key: formLeaf(literalData(args[0], invalid), 'custom-field key', invalid) } : {}) }
105
+ break
106
+ case 'store.table':
107
+ if (args.length === 1) {
108
+ return { kind: 'table', fieldOverride, entityId: sectionSymbol(literalData(args[0], invalid), 'store entity', invalid) }
109
+ }
110
+ break
111
+ case 'store.sink':
112
+ case 'store.external':
113
+ if (args.length === 1) {
114
+ const configuration = unwrap(args[0])
115
+ if (!ts.isObjectLiteralExpression(configuration)) break
116
+ const propertyName = name === 'store.sink' ? 'entityId' : 'mirror'
117
+ const property = configuration.properties.find((candidate): candidate is ts.PropertyAssignment =>
118
+ ts.isPropertyAssignment(candidate) && (ts.isIdentifier(candidate.name) || ts.isStringLiteralLike(candidate.name))
119
+ && candidate.name.text === propertyName)
120
+ const entityId = sectionSymbol(property && literalData(property.initializer, invalid), 'store entity', invalid)
121
+ return { kind: name === 'store.sink' ? 'sink' : 'external', fieldOverride, entityId }
122
+ }
123
+ break
124
+ }
125
+ return invalid(`invalid store builder "${name}"`)
126
+ }
127
+
128
+ function parseFields(
129
+ input: ts.Expression | undefined, sectionStore: SectionExtensionStore | undefined,
130
+ sourceBase: string, importBase: string, invalid: Invalid,
131
+ ): SectionExtensionField[] {
132
+ if (!input) return invalid('missing field declarations')
133
+ return [...fieldsOf(input, invalid)].map(([fieldId, declaration]) => {
134
+ const id = formLeaf(fieldId, 'field id', invalid)
135
+ const { name, args } = readSectionBuilder(declaration, invalid)
136
+ if (name === 'field.remove' && !args.length) return { id, operation: 'remove', browser: {}, loaders: {}, rules: [], server: false }
137
+ if ((name !== 'field.add' && name !== 'field.patch') || args.length !== 1) return invalid(`invalid builder for field "${id}"`)
138
+ const operation = name === 'field.add' ? 'add' : 'patch'
139
+ const fields = fieldsOf(args[0], invalid)
140
+ const browser: Record<string, unknown> = safePlacement(fields, invalid)
141
+ const loaders: SectionExtensionField['loaders'] = {}
142
+ const store = operation === 'add'
143
+ ? fields.get('store') ? readStore(fields.get('store')!, true, invalid) : sectionStore ?? { kind: 'customField' as const, fieldOverride: false }
144
+ : undefined
145
+ for (const [key, value] of fields) {
146
+ if (['before', 'after', 'validate', 'store'].includes(key)) continue
147
+ if (key === 'labelKey') browser[key] = labelKey(optionalLiteral(value, invalid), invalid)
148
+ else if (key === 'options' && ts.isArrowFunction(unwrap(value))) loaders.options = browserLoader(value, sourceBase, importBase, invalid)
149
+ else if (key === 'customComponent') loaders.component = browserLoader(value, sourceBase, importBase, invalid)
150
+ else if (['type', 'required', 'options', 'readOnly', 'visibleWhen', 'optionsCacheTtl'].includes(key)) browser[key] = literalData(value, invalid)
151
+ else invalid(`unsupported field option "${key}"`)
152
+ }
153
+ if (operation === 'add' && !['text', 'textarea', 'number', 'boolean', 'select', 'date', 'custom'].includes(String(browser.type))) {
154
+ invalid(`unsupported field type for "${id}"`)
155
+ }
156
+ if (operation === 'patch' && (fields.has('type') || fields.has('required') || fields.has('store') || loaders.component)) {
157
+ invalid(`cannot replace the schema or storage of field "${id}" using patch`)
158
+ }
159
+ const rules: CrudFormDeclarativeFieldConstraint[] = []
160
+ const validation = fields.get('validate')
161
+ let server = false
162
+ if (validation) {
163
+ const values = fieldsOf(validation, invalid)
164
+ const callback = values.get('client')
165
+ if (callback) loaders.clientRule = browserLoader(callback, sourceBase, importBase, invalid)
166
+ server = values.has('server')
167
+ for (const rule of arrayField(values, 'rules', invalid)) rules.push(literalData(rule, invalid) as CrudFormDeclarativeFieldConstraint)
168
+ const inline = Object.fromEntries([...values].filter(([key]) => !['client', 'server', 'rules'].includes(key))
169
+ .map(([key, value]) => [key, literalData(value, invalid)]))
170
+ if (Object.keys(inline).length) rules.push(inline as CrudFormDeclarativeFieldConstraint)
171
+ }
172
+ for (const rule of rules) labelKey(rule.messageKey, invalid)
173
+ const normalized = normalizeCrudFormFieldRules(rules)
174
+ if (rules.length) browser.rules = rules
175
+ return { id, operation, browser, loaders, rules: normalized, server, store }
176
+ })
177
+ }
178
+
179
+ function inferDefaultReads(syntax: ts.Expression, invalid: Invalid): string[] {
180
+ const input = unwrap(syntax)
181
+ const definition = ts.isIdentifier(input) ? getLocalSectionInitializer(input.getSourceFile(), input.text)
182
+ ?? input.getSourceFile().statements.find((statement): statement is ts.FunctionDeclaration =>
183
+ ts.isFunctionDeclaration(statement) && statement.name?.text === input.text) : input
184
+ if (!definition || (!ts.isArrowFunction(definition) && !ts.isFunctionExpression(definition) && !ts.isFunctionDeclaration(definition))) {
185
+ return invalid('a default must name a local callback with explicit payload reads')
186
+ }
187
+ const param = definition.parameters[0]?.name
188
+ if (!param || !definition.body) return []
189
+ const aliases = new Set<string>()
190
+ const contextName = ts.isIdentifier(param) ? param.text : null
191
+ if (ts.isObjectBindingPattern(param)) for (const binding of param.elements) {
192
+ if ((binding.propertyName ?? binding.name).getText().replace(/^['"]|['"]$/g, '') === 'payload') {
193
+ if (!ts.isIdentifier(binding.name)) return invalid('default payload binding must be a named object')
194
+ aliases.add(binding.name.text)
195
+ }
196
+ }
197
+ const paths = new Set<string>()
198
+ function chain(node: ts.Node): { base: string; parts: string[] } | null {
199
+ if (ts.isIdentifier(node)) return { base: node.text, parts: [] }
200
+ if (ts.isPropertyAccessExpression(node)) {
201
+ const prefix = chain(node.expression)
202
+ return prefix && { ...prefix, parts: [...prefix.parts, node.name.text] }
203
+ }
204
+ if (ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression)) {
205
+ const prefix = chain(node.expression)
206
+ return prefix && { ...prefix, parts: [...prefix.parts, node.argumentExpression.text] }
207
+ }
208
+ return null
209
+ }
210
+ function visit(node: ts.Node): void {
211
+ if ((ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node))
212
+ && (!node.parent || !(ts.isPropertyAccessExpression(node.parent) || ts.isElementAccessExpression(node.parent))
213
+ || node.parent.expression !== node)) {
214
+ const access = chain(node)
215
+ if (access) {
216
+ const leaf = aliases.has(access.base) ? access.parts
217
+ : access.base === contextName && access.parts[0] === 'payload' ? access.parts.slice(1) : undefined
218
+ if (leaf) {
219
+ if (!leaf.length) invalid('default must read a concrete payload path')
220
+ paths.add(formLeaf(leaf.join('.'), 'default payload read', invalid))
221
+ return
222
+ }
223
+ }
224
+ }
225
+ if (ts.isIdentifier(node) && aliases.has(node.text)) invalid('default cannot use its whole payload or a computed payload path')
226
+ if (ts.isIdentifier(node) && node.text === contextName && (!ts.isPropertyAccessExpression(node.parent) || node.parent.expression !== node)) {
227
+ invalid('default cannot use a computed context path')
228
+ }
229
+ ts.forEachChild(node, visit)
230
+ }
231
+ visit(definition.body)
232
+ return [...paths].sort((left, right) => left < right ? -1 : left > right ? 1 : 0)
233
+ }
234
+
235
+ export function parseSectionExtensionSources(
236
+ initializer: ts.Expression | undefined, sourceBase: string, importPath: string, invalid: Invalid,
237
+ ): SectionExtensionSource[] {
238
+ if (!initializer) return []
239
+ const array = unwrap(initializer)
240
+ if (!ts.isArrayLiteralExpression(array)) return invalid('crudFormExtensions must be a literal array')
241
+ const importBase = importPath.slice(0, importPath.lastIndexOf('/'))
242
+ const hosts = new Set<string>()
243
+ return array.elements.map((syntax, index) => {
244
+ const { name, args } = readSectionBuilder(syntax, invalid)
245
+ if (name !== 'defineCrudFormExtension' || args.length !== 1) return invalid('expected defineCrudFormExtension with one argument')
246
+ const fields = fieldsOf(args[0], invalid)
247
+ if ([...fields.keys()].some((key) => !['id', 'host', 'targets', 'sections', 'defaults'].includes(key))) return invalid('unexpected extension property')
248
+ const id = sectionSymbol(optionalLiteral(fields.get('id'), invalid), 'extension id', invalid)
249
+ const host = literalValue(fields.get('host'), 'host spot', invalid)
250
+ if (!host.startsWith('crud-form:')) return invalid('extension host must be a crud-form: spot')
251
+ const hostId = sectionSymbol(host.slice('crud-form:'.length), 'host id', invalid)
252
+ if (hosts.has(hostId)) return invalid(`multiple extension definitions for host "${hostId}" in one module`)
253
+ hosts.add(hostId)
254
+ function readTargets(fieldMap: Map<string, ts.Expression>): SourceTarget[] {
255
+ const entries = arrayField(fieldMap, 'targets', invalid).map((target): SourceTarget => {
256
+ const fields = fieldsOf(target, invalid)
257
+ const formVariant = sectionSymbol(optionalLiteral(fields.get('formVariant'), invalid), 'form variant', invalid)
258
+ const formOperation = optionalLiteral(fields.get('formOperation'), invalid)
259
+ if (fields.size !== 2 || (formOperation !== 'create' && formOperation !== 'update')) return invalid('invalid extension target')
260
+ return { formVariant, formOperation }
261
+ })
262
+ if (!entries.length || entries.length !== new Set(entries.map(({ formVariant, formOperation }) => formVariant + '/' + formOperation)).size) {
263
+ return invalid('expected unique extension targets')
264
+ }
265
+ return entries
266
+ }
267
+ const targets = readTargets(fields)
268
+ const raw = fields.get('sections')
269
+ if (!raw) return invalid('missing extension sections')
270
+ const changes = [...fieldsOf(raw, invalid)].map(([sectionId, declaration]): SectionExtensionChange => {
271
+ const id = sectionSymbol(sectionId, 'section id', invalid)
272
+ const { name, args } = readSectionBuilder(declaration, invalid)
273
+ const base = { id, fields: [], syntax: declaration }
274
+ if (name === 'hide' && !args.length) return { ...base, operation: 'hide' }
275
+ if (name === 'replace' && args.length === 1) {
276
+ return { ...base, operation: 'replace', replacement: browserLoader(args[0], sourceBase, importBase, invalid) }
277
+ }
278
+ if ((name !== 'modify' && name !== 'add') || args.length !== 1) return invalid(`invalid section builder for "${id}"`)
279
+ const opts = fieldsOf(args[0], invalid)
280
+ if ([...opts.keys()].some((key) => !(name === 'add' ? ['fields', 'before', 'after', 'store', 'titleKey'] : ['fields']).includes(key))) {
281
+ return invalid(`unsupported options for section "${id}"`)
282
+ }
283
+ const sectionStore = opts.get('store') ? readStore(opts.get('store')!, false, invalid) : undefined
284
+ const projected = parseFields(opts.get('fields'), sectionStore, sourceBase, importBase, invalid)
285
+ const titleKey = opts.get('titleKey') ? labelKey(optionalLiteral(opts.get('titleKey'), invalid), invalid) : undefined
286
+ if ((!projected.length && (name === 'modify' || !titleKey))
287
+ || (name === 'add' && projected.some(({ operation }) => operation !== 'add'))) return invalid('invalid empty or non-add field declaration')
288
+ return { ...base, ...safePlacement(opts, invalid), operation: name, fields: projected, titleKey }
289
+ })
290
+ if (!changes.length) return invalid('expected at least one section change')
291
+ const defaultMap = fields.get('defaults')
292
+ const defaults = defaultMap ? [...fieldsOf(defaultMap, invalid)].map(([key, syntax]) => {
293
+ const payloadPath = formLeaf(key, 'default payload path', invalid)
294
+ const value = unwrap(syntax)
295
+ if (!ts.isObjectLiteralExpression(value)) return { payloadPath, syntax, readsPayloadPaths: inferDefaultReads(value, invalid) }
296
+ const defaultFields = fieldsOf(value, invalid)
297
+ const resolve = defaultFields.get('resolve')
298
+ if (defaultFields.size !== 2 || !resolve) return invalid('expected scoped default targets and resolve callback')
299
+ const scopedTargets = readTargets(defaultFields)
300
+ if (scopedTargets.some((target) => !targets.some(({ formVariant, formOperation }) =>
301
+ formVariant === target.formVariant && formOperation === target.formOperation))) {
302
+ return invalid('scoped default targets must belong to the extension')
303
+ }
304
+ return { payloadPath, syntax, targets: scopedTargets, readsPayloadPaths: inferDefaultReads(resolve, invalid) }
305
+ }) : []
306
+ return { index, id, hostId, targets, changes, defaults, syntax }
307
+ })
308
+ }
@@ -0,0 +1,211 @@
1
+ import { createHash } from 'node:crypto'
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import ts from 'typescript-js'
5
+ import { compareSectionIds } from '@open-mercato/shared/lib/crud/form-sections/composition'
6
+ import { MODULE_CODE_EXTENSIONS, stripModuleCodeExtension } from './scanner'
7
+
8
+ const ledgerFileName = 'form-sections.runtime-revisions.json'
9
+ const revisionPattern = /^(.+)@v([1-9][0-9]*)$/
10
+
11
+ type Revision = { roundTripId: string; sourceHash: string }
12
+ type Entry = Revision & { id: string }
13
+
14
+ function withoutParentheses(node: ts.Node): ts.Node {
15
+ return ts.isParenthesizedExpression(node) || ts.isAsExpression(node) || ts.isSatisfiesExpression(node)
16
+ ? withoutParentheses(node.expression) : node
17
+ }
18
+
19
+ function enclosingExpression(node: ts.Node): ts.Node {
20
+ const parent = node.parent
21
+ return parent && withoutParentheses(parent) === node ? enclosingExpression(parent) : node
22
+ }
23
+
24
+ function isGranularRefinement(refinement: ts.ObjectLiteralExpression): boolean {
25
+ const array = enclosingExpression(refinement).parent
26
+ if (!array || !ts.isArrayLiteralExpression(array)) return false
27
+ const setting = enclosingExpression(array).parent
28
+ if (!setting || !ts.isPropertyAssignment(setting) || (!ts.isIdentifier(setting.name) && !ts.isStringLiteral(setting.name))
29
+ || setting.name.text !== 'refinements') return false
30
+ const definition = enclosingExpression(setting.parent)
31
+ const call = definition.parent
32
+ return Boolean(call && ts.isCallExpression(call) && ts.isIdentifier(call.expression)
33
+ && call.expression.text === 'defineCrudFormFieldGranularSection' && call.arguments[0] === definition)
34
+ }
35
+
36
+ function isDefaultRefinementFlag(property: ts.Node): boolean {
37
+ if (!ts.isPropertyAssignment(property) || property.initializer.kind !== ts.SyntaxKind.FalseKeyword
38
+ || (!ts.isIdentifier(property.name) && !ts.isStringLiteral(property.name)) || property.name.text !== 'mandatory') return false
39
+ const refinement = property.parent
40
+ if (!ts.isObjectLiteralExpression(refinement) || refinement.properties.some((candidate) => candidate !== property
41
+ && (!candidate.name || (!ts.isIdentifier(candidate.name) && !ts.isStringLiteral(candidate.name))
42
+ || candidate.name.text === 'mandatory'))) return false
43
+ return true
44
+ }
45
+
46
+ function normalize(node: ts.Node, source: ts.SourceFile): unknown {
47
+ if (ts.isObjectLiteralExpression(node) && ts.isArrayLiteralExpression(node.parent)
48
+ && ts.isPropertyAssignment(node.parent.parent)
49
+ && node.parent.parent.name.getText(source).replace(/^['"]|['"]$/g, '') === 'refinements') {
50
+ const entries = node.properties.filter((property) => !ts.isPropertyAssignment(property)
51
+ || property.name.getText(source).replace(/^['"]|['"]$/g, '') !== 'mandatory'
52
+ || property.initializer.kind !== ts.SyntaxKind.FalseKeyword)
53
+ return [node.kind, entries.map((entry) => normalize(entry, source))]
54
+ }
55
+ const children = node.getChildren(source).filter((child) => !ts.isJSDoc(child))
56
+ if (ts.isObjectLiteralExpression(node) && isGranularRefinement(node)) {
57
+ return [node.kind, node.properties.filter((property) => !isDefaultRefinementFlag(property)).map((property) => normalize(property, source))]
58
+ }
59
+ const last = children.at(-1)
60
+ if (last?.kind === ts.SyntaxKind.SemicolonToken && (ts.isStatement(node) || ts.isTypeElement(node))
61
+ && !ts.isEmptyStatement(node)) children.pop()
62
+ if (last?.kind === ts.SyntaxKind.CommaToken && node.kind === ts.SyntaxKind.SyntaxList) children.pop()
63
+ if (children.length) return [node.kind, children.map((child) => normalize(child, source))]
64
+ if (ts.isIdentifier(node) || ts.isStringLiteral(node) || ts.isNumericLiteral(node) || ts.isJsxText(node)) {
65
+ return [node.kind, node.text]
66
+ }
67
+ return [node.kind, node.getText(source)]
68
+ }
69
+
70
+ function readLocalDependency(specifier: string, file: string, sourceRoot: string): string | null {
71
+ const logical = specifier.startsWith('.') ? path.resolve(path.dirname(file), specifier)
72
+ : specifier.startsWith('@/') ? path.resolve(sourceRoot, specifier.slice(2)) : null
73
+ if (!logical) return null
74
+ const target = stripModuleCodeExtension(logical)
75
+ const candidates = [
76
+ ...MODULE_CODE_EXTENSIONS.map((extension) => target + extension),
77
+ ...MODULE_CODE_EXTENSIONS.map((extension) => path.join(target, 'index' + extension)),
78
+ ...(path.extname(logical) === '.json' ? [logical] : []),
79
+ ]
80
+ for (const candidate of candidates) {
81
+ if (!fs.existsSync(candidate) || !fs.statSync(candidate).isFile()) continue
82
+ const absolute = fs.realpathSync(candidate)
83
+ const relative = path.relative(sourceRoot, absolute)
84
+ if (relative.startsWith('..' + path.sep) || path.isAbsolute(relative) || relative.split(path.sep).includes('node_modules')) continue
85
+ return absolute
86
+ }
87
+ return null
88
+ }
89
+
90
+ function fingerprintRuntime(source: ts.SourceFile, sourceRoot: string, visited: Set<string>): unknown {
91
+ const filename = fs.realpathSync(source.fileName)
92
+ if (visited.has(filename)) return null
93
+ visited.add(filename)
94
+ if (path.extname(filename) === '.json') return JSON.parse(source.text)
95
+ const specifiers = new Set<string>()
96
+ const visit = (node: ts.Node): void => {
97
+ if ((ts.isImportDeclaration(node) && !node.importClause?.isTypeOnly)
98
+ || (ts.isExportDeclaration(node) && !node.isTypeOnly)) {
99
+ if (node.moduleSpecifier && ts.isStringLiteralLike(node.moduleSpecifier)) specifiers.add(node.moduleSpecifier.text)
100
+ } else if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword
101
+ || (ts.isIdentifier(node.expression) && node.expression.text === 'require'))) {
102
+ const [argument] = node.arguments
103
+ if (argument && ts.isStringLiteralLike(argument)) specifiers.add(argument.text)
104
+ }
105
+ ts.forEachChild(node, visit)
106
+ }
107
+ visit(source)
108
+ const dependencies = [...specifiers].sort(compareSectionIds).flatMap((specifier) => {
109
+ const dependency = readLocalDependency(specifier, filename, sourceRoot)
110
+ if (!dependency || visited.has(dependency)) return []
111
+ const contents = ts.createSourceFile(dependency, fs.readFileSync(dependency, 'utf8'), ts.ScriptTarget.Latest, true)
112
+ return [[specifier, fingerprintRuntime(contents, sourceRoot, visited)]]
113
+ })
114
+ const jsxPragmas = (ts.getLeadingCommentRanges(source.text, 0) ?? []).flatMap(({ pos, end }) =>
115
+ [...source.text.slice(pos, end).matchAll(/@(jsx(?:Frag|ImportSource|Runtime)?)\s+([^\s*]+)/g)].map((match) => match.slice(1)))
116
+ return [path.relative(sourceRoot, filename).split(path.sep).join('/'), jsxPragmas, normalize(source, source), dependencies]
117
+ }
118
+
119
+ export function hashHandwrittenSectionRuntime(runtime: ts.SourceFile, fact: ts.Expression, moduleBase: string): string {
120
+ const sourceRoot = fs.realpathSync(path.resolve(moduleBase, '../..'))
121
+ return createHash('sha256').update(JSON.stringify([
122
+ normalize(fact, fact.getSourceFile()), fingerprintRuntime(runtime, sourceRoot, new Set()),
123
+ ])).digest('hex')
124
+ }
125
+
126
+ function readLedger(filename: string, invalid: (reason: string) => never): Map<string, Revision> {
127
+ const stats = fs.lstatSync(filename, { throwIfNoEntry: false })
128
+ if (!stats) return new Map()
129
+ if (!stats.isFile()) return invalid(ledgerFileName + ' must be a regular file')
130
+ let parsed: unknown
131
+ try {
132
+ parsed = JSON.parse(fs.readFileSync(filename, 'utf8'))
133
+ } catch {
134
+ return invalid('invalid ' + ledgerFileName)
135
+ }
136
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return invalid('invalid ' + ledgerFileName)
137
+ const entries = new Map<string, Revision>()
138
+ for (const [id, entry] of Object.entries(parsed)) {
139
+ if (!entry || typeof entry !== 'object' || Object.keys(entry).length !== 2
140
+ || typeof entry.roundTripId !== 'string' || revisionPattern.exec(entry.roundTripId)?.[1] !== id
141
+ || typeof entry.sourceHash !== 'string' || !/^[0-9a-f]{64}$/.test(entry.sourceHash)) {
142
+ return invalid('invalid ' + ledgerFileName)
143
+ }
144
+ entries.set(id, { roundTripId: entry.roundTripId, sourceHash: entry.sourceHash })
145
+ }
146
+ return entries
147
+ }
148
+
149
+ export function planHandwrittenSectionRevisionWrite(
150
+ moduleBase: string, entries: readonly Entry[], invalid: (reason: string) => never,
151
+ ): { filename: string; content: string } | null {
152
+ if (!entries.length) return null
153
+ const filename = path.join(moduleBase, ledgerFileName)
154
+ const ledger = readLedger(filename, invalid)
155
+ let changed = false
156
+ for (const { id, roundTripId, sourceHash } of entries) {
157
+ const previous = ledger.get(id)
158
+ if (previous?.roundTripId === roundTripId && previous.sourceHash === sourceHash) continue
159
+ const version = (revision: string) => BigInt(revisionPattern.exec(revision)![2])
160
+ if (previous && version(roundTripId) <= version(previous.roundTripId)) {
161
+ return invalid(`semantic runtime drift for "${id}" requires advancing roundTripId beyond "${previous.roundTripId}"`)
162
+ }
163
+ ledger.set(id, { roundTripId, sourceHash })
164
+ changed = true
165
+ }
166
+ if (!changed) return null
167
+ return {
168
+ filename,
169
+ content: JSON.stringify(Object.fromEntries([...ledger.keys()].sort(compareSectionIds).map((id) => [id, ledger.get(id)])), null, 2) + '\n',
170
+ }
171
+ }
172
+
173
+ export function hashCompiledSectionSource(syntax: ts.Expression, moduleBase: string): string {
174
+ const source = syntax.getSourceFile()
175
+ const sourceRoot = fs.realpathSync(path.resolve(moduleBase, '../..'))
176
+ const declarations = new Map<string, ts.Node>()
177
+ for (const statement of source.statements) {
178
+ if (ts.isFunctionDeclaration(statement) && statement.name) declarations.set(statement.name.text, statement)
179
+ if (ts.isVariableStatement(statement)) for (const declaration of statement.declarationList.declarations) {
180
+ if (ts.isIdentifier(declaration.name)) declarations.set(declaration.name.text, declaration)
181
+ }
182
+ if (ts.isImportDeclaration(statement) && !statement.importClause?.isTypeOnly) {
183
+ const clause = statement.importClause
184
+ if (clause?.name) declarations.set(clause.name.text, statement)
185
+ const bindings = clause?.namedBindings
186
+ if (bindings && ts.isNamespaceImport(bindings)) declarations.set(bindings.name.text, statement)
187
+ if (bindings && ts.isNamedImports(bindings)) for (const element of bindings.elements) {
188
+ if (!element.isTypeOnly) declarations.set(element.name.text, statement)
189
+ }
190
+ }
191
+ }
192
+ const reachable = new Set<ts.Node>()
193
+ function visit(node: ts.Node): void {
194
+ if (ts.isIdentifier(node)) {
195
+ const declaration = declarations.get(node.text)
196
+ if (declaration && !reachable.has(declaration)) {
197
+ reachable.add(declaration)
198
+ ts.forEachChild(declaration, visit)
199
+ }
200
+ }
201
+ ts.forEachChild(node, visit)
202
+ }
203
+ visit(syntax)
204
+ const imports = [...reachable].filter(ts.isImportDeclaration)
205
+ const snippets = [...imports.map((statement) => statement.getText(source)), `const descriptor = (${syntax.getText(source)})`]
206
+ const graph = ts.createSourceFile(source.fileName, snippets.join('\n'), ts.ScriptTarget.Latest, true)
207
+ return createHash('sha256').update(JSON.stringify([
208
+ [...reachable].filter((statement) => !ts.isImportDeclaration(statement)).map((statement) => normalize(statement, source)),
209
+ fingerprintRuntime(graph, sourceRoot, new Set()),
210
+ ])).digest('hex')
211
+ }