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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (285) hide show
  1. package/.turbo/turbo-build.log +4 -2
  2. package/AGENTS.md +3 -0
  3. package/dist/agentic/guides/architecture.md +2 -2
  4. package/dist/agentic/guides/extensions.md +7 -2
  5. package/dist/agentic/guides/framework-extension-points.md +1 -0
  6. package/dist/agentic/guides/infrastructure-providers.md +20 -0
  7. package/dist/agentic/guides/integrations.md +2 -2
  8. package/dist/agentic/guides/module-facts.json +2564 -265
  9. package/dist/agentic/guides/module-facts.v2.json +2580 -265
  10. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  11. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  12. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  13. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  14. package/dist/agentic/guides/modules/assisted_selling/acl-features.md +16 -0
  15. package/dist/agentic/guides/modules/assisted_selling/contribution-resolutions.md +21 -0
  16. package/dist/agentic/guides/modules/assisted_selling/domain-commands.md +11 -0
  17. package/dist/agentic/guides/modules/assisted_selling/entities.md +11 -0
  18. package/dist/agentic/guides/modules/assisted_selling/events.md +22 -0
  19. package/dist/agentic/guides/modules/assisted_selling/exact-override-targets.md +17 -0
  20. package/dist/agentic/guides/modules/assisted_selling/index.md +21 -0
  21. package/dist/agentic/guides/modules/assisted_selling/owned-contract-module-metadata.md +11 -0
  22. package/dist/agentic/guides/modules/assisted_selling/setup.md +11 -0
  23. package/dist/agentic/guides/modules/assisted_selling/umes-contributions.md +21 -0
  24. package/dist/agentic/guides/modules/assisted_selling/umes-hosts.md +23 -0
  25. package/dist/agentic/guides/modules/attachments/exact-override-targets.md +1 -1
  26. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  27. package/dist/agentic/guides/modules/attachments/workers.md +1 -1
  28. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  29. package/dist/agentic/guides/modules/auth/index.md +1 -1
  30. package/dist/agentic/guides/modules/availability/index.md +1 -1
  31. package/dist/agentic/guides/modules/backups/di-registrations-rich.md +11 -0
  32. package/dist/agentic/guides/modules/backups/di-service-tokens.md +11 -0
  33. package/dist/agentic/guides/modules/backups/exact-override-targets.md +11 -0
  34. package/dist/agentic/guides/modules/backups/index.md +5 -2
  35. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  36. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  37. package/dist/agentic/guides/modules/cart/index.md +1 -1
  38. package/dist/agentic/guides/modules/catalog/acl-features.md +2 -1
  39. package/dist/agentic/guides/modules/catalog/active-extension-bindings.md +2 -0
  40. package/dist/agentic/guides/modules/catalog/backend-pages.md +1 -0
  41. package/dist/agentic/guides/modules/catalog/contribution-resolutions.md +5 -0
  42. package/dist/agentic/guides/modules/catalog/di-registrations-rich.md +8 -7
  43. package/dist/agentic/guides/modules/catalog/di-service-tokens.md +5 -4
  44. package/dist/agentic/guides/modules/catalog/domain-commands.md +2 -0
  45. package/dist/agentic/guides/modules/catalog/entities.md +1 -0
  46. package/dist/agentic/guides/modules/catalog/events.md +4 -1
  47. package/dist/agentic/guides/modules/catalog/exact-override-targets.md +13 -7
  48. package/dist/agentic/guides/modules/catalog/index.md +9 -9
  49. package/dist/agentic/guides/modules/catalog/umes-contributions.md +5 -0
  50. package/dist/agentic/guides/modules/catalog/umes-hosts.md +4 -0
  51. package/dist/agentic/guides/modules/catalog/workers.md +1 -0
  52. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  53. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  54. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  55. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  56. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  57. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  58. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  59. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  60. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  61. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  62. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  63. package/dist/agentic/guides/modules/configs/index.md +1 -1
  64. package/dist/agentic/guides/modules/content/index.md +1 -1
  65. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  66. package/dist/agentic/guides/modules/customer_accounts/active-extension-bindings.md +1 -1
  67. package/dist/agentic/guides/modules/customer_accounts/exact-override-targets.md +2 -0
  68. package/dist/agentic/guides/modules/customer_accounts/index.md +2 -2
  69. package/dist/agentic/guides/modules/customer_accounts/workers.md +2 -0
  70. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  71. package/dist/agentic/guides/modules/customers/active-extension-bindings.md +2 -1
  72. package/dist/agentic/guides/modules/customers/incoming-installed-contributions.md +1 -0
  73. package/dist/agentic/guides/modules/customers/index.md +3 -3
  74. package/dist/agentic/guides/modules/customers/umes-hosts.md +1 -0
  75. package/dist/agentic/guides/modules/dashboards/active-extension-bindings.md +0 -1
  76. package/dist/agentic/guides/modules/dashboards/cli-commands.md +1 -0
  77. package/dist/agentic/guides/modules/dashboards/exact-override-targets.md +1 -0
  78. package/dist/agentic/guides/modules/dashboards/index.md +2 -3
  79. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  80. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  81. package/dist/agentic/guides/modules/devices/index.md +1 -1
  82. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  83. package/dist/agentic/guides/modules/directory/index.md +1 -1
  84. package/dist/agentic/guides/modules/documents/index.md +1 -1
  85. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  86. package/dist/agentic/guides/modules/entities/index.md +1 -1
  87. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  88. package/dist/agentic/guides/modules/events/index.md +1 -1
  89. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  90. package/dist/agentic/guides/modules/forms/index.md +1 -1
  91. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  92. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  93. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  94. package/dist/agentic/guides/modules/generators/index.md +1 -1
  95. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  96. package/dist/agentic/guides/modules/integrations/di-registrations-rich.md +8 -8
  97. package/dist/agentic/guides/modules/integrations/di-service-tokens.md +4 -4
  98. package/dist/agentic/guides/modules/integrations/exact-override-targets.md +14 -12
  99. package/dist/agentic/guides/modules/integrations/index.md +2 -2
  100. package/dist/agentic/guides/modules/integrations/setup.md +1 -1
  101. package/dist/agentic/guides/modules/integrations/workers.md +3 -1
  102. package/dist/agentic/guides/modules/messages/index.md +1 -1
  103. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  104. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  105. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  106. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  107. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  108. package/dist/agentic/guides/modules/planner/index.md +1 -1
  109. package/dist/agentic/guides/modules/portal/index.md +1 -1
  110. package/dist/agentic/guides/modules/progress/index.md +1 -1
  111. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  112. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  113. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  114. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  115. package/dist/agentic/guides/modules/resources/exact-override-targets.md +3 -3
  116. package/dist/agentic/guides/modules/resources/index.md +1 -1
  117. package/dist/agentic/guides/modules/resources/owned-contract-module-metadata.md +1 -1
  118. package/dist/agentic/guides/modules/resources/setup.md +1 -1
  119. package/dist/agentic/guides/modules/sales/contribution-resolutions.md +1 -0
  120. package/dist/agentic/guides/modules/sales/exact-override-targets.md +1 -0
  121. package/dist/agentic/guides/modules/sales/index.md +3 -3
  122. package/dist/agentic/guides/modules/sales/umes-contributions.md +1 -0
  123. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  124. package/dist/agentic/guides/modules/search/index.md +1 -1
  125. package/dist/agentic/guides/modules/security/index.md +1 -1
  126. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  127. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  128. package/dist/agentic/guides/modules/sso/index.md +1 -1
  129. package/dist/agentic/guides/modules/staff/contribution-resolutions.md +1 -1
  130. package/dist/agentic/guides/modules/staff/exact-override-targets.md +1 -1
  131. package/dist/agentic/guides/modules/staff/index.md +1 -1
  132. package/dist/agentic/guides/modules/staff/workers.md +1 -1
  133. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  134. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  135. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  136. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  137. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  138. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  139. package/dist/agentic/guides/modules/translations/index.md +1 -1
  140. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  141. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  142. package/dist/agentic/guides/modules/wms/index.md +1 -1
  143. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  144. package/dist/agentic/guides/reference-module-facts.json +811 -21
  145. package/dist/agentic/guides/reference-modules/example/active-extension-bindings.md +1 -0
  146. package/dist/agentic/guides/reference-modules/example/backend-pages.md +2 -0
  147. package/dist/agentic/guides/reference-modules/example/contribution-resolutions.md +3 -1
  148. package/dist/agentic/guides/reference-modules/example/di-registrations-rich.md +3 -3
  149. package/dist/agentic/guides/reference-modules/example/di-service-tokens.md +1 -1
  150. package/dist/agentic/guides/reference-modules/example/entities.md +2 -0
  151. package/dist/agentic/guides/reference-modules/example/events.md +2 -1
  152. package/dist/agentic/guides/reference-modules/example/exact-override-targets.md +25 -8
  153. package/dist/agentic/guides/reference-modules/example/index.md +7 -7
  154. package/dist/agentic/guides/reference-modules/example/notifications.md +1 -0
  155. package/dist/agentic/guides/reference-modules/example/setup.md +1 -1
  156. package/dist/agentic/guides/reference-modules/example/umes-contributions.md +3 -1
  157. package/dist/agentic/guides/reference-modules/example/umes-hosts.md +4 -0
  158. package/dist/agentic/guides/upstream/AGENTS.md +5 -4
  159. package/dist/agentic/guides/upstream/BACKWARD_COMPATIBILITY.md +37 -20
  160. package/dist/agentic/guides/upstream/manifest.json +3 -3
  161. package/dist/agentic/shared/AGENTS.md.template +11 -15
  162. package/dist/agentic/shared/ai/harness/README.md +4 -2
  163. package/dist/agentic/shared/ai/harness/RELEASE.md +4 -4
  164. package/dist/agentic/shared/ai/harness/cases.json +1420 -41
  165. package/dist/agentic/shared/ai/harness/cases.schema.json +4 -4
  166. package/dist/agentic/shared/ai/harness/design-system-inventory.json +640 -142
  167. package/dist/agentic/shared/ai/harness/source-link-inventory.json +223 -16
  168. package/dist/agentic/shared/ai/harness/validators.json +1 -1
  169. package/dist/agentic/shared/ai/skills/om-system-extension/SKILL.md +1 -1
  170. package/dist/agentic/shared/ai/skills/om-system-extension/references/extension-branches.md +25 -0
  171. package/dist/agentic/shared/ai/skills/om-system-extension/references/mechanism-selector.md +1 -0
  172. package/dist/agentic/shared/ai/skills/om-system-extension/references/unified-overrides.md +2 -0
  173. package/dist/agentic/shared/scripts/run-agent-harness-release.mjs +21 -1
  174. package/dist/lib/cache-provider-manifest.js +9 -0
  175. package/dist/lib/cache-provider-manifest.js.map +7 -0
  176. package/dist/lib/generate-child-process.js +21 -3
  177. package/dist/lib/generate-child-process.js.map +2 -2
  178. package/dist/lib/generate-watch-events.js +135 -19
  179. package/dist/lib/generate-watch-events.js.map +2 -2
  180. package/dist/lib/generate-watch-plan.js +170 -0
  181. package/dist/lib/generate-watch-plan.js.map +7 -0
  182. package/dist/lib/generate-watch-runner.js +54 -0
  183. package/dist/lib/generate-watch-runner.js.map +7 -0
  184. package/dist/lib/generate-watch-structure.js +578 -203
  185. package/dist/lib/generate-watch-structure.js.map +3 -3
  186. package/dist/lib/generators/ast/writers.js +5 -1
  187. package/dist/lib/generators/ast/writers.js.map +2 -2
  188. package/dist/lib/generators/cache-providers.js +80 -0
  189. package/dist/lib/generators/cache-providers.js.map +7 -0
  190. package/dist/lib/generators/extensions/agent-files.js +1 -0
  191. package/dist/lib/generators/extensions/agent-files.js.map +2 -2
  192. package/dist/lib/generators/form-section-ast.js +156 -0
  193. package/dist/lib/generators/form-section-ast.js.map +7 -0
  194. package/dist/lib/generators/form-section-extension-compiler.js +568 -0
  195. package/dist/lib/generators/form-section-extension-compiler.js.map +7 -0
  196. package/dist/lib/generators/form-section-extension-source.js +245 -0
  197. package/dist/lib/generators/form-section-extension-source.js.map +7 -0
  198. package/dist/lib/generators/form-section-runtime-revisions.js +184 -0
  199. package/dist/lib/generators/form-section-runtime-revisions.js.map +7 -0
  200. package/dist/lib/generators/form-sections.js +773 -0
  201. package/dist/lib/generators/form-sections.js.map +7 -0
  202. package/dist/lib/generators/index.js +2 -0
  203. package/dist/lib/generators/index.js.map +2 -2
  204. package/dist/lib/generators/module-entities.js +21 -2
  205. package/dist/lib/generators/module-entities.js.map +2 -2
  206. package/dist/lib/generators/module-extension-facts.js +2 -1
  207. package/dist/lib/generators/module-extension-facts.js.map +2 -2
  208. package/dist/lib/generators/module-facts.js +30 -1
  209. package/dist/lib/generators/module-facts.js.map +2 -2
  210. package/dist/lib/generators/module-override-targets.js +24 -2
  211. package/dist/lib/generators/module-override-targets.js.map +2 -2
  212. package/dist/lib/generators/module-registry.js +223 -194
  213. package/dist/lib/generators/module-registry.js.map +3 -3
  214. package/dist/lib/generators/openapi.js +51 -18
  215. package/dist/lib/generators/openapi.js.map +2 -2
  216. package/dist/lib/generators/web-research-adapters.js +54 -22
  217. package/dist/lib/generators/web-research-adapters.js.map +2 -2
  218. package/dist/lib/in-process-generate-watcher.js +98 -75
  219. package/dist/lib/in-process-generate-watcher.js.map +2 -2
  220. package/dist/lib/post-generate-invalidation.js +20 -1
  221. package/dist/lib/post-generate-invalidation.js.map +2 -2
  222. package/dist/lib/resolver.js +195 -1
  223. package/dist/lib/resolver.js.map +3 -3
  224. package/dist/lib/single-instance-strategy-guard.js +26 -3
  225. package/dist/lib/single-instance-strategy-guard.js.map +2 -2
  226. package/dist/mercato.js +106 -50
  227. package/dist/mercato.js.map +2 -2
  228. package/jest.config.cjs +2 -0
  229. package/package.json +7 -7
  230. package/src/__tests__/mercato.test.ts +18 -0
  231. package/src/__tests__/rotation-json-output.test.ts +52 -0
  232. package/src/lib/__tests__/cache-provider-manifest.test.ts +76 -0
  233. package/src/lib/__tests__/generate-child-process.test.ts +30 -0
  234. package/src/lib/__tests__/generate-watch-events.test.ts +377 -8
  235. package/src/lib/__tests__/generate-watch-plan.test.ts +99 -0
  236. package/src/lib/__tests__/generate-watch-runner.test.ts +138 -0
  237. package/src/lib/__tests__/generate-watch-structure.test.ts +556 -1
  238. package/src/lib/__tests__/in-process-generate-watcher.test.ts +393 -6
  239. package/src/lib/__tests__/module-inspection.test.ts +17 -11
  240. package/src/lib/__tests__/post-generate-invalidation.test.ts +108 -0
  241. package/src/lib/__tests__/resolver.form-section-gates.test.ts +82 -0
  242. package/src/lib/__tests__/single-instance-strategy-guard.test.ts +129 -0
  243. package/src/lib/cache-provider-manifest.ts +8 -0
  244. package/src/lib/generate-child-process.ts +26 -3
  245. package/src/lib/generate-watch-events.ts +189 -17
  246. package/src/lib/generate-watch-plan.ts +180 -0
  247. package/src/lib/generate-watch-runner.ts +63 -0
  248. package/src/lib/generate-watch-structure.ts +670 -227
  249. package/src/lib/generators/__tests__/cache-providers.test.ts +102 -0
  250. package/src/lib/generators/__tests__/derived-crud-route-collisions.test.ts +85 -0
  251. package/src/lib/generators/__tests__/form-section-outbox.test.ts +53 -0
  252. package/src/lib/generators/__tests__/form-sections.test.ts +896 -0
  253. package/src/lib/generators/__tests__/incremental-registry.test.ts +262 -0
  254. package/src/lib/generators/__tests__/module-extension-facts.test.ts +1 -0
  255. package/src/lib/generators/__tests__/module-facts.bc-guard.test.ts +8 -6
  256. package/src/lib/generators/__tests__/module-facts.example-fact-coverage.test.ts +37 -13
  257. package/src/lib/generators/__tests__/module-facts.local-reference.test.ts +13 -0
  258. package/src/lib/generators/__tests__/module-override-targets.test.ts +2 -3
  259. package/src/lib/generators/__tests__/module-subset.test.ts +1 -1
  260. package/src/lib/generators/__tests__/openapi.test.ts +147 -10
  261. package/src/lib/generators/__tests__/structural-contracts.test.ts +2 -2
  262. package/src/lib/generators/__tests__/web-research-adapters.test.ts +298 -87
  263. package/src/lib/generators/ast/writers.ts +6 -1
  264. package/src/lib/generators/cache-providers.ts +111 -0
  265. package/src/lib/generators/extension.ts +2 -0
  266. package/src/lib/generators/extensions/agent-files.ts +1 -0
  267. package/src/lib/generators/form-section-ast.ts +166 -0
  268. package/src/lib/generators/form-section-extension-compiler.ts +632 -0
  269. package/src/lib/generators/form-section-extension-source.ts +308 -0
  270. package/src/lib/generators/form-section-runtime-revisions.ts +211 -0
  271. package/src/lib/generators/form-sections.ts +896 -0
  272. package/src/lib/generators/index.ts +1 -0
  273. package/src/lib/generators/module-entities.ts +22 -4
  274. package/src/lib/generators/module-extension-facts.ts +1 -0
  275. package/src/lib/generators/module-facts.ts +40 -0
  276. package/src/lib/generators/module-override-targets.ts +19 -0
  277. package/src/lib/generators/module-registry.ts +246 -202
  278. package/src/lib/generators/openapi.ts +65 -20
  279. package/src/lib/generators/web-research-adapters.ts +76 -21
  280. package/src/lib/in-process-generate-watcher.ts +151 -96
  281. package/src/lib/post-generate-invalidation.ts +28 -1
  282. package/src/lib/resolver.ts +218 -0
  283. package/src/lib/single-instance-strategy-guard.ts +51 -1
  284. package/src/mercato.ts +117 -57
  285. package/dist/agentic/guides/modules/dashboards/incoming-installed-contributions.md +0 -11
@@ -1,3 +1,4 @@
1
+ import { planGenerateWatchChanges } from "./generate-watch-plan.js";
1
2
  const MIN_POLL_MS = 250;
2
3
  const DEFAULT_POLL_MS = 1e3;
3
4
  function resolvePollMs(value) {
@@ -9,111 +10,137 @@ function startInProcessGenerateWatcher(options) {
9
10
  const logger = options.logger ?? console;
10
11
  const quiet = options.quiet === true;
11
12
  const pollMs = resolvePollMs(options.pollMs);
12
- const skipInitial = options.skipInitial === true;
13
- const { changeSignal, computeStructureChecksum, runGenerators } = options;
13
+ const { changeSignal, computeStructureChecksum, runGenerators, incremental } = options;
14
14
  let stopping = false;
15
15
  let pollTimer = null;
16
- let activeCycle = null;
17
- let running = false;
18
- let pendingReason = null;
19
- let previousChecksum = "";
16
+ let previousChecksum;
17
+ let previousSnapshot;
20
18
  let observedChangeVersion = -1;
21
- let doneResolve = null;
19
+ let attemptedChangeVersion = -1;
20
+ let attemptedChecksum;
21
+ let attemptedUncertaintyKey;
22
+ let hasAttemptedCapture = false;
23
+ let retryReason;
24
+ let doneResolve = () => {
25
+ };
22
26
  const done = new Promise((resolve) => {
23
27
  doneResolve = resolve;
24
28
  });
25
- async function runOnce(reason) {
29
+ async function captureAndGenerate(initial, refreshSubscriptions = true) {
30
+ const changeVersion = changeSignal?.currentVersion() ?? 0;
31
+ const hadPriorAttempt = hasAttemptedCapture;
32
+ const priorAttemptVersion = attemptedChangeVersion;
33
+ const priorAttemptChecksum = attemptedChecksum;
34
+ const priorAttemptUncertaintyKey = attemptedUncertaintyKey;
35
+ hasAttemptedCapture = true;
36
+ attemptedChangeVersion = changeVersion;
37
+ let candidate;
38
+ let checksum;
39
+ try {
40
+ candidate = incremental ? await incremental.capture() : void 0;
41
+ checksum = candidate?.checksum ?? await computeStructureChecksum();
42
+ } catch (error) {
43
+ attemptedChecksum = void 0;
44
+ attemptedUncertaintyKey = "capture failed";
45
+ retryReason = "retry after uncertain structure snapshot";
46
+ throw error;
47
+ }
48
+ if (stopping) return;
49
+ if (refreshSubscriptions) await changeSignal?.refresh();
26
50
  if (stopping) return;
27
- if (running) {
28
- pendingReason = reason;
51
+ const uncertaintyKey = candidate?.fullReasons.join("\0");
52
+ const inputChangedSinceAttempt = !hadPriorAttempt || changeVersion !== priorAttemptVersion || checksum !== priorAttemptChecksum || uncertaintyKey !== priorAttemptUncertaintyKey;
53
+ attemptedChecksum = checksum;
54
+ attemptedUncertaintyKey = uncertaintyKey;
55
+ const skipInitial = initial && options.skipInitial === true;
56
+ const changed = checksum !== previousChecksum;
57
+ const uncertain = Boolean(candidate?.fullReasons.length);
58
+ const eventReason = changeSignal?.fullGenerationReasonSince?.(observedChangeVersion);
59
+ const shouldGenerate = !skipInitial && (retryReason ? inputChangedSinceAttempt : initial || changed || uncertain || Boolean(eventReason));
60
+ if (shouldGenerate) {
61
+ let plan;
62
+ if (incremental && candidate) {
63
+ const fallbackReason = initial ? "initial generation" : retryReason ?? (!previousSnapshot ? "no successful snapshot" : changeSignal?.usesPollingFallback() ? "filesystem watching unavailable; polling fallback" : eventReason);
64
+ const candidatePlan = previousSnapshot ? incremental.plan(previousSnapshot, candidate) : void 0;
65
+ plan = fallbackReason ? planGenerateWatchChanges(candidatePlan?.changes ?? [], [fallbackReason, ...candidate.fullReasons]) : candidatePlan;
66
+ }
67
+ if (plan?.mode !== "none") {
68
+ const reason = initial ? "initial" : retryReason ?? "structure change";
69
+ if (!quiet) {
70
+ const detail = plan ? `; categories=${[...new Set(plan.changes.map((change) => change.category))].join(",") || "all"}; groups=${plan.groups.join(",")}${plan.reasons.length ? `; reasons=${plan.reasons.join("; ")}` : ""}` : "";
71
+ logger.log(`[generate:watch] Regenerating (${reason}${detail})...`);
72
+ }
73
+ try {
74
+ if (plan) await runGenerators(reason, plan);
75
+ else await runGenerators(reason);
76
+ } catch (error) {
77
+ retryReason = "retry after failed generation";
78
+ const message = error instanceof Error ? error.message : String(error);
79
+ logger.error(`[generate:watch] Generation failed: ${message}`);
80
+ return;
81
+ }
82
+ if (incremental && !stopping) await changeSignal?.refresh();
83
+ if (!quiet) logger.log("[generate:watch] Generators completed.");
84
+ }
85
+ } else if (retryReason) {
86
+ return;
87
+ }
88
+ if (uncertain) {
89
+ retryReason = "retry after uncertain structure snapshot";
29
90
  return;
30
91
  }
31
- running = true;
92
+ previousChecksum = checksum;
93
+ previousSnapshot = candidate;
94
+ observedChangeVersion = changeVersion;
95
+ retryReason = void 0;
96
+ }
97
+ async function poll() {
32
98
  try {
33
- if (!quiet) {
34
- logger.log(`[generate:watch] Regenerating (${reason})...`);
35
- }
36
- await runGenerators(reason);
37
- if (!quiet) {
38
- logger.log("[generate:watch] Generators completed.");
99
+ if (stopping) return;
100
+ const eventGatedIdle = hasAttemptedCapture && changeSignal && !changeSignal.usesPollingFallback() && changeSignal.currentVersion() === attemptedChangeVersion;
101
+ if (eventGatedIdle) {
102
+ if (!changeSignal.hasSkippedTargets?.()) return;
103
+ await changeSignal.refresh();
104
+ if (stopping) return;
105
+ const stillAtAttemptedVersion = changeSignal.currentVersion() === attemptedChangeVersion;
106
+ if (stillAtAttemptedVersion && (retryReason || changeSignal.hasSkippedTargets?.())) return;
39
107
  }
108
+ await captureAndGenerate(false, !eventGatedIdle);
40
109
  } catch (error) {
41
110
  const message = error instanceof Error ? error.message : String(error);
42
- logger.error(`[generate:watch] Generation failed: ${message}`);
111
+ logger.error(`[generate:watch] Poll cycle failed: ${message}`);
43
112
  } finally {
44
- running = false;
45
- if (pendingReason && !stopping) {
46
- const queued = pendingReason;
47
- pendingReason = null;
48
- await runOnce(queued);
49
- }
113
+ scheduleNext();
50
114
  }
51
115
  }
52
116
  function scheduleNext() {
53
117
  if (stopping) return;
54
118
  pollTimer = setTimeout(() => {
55
- activeCycle = (async () => {
56
- if (stopping) return;
57
- try {
58
- const changeVersion = changeSignal?.currentVersion() ?? 0;
59
- const eventGatedIdle = Boolean(
60
- changeSignal && !changeSignal.usesPollingFallback() && changeVersion === observedChangeVersion
61
- );
62
- let refreshedSkippedTargets = false;
63
- if (eventGatedIdle) {
64
- if (!changeSignal?.hasSkippedTargets?.()) return;
65
- await changeSignal.refresh();
66
- refreshedSkippedTargets = true;
67
- if (changeSignal.hasSkippedTargets?.()) return;
68
- }
69
- const nextChecksum = await computeStructureChecksum();
70
- observedChangeVersion = changeVersion;
71
- if (!refreshedSkippedTargets) {
72
- await changeSignal?.refresh();
73
- }
74
- if (nextChecksum !== previousChecksum) {
75
- previousChecksum = nextChecksum;
76
- await runOnce("structure change");
77
- }
78
- } catch (error) {
79
- const message = error instanceof Error ? error.message : String(error);
80
- logger.error(`[generate:watch] Poll cycle failed: ${message}`);
81
- } finally {
82
- if (!stopping) scheduleNext();
83
- }
84
- })();
119
+ pollTimer = null;
120
+ activeCycle = poll();
85
121
  }, pollMs);
86
122
  pollTimer.unref?.();
87
123
  }
88
- activeCycle = (async () => {
124
+ let activeCycle = (async () => {
89
125
  try {
90
126
  await changeSignal?.refresh();
91
127
  if (stopping) return;
92
- const initialChangeVersion = changeSignal?.currentVersion() ?? 0;
93
- if (!skipInitial) {
94
- await runOnce("initial");
95
- }
96
- if (stopping) return;
97
- previousChecksum = await computeStructureChecksum();
98
- observedChangeVersion = initialChangeVersion;
99
- if (!quiet) {
100
- if (skipInitial) {
128
+ await captureAndGenerate(true, Boolean(incremental));
129
+ if (!quiet && !stopping) {
130
+ if (options.skipInitial) {
101
131
  logger.log("[generate:watch] Skipping initial regeneration and watching the current generated state.");
102
132
  }
103
133
  logger.log(`[generate:watch] Watching structural module files with a ${pollMs}ms debounce (in-process).`);
104
134
  }
105
- scheduleNext();
106
135
  } catch (error) {
107
136
  const message = error instanceof Error ? error.message : String(error);
108
137
  logger.error(`[generate:watch] Initial setup failed: ${message}`);
138
+ } finally {
109
139
  scheduleNext();
110
140
  }
111
141
  })();
112
142
  async function close() {
113
- if (stopping) {
114
- await done;
115
- return;
116
- }
143
+ if (stopping) return done;
117
144
  stopping = true;
118
145
  if (pollTimer) {
119
146
  clearTimeout(pollTimer);
@@ -123,14 +150,10 @@ function startInProcessGenerateWatcher(options) {
123
150
  await activeCycle;
124
151
  await changeSignal?.close();
125
152
  } finally {
126
- doneResolve?.();
127
- doneResolve = null;
153
+ doneResolve();
128
154
  }
129
155
  }
130
- return {
131
- done,
132
- close
133
- };
156
+ return { done, close };
134
157
  }
135
158
  export {
136
159
  startInProcessGenerateWatcher
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/in-process-generate-watcher.ts"],
4
- "sourcesContent": ["/**\n * In-process generate watcher.\n *\n * Coalesces filesystem events on a configurable interval, then verifies them\n * with the existing structural fingerprint before invoking the generator.\n * If filesystem watching is unavailable, it falls back to fingerprint polling.\n * The polling loop is identical to the legacy standalone watcher; the only\n * difference is that it now runs inside whatever process calls it\n * (typically `mercato server dev`), so the dev runtime no longer needs a\n * sidecar `mercato generate watch` Node process.\n *\n * Contract preserved from the prior standalone watcher:\n * - Default debounce/fallback poll interval 1000 ms (minimum 250 ms).\n * - One initial generator run unless `skipInitial` is true.\n * - Concurrent regeneration requests are coalesced (running + pending).\n * - Generator errors are logged but never crash the watcher.\n * - The polling timer uses `.unref()` so it never blocks process exit.\n */\n\nexport type GenerateWatcherLogger = Pick<Console, 'log' | 'error'>\n\nexport type GenerateWatcherChangeSignal = {\n /** Monotonic event generation. Changes indicate that a checksum may be stale. */\n currentVersion(): number\n /** Refresh filesystem subscriptions after module configuration changes. */\n refresh(): Promise<void> | void\n /** Whether configured roots are missing and should be retried on idle polls. */\n hasSkippedTargets?(): boolean\n /** When true, preserve the legacy full-checksum-on-every-poll behavior. */\n usesPollingFallback(): boolean\n /** Close filesystem subscriptions. Idempotent. */\n close(): Promise<void> | void\n}\n\nexport type GenerateWatcherOptions = {\n /**\n * Function that returns the current structural fingerprint of the module\n * tree. The watcher re-runs `runGenerators` whenever this value changes.\n */\n computeStructureChecksum: () => Promise<string> | string\n /** Optional event signal that avoids full checksum work during idle polls. */\n changeSignal?: GenerateWatcherChangeSignal\n /**\n * Function that performs the actual regeneration work. Called once on\n * startup (unless `skipInitial`) and again whenever the checksum changes.\n * The `reason` argument is suitable for logging (`'initial'`,\n * `'structure change'`, `'queued change'`).\n */\n runGenerators: (reason: string) => Promise<void>\n /** Poll interval in milliseconds. Defaults to 1000. Clamped to >= 250. */\n pollMs?: number\n /** Skip the initial regeneration on startup. Defaults to false. */\n skipInitial?: boolean\n /** Suppress informational logs. Errors are always logged. */\n quiet?: boolean\n /** Logger override. Defaults to `console`. */\n logger?: GenerateWatcherLogger\n}\n\nexport type GenerateWatcherHandle = {\n /** Resolves when the watcher loop has stopped (after `close()`). */\n readonly done: Promise<void>\n /** Stop polling, drain the active cycle, and resolve `done`. Idempotent. */\n close(): Promise<void>\n}\n\nconst MIN_POLL_MS = 250\nconst DEFAULT_POLL_MS = 1000\n\nfunction resolvePollMs(value: number | undefined): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) return DEFAULT_POLL_MS\n const numeric = Math.floor(value)\n return numeric >= MIN_POLL_MS ? numeric : DEFAULT_POLL_MS\n}\n\n/**\n * Start an in-process generate watcher. The returned handle exposes a\n * `close()` to stop polling and a `done` promise that resolves once the\n * watcher loop has finished.\n */\nexport function startInProcessGenerateWatcher(\n options: GenerateWatcherOptions,\n): GenerateWatcherHandle {\n const logger = options.logger ?? console\n const quiet = options.quiet === true\n const pollMs = resolvePollMs(options.pollMs)\n const skipInitial = options.skipInitial === true\n const { changeSignal, computeStructureChecksum, runGenerators } = options\n\n let stopping = false\n let pollTimer: ReturnType<typeof setTimeout> | null = null\n let activeCycle: Promise<void> | null = null\n let running = false\n let pendingReason: string | null = null\n let previousChecksum = ''\n let observedChangeVersion = -1\n let doneResolve: (() => void) | null = null\n const done = new Promise<void>((resolve) => {\n doneResolve = resolve\n })\n\n async function runOnce(reason: string): Promise<void> {\n if (stopping) return\n if (running) {\n pendingReason = reason\n return\n }\n running = true\n try {\n if (!quiet) {\n logger.log(`[generate:watch] Regenerating (${reason})...`)\n }\n await runGenerators(reason)\n if (!quiet) {\n logger.log('[generate:watch] Generators completed.')\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`[generate:watch] Generation failed: ${message}`)\n } finally {\n running = false\n if (pendingReason && !stopping) {\n const queued = pendingReason\n pendingReason = null\n await runOnce(queued)\n }\n }\n }\n\n function scheduleNext(): void {\n if (stopping) return\n pollTimer = setTimeout(() => {\n activeCycle = (async () => {\n if (stopping) return\n try {\n const changeVersion = changeSignal?.currentVersion() ?? 0\n const eventGatedIdle = Boolean(\n changeSignal\n && !changeSignal.usesPollingFallback()\n && changeVersion === observedChangeVersion\n )\n let refreshedSkippedTargets = false\n if (eventGatedIdle) {\n if (!changeSignal?.hasSkippedTargets?.()) return\n await changeSignal.refresh()\n refreshedSkippedTargets = true\n if (changeSignal.hasSkippedTargets?.()) return\n }\n const nextChecksum = await computeStructureChecksum()\n observedChangeVersion = changeVersion\n if (!refreshedSkippedTargets) {\n await changeSignal?.refresh()\n }\n if (nextChecksum !== previousChecksum) {\n previousChecksum = nextChecksum\n await runOnce('structure change')\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`[generate:watch] Poll cycle failed: ${message}`)\n } finally {\n if (!stopping) scheduleNext()\n }\n })()\n }, pollMs)\n pollTimer.unref?.()\n }\n\n activeCycle = (async () => {\n try {\n await changeSignal?.refresh()\n if (stopping) return\n const initialChangeVersion = changeSignal?.currentVersion() ?? 0\n if (!skipInitial) {\n await runOnce('initial')\n }\n if (stopping) return\n previousChecksum = await computeStructureChecksum()\n observedChangeVersion = initialChangeVersion\n if (!quiet) {\n if (skipInitial) {\n logger.log('[generate:watch] Skipping initial regeneration and watching the current generated state.')\n }\n logger.log(`[generate:watch] Watching structural module files with a ${pollMs}ms debounce (in-process).`)\n }\n scheduleNext()\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`[generate:watch] Initial setup failed: ${message}`)\n // Even if the initial bootstrap fails, schedule polling so a later\n // checksum recovery still picks up the next change on disk.\n scheduleNext()\n }\n })()\n\n async function close(): Promise<void> {\n if (stopping) {\n await done\n return\n }\n stopping = true\n if (pollTimer) {\n clearTimeout(pollTimer)\n pollTimer = null\n }\n // Drain before closing subscriptions: an in-flight capture can refresh\n // them, and a generator child must exit before dev restarts its group.\n try {\n await activeCycle\n await changeSignal?.close()\n } finally {\n doneResolve?.()\n doneResolve = null\n }\n }\n\n return {\n done,\n close,\n }\n}\n"],
5
- "mappings": "AAkEA,MAAM,cAAc;AACpB,MAAM,kBAAkB;AAExB,SAAS,cAAc,OAAmC;AACxD,MAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,EAAG,QAAO;AACjE,QAAM,UAAU,KAAK,MAAM,KAAK;AAChC,SAAO,WAAW,cAAc,UAAU;AAC5C;AAOO,SAAS,8BACd,SACuB;AACvB,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,QAAQ,QAAQ,UAAU;AAChC,QAAM,SAAS,cAAc,QAAQ,MAAM;AAC3C,QAAM,cAAc,QAAQ,gBAAgB;AAC5C,QAAM,EAAE,cAAc,0BAA0B,cAAc,IAAI;AAElE,MAAI,WAAW;AACf,MAAI,YAAkD;AACtD,MAAI,cAAoC;AACxC,MAAI,UAAU;AACd,MAAI,gBAA+B;AACnC,MAAI,mBAAmB;AACvB,MAAI,wBAAwB;AAC5B,MAAI,cAAmC;AACvC,QAAM,OAAO,IAAI,QAAc,CAAC,YAAY;AAC1C,kBAAc;AAAA,EAChB,CAAC;AAED,iBAAe,QAAQ,QAA+B;AACpD,QAAI,SAAU;AACd,QAAI,SAAS;AACX,sBAAgB;AAChB;AAAA,IACF;AACA,cAAU;AACV,QAAI;AACF,UAAI,CAAC,OAAO;AACV,eAAO,IAAI,kCAAkC,MAAM,MAAM;AAAA,MAC3D;AACA,YAAM,cAAc,MAAM;AAC1B,UAAI,CAAC,OAAO;AACV,eAAO,IAAI,wCAAwC;AAAA,MACrD;AAAA,IACF,SAAS,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UAAI,CAAC,aAAa;AAChB,cAAM,QAAQ,SAAS;AAAA,MACzB;AACA,UAAI,SAAU;AACd,yBAAmB,MAAM,yBAAyB;AAClD,8BAAwB;AACxB,UAAI,CAAC,OAAO;AACV,YAAI,aAAa;AACf,iBAAO,IAAI,0FAA0F;AAAA,QACvG;AACA,eAAO,IAAI,4DAA4D,MAAM,2BAA2B;AAAA,MAC1G;AACA,mBAAa;AAAA,IACf,SAAS,OAAO;AACd,YAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,aAAO,MAAM,0CAA0C,OAAO,EAAE;AAGhE,mBAAa;AAAA,IACf;AAAA,EACF,GAAG;AAEH,iBAAe,QAAuB;AACpC,QAAI,UAAU;AACZ,YAAM;AACN;AAAA,IACF;AACA,eAAW;AACX,QAAI,WAAW;AACb,mBAAa,SAAS;AACtB,kBAAY;AAAA,IACd;AAGA,QAAI;AACF,YAAM;AACN,YAAM,cAAc,MAAM;AAAA,IAC5B,UAAE;AACA,oBAAc;AACd,oBAAc;AAAA,IAChB;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["/**\n * In-process generate watcher.\n *\n * Coalesces filesystem events before comparing the current module structure\n * with the last successfully generated snapshot. Failed or uncertain\n * candidates remain unacknowledged, but are retried only after a new input\n * event (or a newly observed polling-fallback snapshot). Capturing before\n * generation leaves edits made during a run dirty for the next serial poll.\n *\n * Contract preserved from the prior standalone watcher:\n * - Default debounce/fallback poll interval 1000 ms (minimum 250 ms).\n * - One initial generator run unless `skipInitial` is true.\n * - Concurrent regeneration requests are coalesced (running + pending).\n * - Generator errors are logged but never crash the watcher.\n * - The polling timer uses `.unref()` so it never blocks process exit.\n */\nimport { planGenerateWatchChanges } from './generate-watch-plan'\nimport type { GenerateWatchPlan, GenerateWatchSnapshot } from './generate-watch-plan'\n\nexport type GenerateWatcherLogger = Pick<Console, 'log' | 'error'>\n\nexport type GenerateWatcherChangeSignal = {\n /** Monotonic event generation. Changes indicate that a checksum may be stale. */\n currentVersion(): number\n /** Explain events without a usable filename since a captured event version. */\n fullGenerationReasonSince?(version: number): string | undefined\n /** Refresh filesystem subscriptions after module configuration changes. */\n refresh(): Promise<void> | void\n /** Whether configured roots are missing and should be retried on idle polls. */\n hasSkippedTargets?(): boolean\n /** When true, preserve the legacy full-checksum-on-every-poll behavior. */\n usesPollingFallback(): boolean\n /** Close filesystem subscriptions. Idempotent. */\n close(): Promise<void> | void\n}\n\nexport type GenerateWatcherOptions = {\n /**\n * Function that returns the current structural fingerprint of the module\n * tree. The watcher re-runs `runGenerators` whenever this value changes.\n */\n computeStructureChecksum: () => Promise<string> | string\n /** Optional event signal that avoids full checksum work during idle polls. */\n changeSignal?: GenerateWatcherChangeSignal\n /** Opt in to category-aware planning; legacy checksum-only callers stay valid. */\n incremental?: {\n capture(): Promise<GenerateWatchSnapshot> | GenerateWatchSnapshot\n plan(previous: GenerateWatchSnapshot, next: GenerateWatchSnapshot): GenerateWatchPlan\n }\n /**\n * Function that performs the actual regeneration work. Called once on\n * startup (unless `skipInitial`) and again whenever the input changes.\n * After a failed or uncertain candidate, the next changed input is repaired\n * with a full generation. The `reason` argument is suitable for logging\n * (`'initial'`, `'structure change'`, `'retry after failed generation'`,\n * or `'retry after uncertain structure snapshot'`).\n */\n runGenerators: (reason: string, plan?: GenerateWatchPlan) => Promise<void>\n /** Poll interval in milliseconds. Defaults to 1000. Clamped to >= 250. */\n pollMs?: number\n /** Skip the initial regeneration on startup. Defaults to false. */\n skipInitial?: boolean\n /** Suppress informational logs. Errors are always logged. */\n quiet?: boolean\n /** Logger override. Defaults to `console`. */\n logger?: GenerateWatcherLogger\n}\n\nexport type GenerateWatcherHandle = {\n /** Resolves when the watcher loop has stopped (after `close()`). */\n readonly done: Promise<void>\n /** Stop polling, drain the active cycle, and resolve `done`. Idempotent. */\n close(): Promise<void>\n}\n\nconst MIN_POLL_MS = 250\nconst DEFAULT_POLL_MS = 1000\n\nfunction resolvePollMs(value: number | undefined): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) return DEFAULT_POLL_MS\n const numeric = Math.floor(value)\n return numeric >= MIN_POLL_MS ? numeric : DEFAULT_POLL_MS\n}\n\n/**\n * Start an in-process generate watcher. The returned handle exposes a\n * `close()` to stop polling and a `done` promise that resolves once the\n * watcher loop has finished.\n */\nexport function startInProcessGenerateWatcher(\n options: GenerateWatcherOptions,\n): GenerateWatcherHandle {\n const logger = options.logger ?? console\n const quiet = options.quiet === true\n const pollMs = resolvePollMs(options.pollMs)\n const { changeSignal, computeStructureChecksum, runGenerators, incremental } = options\n let stopping = false\n let pollTimer: ReturnType<typeof setTimeout> | null = null\n let previousChecksum: string | undefined\n let previousSnapshot: GenerateWatchSnapshot | undefined\n let observedChangeVersion = -1\n let attemptedChangeVersion = -1\n let attemptedChecksum: string | undefined\n let attemptedUncertaintyKey: string | undefined\n let hasAttemptedCapture = false\n let retryReason: string | undefined\n let doneResolve: () => void = () => {}\n const done = new Promise<void>((resolve) => { doneResolve = resolve })\n\n async function captureAndGenerate(initial: boolean, refreshSubscriptions = true): Promise<void> {\n // This version belongs to the candidate, not to the state after generation.\n const changeVersion = changeSignal?.currentVersion() ?? 0\n const hadPriorAttempt = hasAttemptedCapture\n const priorAttemptVersion = attemptedChangeVersion\n const priorAttemptChecksum = attemptedChecksum\n const priorAttemptUncertaintyKey = attemptedUncertaintyKey\n hasAttemptedCapture = true\n attemptedChangeVersion = changeVersion\n\n let candidate: GenerateWatchSnapshot | undefined\n let checksum: string\n try {\n candidate = incremental ? await incremental.capture() : undefined\n checksum = candidate?.checksum ?? await computeStructureChecksum()\n } catch (error) {\n // A later authoritative capture must be treated as a new candidate even\n // when it has the same checksum as the snapshot preceding this failure.\n attemptedChecksum = undefined\n attemptedUncertaintyKey = 'capture failed'\n retryReason = 'retry after uncertain structure snapshot'\n throw error\n }\n if (stopping) return\n if (refreshSubscriptions) await changeSignal?.refresh()\n if (stopping) return\n\n const uncertaintyKey = candidate?.fullReasons.join('\\u0000')\n const inputChangedSinceAttempt = !hadPriorAttempt\n || changeVersion !== priorAttemptVersion\n || checksum !== priorAttemptChecksum\n || uncertaintyKey !== priorAttemptUncertaintyKey\n attemptedChecksum = checksum\n attemptedUncertaintyKey = uncertaintyKey\n\n const skipInitial = initial && options.skipInitial === true\n const changed = checksum !== previousChecksum\n const uncertain = Boolean(candidate?.fullReasons.length)\n const eventReason = changeSignal?.fullGenerationReasonSince?.(observedChangeVersion)\n const shouldGenerate = !skipInitial && (retryReason\n ? inputChangedSinceAttempt\n : initial || changed || uncertain || Boolean(eventReason))\n if (shouldGenerate) {\n let plan: GenerateWatchPlan | undefined\n if (incremental && candidate) {\n const fallbackReason = initial\n ? 'initial generation'\n : retryReason\n ?? (!previousSnapshot\n ? 'no successful snapshot'\n : changeSignal?.usesPollingFallback()\n ? 'filesystem watching unavailable; polling fallback'\n : eventReason)\n const candidatePlan = previousSnapshot ? incremental.plan(previousSnapshot, candidate) : undefined\n plan = fallbackReason\n ? planGenerateWatchChanges(candidatePlan?.changes ?? [], [fallbackReason, ...candidate.fullReasons])\n : candidatePlan\n }\n if (plan?.mode !== 'none') {\n const reason = initial ? 'initial' : retryReason ?? 'structure change'\n if (!quiet) {\n const detail = plan\n ? `; categories=${[...new Set(plan.changes.map((change) => change.category))].join(',') || 'all'}; groups=${plan.groups.join(',')}${plan.reasons.length ? `; reasons=${plan.reasons.join('; ')}` : ''}`\n : ''\n logger.log(`[generate:watch] Regenerating (${reason}${detail})...`)\n }\n try {\n // Do not add an undefined argument to the legacy callback contract.\n if (plan) await runGenerators(reason, plan)\n else await runGenerators(reason)\n } catch (error) {\n retryReason = 'retry after failed generation'\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`[generate:watch] Generation failed: ${message}`)\n return\n }\n // A successful bundle can discover new external dependencies to watch.\n if (incremental && !stopping) await changeSignal?.refresh()\n if (!quiet) logger.log('[generate:watch] Generators completed.')\n }\n } else if (retryReason) {\n // Keep the failed/uncertain candidate unacknowledged without retrying it.\n return\n }\n // Only successful generation (or a verified no-op) acknowledges this input.\n if (uncertain) {\n retryReason = 'retry after uncertain structure snapshot'\n return\n }\n previousChecksum = checksum\n previousSnapshot = candidate\n observedChangeVersion = changeVersion\n retryReason = undefined\n }\n\n async function poll(): Promise<void> {\n try {\n if (stopping) return\n const eventGatedIdle = hasAttemptedCapture\n && changeSignal\n && !changeSignal.usesPollingFallback()\n && changeSignal.currentVersion() === attemptedChangeVersion\n if (eventGatedIdle) {\n if (!changeSignal.hasSkippedTargets?.()) return\n await changeSignal.refresh()\n if (stopping) return\n const stillAtAttemptedVersion = changeSignal.currentVersion() === attemptedChangeVersion\n // A pending repair is strictly event-gated. Normal idle polling may\n // still discover a formerly missing root even if the signal provider\n // cannot attribute that discovery to a filesystem event.\n if (stillAtAttemptedVersion\n && (retryReason || changeSignal.hasSkippedTargets?.())) return\n }\n await captureAndGenerate(false, !eventGatedIdle)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`[generate:watch] Poll cycle failed: ${message}`)\n } finally {\n scheduleNext()\n }\n }\n\n function scheduleNext(): void {\n if (stopping) return\n pollTimer = setTimeout(() => {\n pollTimer = null\n activeCycle = poll()\n }, pollMs)\n pollTimer.unref?.()\n }\n\n let activeCycle = (async () => {\n try {\n await changeSignal?.refresh()\n if (stopping) return\n await captureAndGenerate(true, Boolean(incremental))\n if (!quiet && !stopping) {\n if (options.skipInitial) {\n logger.log('[generate:watch] Skipping initial regeneration and watching the current generated state.')\n }\n logger.log(`[generate:watch] Watching structural module files with a ${pollMs}ms debounce (in-process).`)\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n logger.error(`[generate:watch] Initial setup failed: ${message}`)\n } finally {\n scheduleNext()\n }\n })()\n\n async function close(): Promise<void> {\n if (stopping) return done\n stopping = true\n if (pollTimer) {\n clearTimeout(pollTimer)\n pollTimer = null\n }\n try {\n await activeCycle\n await changeSignal?.close()\n } fin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0FAA0F;AAAA,QACvG;AACA,eAAO,IAAI,4DAA4D,MAAM,2BAA2B;AAAA,MAC1G;AAAA,IACF,SAAS,OAAO;AACd,YAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,aAAO,MAAM,0CAA0C,OAAO,EAAE;AAAA,IAClE,UAAE;AACA,mBAAa;AAAA,IACf;AAAA,EACF,GAAG;AAEH,iBAAe,QAAuB;AACpC,QAAI,SAAU,QAAO;AACrB,eAAW;AACX,QAAI,WAAW;AACb,mBAAa,SAAS;AACtB,kBAAY;AAAA,IACd;AACA,QAAI;AACF,YAAM;AACN,YAAM,cAAc,MAAM;AAAA,IAC5B,UAAE;AACA,kBAAY;AAAA,IACd;AAAA,EACF;AAEA,SAAO,EAAE,MAAM,MAAM;AACvB;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,13 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { purgeConfiguredCachePatternsAcrossTenantScopes } from "@open-mercato/shared/lib/cache/maintenance";
4
+ import {
5
+ CacheProviderError,
6
+ isCacheProviderError,
7
+ prepareCacheProviderSelection,
8
+ readSelectedCacheProviderId
9
+ } from "@open-mercato/shared/lib/cache/providers";
10
+ import { loadCacheProviderManifest } from "./cache-provider-manifest.js";
4
11
  const STRUCTURAL_CACHE_PATTERNS = [
5
12
  "nav:*",
6
13
  "crud|*|*|*/admin/nav|*",
@@ -21,6 +28,18 @@ function touchGeneratedFiles(appDir) {
21
28
  }
22
29
  return touched;
23
30
  }
31
+ async function purgeStructuralCacheEntries(appDir) {
32
+ const providerId = readSelectedCacheProviderId(process.env);
33
+ if (!providerId) return purgeConfiguredCachePatternsAcrossTenantScopes(STRUCTURAL_CACHE_PATTERNS);
34
+ try {
35
+ await loadCacheProviderManifest(appDir);
36
+ await prepareCacheProviderSelection();
37
+ return await purgeConfiguredCachePatternsAcrossTenantScopes(STRUCTURAL_CACHE_PATTERNS);
38
+ } catch (error) {
39
+ if (isCacheProviderError(error)) throw error;
40
+ throw new CacheProviderError("unavailable", "Cache provider structural purge failed", { cause: error });
41
+ }
42
+ }
24
43
  async function runPostGenerateStructuralInvalidation(appDir) {
25
44
  let cacheEntriesDeleted = 0;
26
45
  let generatedFilesTouched = [];
@@ -32,7 +51,7 @@ async function runPostGenerateStructuralInvalidation(appDir) {
32
51
  generatedFilesError = error;
33
52
  }
34
53
  try {
35
- cacheEntriesDeleted = await purgeConfiguredCachePatternsAcrossTenantScopes(STRUCTURAL_CACHE_PATTERNS);
54
+ cacheEntriesDeleted = await purgeStructuralCacheEntries(appDir);
36
55
  } catch (error) {
37
56
  cacheError = error;
38
57
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/post-generate-invalidation.ts"],
4
- "sourcesContent": ["import fs from 'node:fs'\nimport path from 'node:path'\nimport { purgeConfiguredCachePatternsAcrossTenantScopes } from '@open-mercato/shared/lib/cache/maintenance'\n\nconst STRUCTURAL_CACHE_PATTERNS = [\n 'nav:*',\n 'crud|*|*|*/admin/nav|*',\n 'crud|*|*|*/portal/nav|*',\n]\nconst TOUCHABLE_GENERATED_FILE_PATTERN = /\\.generated(?:\\.[a-z0-9]+)?(?:\\.ts|\\.checksum)$/i\n\nexport type PostGenerateStructuralInvalidationResult = {\n cacheEntriesDeleted: number\n generatedFilesTouched: string[]\n cacheError: unknown | null\n generatedFilesError: unknown | null\n}\n\nfunction touchGeneratedFiles(appDir: string): string[] {\n const generatedDir = path.join(appDir, '.mercato', 'generated')\n if (!fs.existsSync(generatedDir) || !fs.statSync(generatedDir).isDirectory()) return []\n\n const touched: string[] = []\n // `utimes` advances mtime without opening the file for writing. Rewriting the\n // identical bytes would truncate multi-megabyte registries first, and Turbopack\n // reads them concurrently during a dev compile \u2014 it can observe the empty window.\n const touchedAt = new Date()\n const entries = fs.readdirSync(generatedDir, { withFileTypes: true })\n .sort((left, right) => left.name.localeCompare(right.name))\n for (const entry of entries) {\n if (!entry.isFile() || !TOUCHABLE_GENERATED_FILE_PATTERN.test(entry.name)) continue\n const filePath = path.join(generatedDir, entry.name)\n fs.utimesSync(filePath, touchedAt, touchedAt)\n touched.push(filePath)\n }\n return touched\n}\n\nexport async function runPostGenerateStructuralInvalidation(\n appDir: string,\n): Promise<PostGenerateStructuralInvalidationResult> {\n let cacheEntriesDeleted = 0\n let generatedFilesTouched: string[] = []\n let cacheError: unknown | null = null\n let generatedFilesError: unknown | null = null\n\n try {\n generatedFilesTouched = touchGeneratedFiles(appDir)\n } catch (error) {\n generatedFilesError = error\n }\n\n try {\n cacheEntriesDeleted = await purgeConfiguredCachePatternsAcrossTenantScopes(STRUCTURAL_CACHE_PATTERNS)\n } catch (error) {\n cacheError = error\n }\n\n return {\n cacheEntriesDeleted,\n generatedFilesTouched,\n cacheError,\n generatedFilesError,\n }\n}\n"],
5
- "mappings": "AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,sDAAsD;AAE/D,MAAM,4BAA4B;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,mCAAmC;AASzC,SAAS,oBAAoB,QAA0B;AACrD,QAAM,eAAe,KAAK,KAAK,QAAQ,YAAY,WAAW;AAC9D,MAAI,CAAC,GAAG,WAAW,YAAY,KAAK,CAAC,GAAG,SAAS,YAAY,EAAE,YAAY,EAAG,QAAO,CAAC;AAEtF,QAAM,UAAoB,CAAC;AAI3B,QAAM,YAAY,oBAAI,KAAK;AAC3B,QAAM,UAAU,GAAG,YAAY,cAAc,EAAE,eAAe,KAAK,CAAC,EACjE,KAAK,CAAC,MAAM,UAAU,KAAK,KAAK,cAAc,MAAM,IAAI,CAAC;AAC5D,aAAW,SAAS,SAAS;AAC3B,QAAI,CAAC,MAAM,OAAO,KAAK,CAAC,iCAAiC,KAAK,MAAM,IAAI,EAAG;AAC3E,UAAM,WAAW,KAAK,KAAK,cAAc,MAAM,IAAI;AACnD,OAAG,WAAW,UAAU,WAAW,SAAS;AAC5C,YAAQ,KAAK,QAAQ;AAAA,EACvB;AACA,SAAO;AACT;AAEA,eAAsB,sCACpB,QACmD;AACnD,MAAI,sBAAsB;AAC1B,MAAI,wBAAkC,CAAC;AACvC,MAAI,aAA6B;AACjC,MAAI,sBAAsC;AAE1C,MAAI;AACF,4BAAwB,oBAAoB,MAAM;AAAA,EACpD,SAAS,OAAO;AACd,0BAAsB;AAAA,EACxB;AAEA,MAAI;AACF,0BAAsB,MAAM,+CAA+C,yBAAyB;AAAA,EACtG,SAAS,OAAO;AACd,iBAAa;AAAA,EACf;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import fs from 'node:fs'\nimport path from 'node:path'\nimport { purgeConfiguredCachePatternsAcrossTenantScopes } from '@open-mercato/shared/lib/cache/maintenance'\nimport {\n CacheProviderError,\n isCacheProviderError,\n prepareCacheProviderSelection,\n readSelectedCacheProviderId,\n} from '@open-mercato/shared/lib/cache/providers'\nimport { loadCacheProviderManifest } from './cache-provider-manifest'\n\nconst STRUCTURAL_CACHE_PATTERNS = [\n 'nav:*',\n 'crud|*|*|*/admin/nav|*',\n 'crud|*|*|*/portal/nav|*',\n]\nconst TOUCHABLE_GENERATED_FILE_PATTERN = /\\.generated(?:\\.[a-z0-9]+)?(?:\\.ts|\\.checksum)$/i\n\nexport type PostGenerateStructuralInvalidationResult = {\n cacheEntriesDeleted: number\n generatedFilesTouched: string[]\n cacheError: unknown | null\n generatedFilesError: unknown | null\n}\n\nfunction touchGeneratedFiles(appDir: string): string[] {\n const generatedDir = path.join(appDir, '.mercato', 'generated')\n if (!fs.existsSync(generatedDir) || !fs.statSync(generatedDir).isDirectory()) return []\n\n const touched: string[] = []\n // `utimes` advances mtime without opening the file for writing. Rewriting the\n // identical bytes would truncate multi-megabyte registries first, and Turbopack\n // reads them concurrently during a dev compile \u2014 it can observe the empty window.\n const touchedAt = new Date()\n const entries = fs.readdirSync(generatedDir, { withFileTypes: true })\n .sort((left, right) => left.name.localeCompare(right.name))\n for (const entry of entries) {\n if (!entry.isFile() || !TOUCHABLE_GENERATED_FILE_PATTERN.test(entry.name)) continue\n const filePath = path.join(generatedDir, entry.name)\n fs.utimesSync(filePath, touchedAt, touchedAt)\n touched.push(filePath)\n }\n return touched\n}\n\n/**\n * Purge the structural patterns through the effective cache selection. With a registered\n * provider (`CACHE_PROVIDER`) the generated manifest is loaded and the same provider the app\n * resolves is prepared first; the purge closes its maintenance client itself. Provider\n * failures are reduced to a `CacheProviderError` so driver messages (which may embed\n * endpoints or credentials) never reach the CLI diagnostics.\n */\nasync function purgeStructuralCacheEntries(appDir: string): Promise<number> {\n const providerId = readSelectedCacheProviderId(process.env)\n if (!providerId) return purgeConfiguredCachePatternsAcrossTenantScopes(STRUCTURAL_CACHE_PATTERNS)\n try {\n await loadCacheProviderManifest(appDir)\n await prepareCacheProviderSelection()\n return await purgeConfiguredCachePatternsAcrossTenantScopes(STRUCTURAL_CACHE_PATTERNS)\n } catch (error) {\n if (isCacheProviderError(error)) throw error\n throw new CacheProviderError('unavailable', 'Cache provider structural purge failed', { cause: error })\n }\n}\n\nexport async function runPostGenerateStructuralInvalidation(\n appDir: string,\n): Promise<PostGenerateStructuralInvalidationResult> {\n let cacheEntriesDeleted = 0\n let generatedFilesTouched: string[] = []\n let cacheError: unknown | null = null\n let generatedFilesError: unknown | null = null\n\n try {\n generatedFilesTouched = touchGeneratedFiles(appDir)\n } catch (error) {\n generatedFilesError = error\n }\n\n try {\n cacheEntriesDeleted = await purgeStructuralCacheEntries(appDir)\n } catch (error) {\n cacheError = error\n }\n\n return {\n cacheEntriesDeleted,\n generatedFilesTouched,\n cacheError,\n generatedFilesError,\n }\n}\n"],
5
+ "mappings": "AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,sDAAsD;AAC/D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iCAAiC;AAE1C,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AEA,MAAI;AACF,0BAAsB,MAAM,4BAA4B,MAAM;AAAA,EAChE,SAAS,OAAO;AACd,iBAAa;AAAA,EACf;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -23,13 +23,87 @@ function pkgRootFor(rootDir, from, isMonorepo = true, appDir = rootDir) {
23
23
  }
24
24
  return resolveInstalledPackageRootWithRequire(packageName, appDir) ?? path.join(rootDir, "node_modules", packageName);
25
25
  }
26
+ function staticFormSectionOverrides(expression) {
27
+ const initializers = /* @__PURE__ */ new Map();
28
+ for (const statement of expression.getSourceFile().statements) {
29
+ if (!ts.isVariableStatement(statement) || !(statement.declarationList.flags & ts.NodeFlags.Const)) continue;
30
+ for (const declaration of statement.declarationList.declarations) {
31
+ if (ts.isIdentifier(declaration.name) && declaration.initializer) initializers.set(declaration.name.text, declaration.initializer);
32
+ }
33
+ }
34
+ function unwrap(value) {
35
+ const visited = /* @__PURE__ */ new Set();
36
+ while (true) {
37
+ if (ts.isAsExpression(value) || ts.isSatisfiesExpression(value) || ts.isParenthesizedExpression(value)) {
38
+ value = value.expression;
39
+ continue;
40
+ }
41
+ if (!ts.isIdentifier(value) || visited.has(value.text)) return value;
42
+ const resolved = initializers.get(value.text);
43
+ if (!resolved) return value;
44
+ visited.add(value.text);
45
+ value = resolved;
46
+ }
47
+ }
48
+ function fields(value, visited = /* @__PURE__ */ new Set()) {
49
+ if (!value) return /* @__PURE__ */ new Map();
50
+ const node = unwrap(value);
51
+ if (!ts.isObjectLiteralExpression(node) || visited.has(node)) return /* @__PURE__ */ new Map();
52
+ const next = /* @__PURE__ */ new Set([...visited, node]);
53
+ const output = /* @__PURE__ */ new Map();
54
+ for (const property of node.properties) {
55
+ if (ts.isSpreadAssignment(property)) for (const [key, entry] of fields(property.expression, next)) output.set(key, entry);
56
+ else if (ts.isShorthandPropertyAssignment(property)) output.set(property.name.text, property.name);
57
+ else if (ts.isPropertyAssignment(property) && (ts.isIdentifier(property.name) || ts.isStringLiteralLike(property.name))) {
58
+ output.set(property.name.text, property.initializer);
59
+ }
60
+ }
61
+ return output;
62
+ }
63
+ const entries = fields(fields(fields(expression).get("forms")).get("sections"));
64
+ const result = /* @__PURE__ */ new Map();
65
+ function text(input) {
66
+ const node = input ? unwrap(input) : void 0;
67
+ return node && ts.isStringLiteralLike(node) ? node.text : void 0;
68
+ }
69
+ for (const [key, value] of entries) {
70
+ if (unwrap(value).kind === ts.SyntaxKind.NullKeyword) {
71
+ result.set(key, null);
72
+ continue;
73
+ }
74
+ const options = fields(value);
75
+ const operation = text(options.get("operation"));
76
+ const contributionId = text(options.get("contributionId"));
77
+ if (!contributionId || operation !== "add" && operation !== "hide" && operation !== "replace") continue;
78
+ if (operation !== "add") {
79
+ result.set(key, { operation, contributionId });
80
+ continue;
81
+ }
82
+ const placement = fields(options.get("placement"));
83
+ const rawPosition = placement.get("position");
84
+ const positionNode = rawPosition ? unwrap(rawPosition) : void 0;
85
+ const position = positionNode && ts.isPropertyAccessExpression(positionNode) && ts.isIdentifier(positionNode.expression) && positionNode.expression.text === "InjectionPosition" && ["First", "Last", "Before", "After"].includes(positionNode.name.text) ? positionNode.name.text.toLowerCase() : text(rawPosition);
86
+ const relativeTo = text(placement.get("relativeTo"));
87
+ const allowed = /* @__PURE__ */ new Set(["first", "last", "before", "after"]);
88
+ if (placement.size && (!position || !allowed.has(position))) continue;
89
+ result.set(key, { operation, contributionId, ...position ? {
90
+ placement: { position, relativeTo }
91
+ } : {} });
92
+ }
93
+ return result.size ? Object.fromEntries(result) : void 0;
94
+ }
26
95
  function parseModuleEntryFromObjectLiteral(node) {
27
96
  let id = null;
28
97
  let from = null;
29
98
  let locator;
30
99
  let packageName;
31
100
  let devSupervisorRequiresFullBootstrap = false;
101
+ let formSectionOverrides;
32
102
  for (const property of node.properties) {
103
+ if (ts.isShorthandPropertyAssignment(property) && property.name.text === "overrides") {
104
+ formSectionOverrides = staticFormSectionOverrides(property.name);
105
+ continue;
106
+ }
33
107
  if (!ts.isPropertyAssignment(property)) continue;
34
108
  const key = ts.isIdentifier(property.name) || ts.isStringLiteralLike(property.name) ? property.name.text : null;
35
109
  if (key === "id" && ts.isStringLiteralLike(property.initializer)) {
@@ -45,6 +119,7 @@ function parseModuleEntryFromObjectLiteral(node) {
45
119
  locator = property.initializer.text;
46
120
  }
47
121
  if (key === "overrides") {
122
+ formSectionOverrides = staticFormSectionOverrides(property.initializer);
48
123
  if (!ts.isObjectLiteralExpression(property.initializer)) {
49
124
  devSupervisorRequiresFullBootstrap = true;
50
125
  continue;
@@ -69,7 +144,8 @@ function parseModuleEntryFromObjectLiteral(node) {
69
144
  from: from ?? "@open-mercato/core",
70
145
  ...locator ? { locator } : {},
71
146
  ...packageName ? { packageName } : {},
72
- ...devSupervisorRequiresFullBootstrap ? { devSupervisorRequiresFullBootstrap: true } : {}
147
+ ...devSupervisorRequiresFullBootstrap ? { devSupervisorRequiresFullBootstrap: true } : {},
148
+ ...formSectionOverrides ? { formSectionOverrides } : {}
73
149
  };
74
150
  }
75
151
  function parseProcessEnvAccess(node, env) {
@@ -184,10 +260,128 @@ function collectPushEntriesFromStatement(statement, env, targetVariableName, sco
184
260
  return entry ? [entry] : [];
185
261
  });
186
262
  }
263
+ function validateFormSectionGates(sourceFile, targetVariableName) {
264
+ const initializers = /* @__PURE__ */ new Map();
265
+ for (const statement of sourceFile.statements) {
266
+ if (!ts.isVariableStatement(statement)) continue;
267
+ for (const declaration of statement.declarationList.declarations) {
268
+ let mapBinding2 = function(binding, value) {
269
+ if (ts.isIdentifier(binding)) initializers.set(binding.text, value);
270
+ else for (const element of binding.elements) if (ts.isBindingElement(element)) mapBinding2(element.name, value);
271
+ };
272
+ var mapBinding = mapBinding2;
273
+ const initializer = declaration.initializer;
274
+ if (!initializer) continue;
275
+ mapBinding2(declaration.name, initializer);
276
+ }
277
+ }
278
+ function serverEnvironmentReads(expression) {
279
+ const found = /* @__PURE__ */ new Set();
280
+ const seen = /* @__PURE__ */ new Set();
281
+ function visit(node) {
282
+ if (ts.isIdentifier(node) && !seen.has(node.text)) {
283
+ seen.add(node.text);
284
+ const initializer = initializers.get(node.text);
285
+ if (initializer && node.text !== targetVariableName) visit(initializer);
286
+ }
287
+ if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === "process" && node.name.text === "env") {
288
+ found.add("<dynamic process.env>");
289
+ return;
290
+ }
291
+ if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) {
292
+ const target = node.expression;
293
+ if (ts.isPropertyAccessExpression(target) && target.name.text === "env" && ts.isIdentifier(target.expression) && target.expression.text === "process") {
294
+ const environmentKey = ts.isPropertyAccessExpression(node) ? node.name.text : ts.isStringLiteralLike(node.argumentExpression) ? node.argumentExpression.text : "<dynamic process.env>";
295
+ if (!environmentKey.startsWith("NEXT_PUBLIC_")) found.add(environmentKey);
296
+ return;
297
+ }
298
+ }
299
+ ts.forEachChild(node, visit);
300
+ }
301
+ visit(expression);
302
+ return [...found].sort((left, right) => left < right ? -1 : left > right ? 1 : 0);
303
+ }
304
+ function assertGates(gates) {
305
+ const serverKeys = [...new Set(gates.flatMap(serverEnvironmentReads))].sort((left, right) => left < right ? -1 : left > right ? 1 : 0);
306
+ if (serverKeys.length) {
307
+ throw new Error(`[resolver] forms.sections in src/modules.ts requires browser-visible module gating; server-only: ${serverKeys.join(", ")}`);
308
+ }
309
+ }
310
+ function inspectOverride(node, keys, gates, seen = /* @__PURE__ */ new Set()) {
311
+ if (ts.isParenthesizedExpression(node) || ts.isSatisfiesExpression(node) || ts.isAsExpression(node)) {
312
+ inspectOverride(node.expression, keys, gates, seen);
313
+ } else if (ts.isConditionalExpression(node)) {
314
+ inspectOverride(node.whenTrue, keys, [...gates, node.condition], seen);
315
+ inspectOverride(node.whenFalse, keys, [...gates, node.condition], seen);
316
+ } else if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken) {
317
+ inspectOverride(node.right, keys, [...gates, node.left], seen);
318
+ } else if (ts.isIdentifier(node) && !seen.has(node.text) && initializers.has(node.text)) {
319
+ const initializer = initializers.get(node.text);
320
+ if (initializer) inspectOverride(initializer, keys, gates, /* @__PURE__ */ new Set([...seen, node.text]));
321
+ } else if (!keys.length) {
322
+ assertGates([...gates, node]);
323
+ } else if (ts.isObjectLiteralExpression(node)) {
324
+ for (const property of node.properties) {
325
+ if (ts.isSpreadAssignment(property)) inspectOverride(property.expression, keys, gates, seen);
326
+ if (ts.isShorthandPropertyAssignment(property) && property.name.text === keys[0]) {
327
+ inspectOverride(property.name, keys.slice(1), gates, seen);
328
+ }
329
+ if (ts.isPropertyAssignment(property) && (ts.isIdentifier(property.name) || ts.isStringLiteralLike(property.name)) && property.name.text === keys[0]) {
330
+ inspectOverride(property.initializer, keys.slice(1), gates, seen);
331
+ }
332
+ }
333
+ }
334
+ }
335
+ function inspectModules(node, gates, seen = /* @__PURE__ */ new Set()) {
336
+ if (ts.isIdentifier(node) && !seen.has(node.text)) {
337
+ const initializer = initializers.get(node.text);
338
+ if (initializer && node.text !== targetVariableName) inspectModules(initializer, gates, /* @__PURE__ */ new Set([...seen, node.text]));
339
+ } else if (ts.isObjectLiteralExpression(node)) {
340
+ inspectOverride(node, ["overrides", "forms", "sections"], gates);
341
+ } else if (ts.isConditionalExpression(node)) {
342
+ inspectModules(node.whenTrue, [...gates, node.condition], seen);
343
+ inspectModules(node.whenFalse, [...gates, node.condition], seen);
344
+ } else {
345
+ ts.forEachChild(node, (child) => inspectModules(child, gates, seen));
346
+ }
347
+ }
348
+ function inspectStatement(statement, gates) {
349
+ if (ts.isBlock(statement)) {
350
+ for (const child of statement.statements) inspectStatement(child, gates);
351
+ return;
352
+ }
353
+ if (ts.isIfStatement(statement)) {
354
+ const branchGates = [...gates, statement.expression];
355
+ inspectStatement(statement.thenStatement, branchGates);
356
+ if (statement.elseStatement) inspectStatement(statement.elseStatement, branchGates);
357
+ return;
358
+ }
359
+ if (ts.isExpressionStatement(statement)) inspectPush(statement.expression, gates);
360
+ }
361
+ function inspectPush(node, gates) {
362
+ if (ts.isParenthesizedExpression(node)) inspectPush(node.expression, gates);
363
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken) {
364
+ inspectPush(node.right, [...gates, node.left]);
365
+ }
366
+ if (ts.isConditionalExpression(node)) {
367
+ inspectPush(node.whenTrue, [...gates, node.condition]);
368
+ inspectPush(node.whenFalse, [...gates, node.condition]);
369
+ }
370
+ if (!ts.isCallExpression(node)) return;
371
+ const { expression, arguments: entries } = node;
372
+ if (ts.isPropertyAccessExpression(expression) && expression.name.text === "push" && ts.isIdentifier(expression.expression) && expression.expression.text === targetVariableName) {
373
+ for (const entry of entries) inspectModules(entry, gates);
374
+ }
375
+ }
376
+ const enabled = initializers.get(targetVariableName);
377
+ if (enabled) inspectModules(enabled, []);
378
+ for (const statement of sourceFile.statements) inspectStatement(statement, []);
379
+ }
187
380
  function parseModulesFromSource(source, env = process.env) {
188
381
  const sourceFile = ts.createSourceFile("modules.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
189
382
  const modules = [];
190
383
  const variableName = "enabledModules";
384
+ validateFormSectionGates(sourceFile, variableName);
191
385
  const scope = /* @__PURE__ */ new Map();
192
386
  let foundDeclaration = false;
193
387
  for (const statement of sourceFile.statements) {