@open-mercato/cli 0.11.1-develop.8951.1.108985f0c9 → 0.11.1-develop.8960.1.1345cbafca

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 (102) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/agentic/guides/module-facts.json +182 -182
  3. package/dist/agentic/guides/module-facts.v2.json +182 -182
  4. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  5. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  6. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  7. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  8. package/dist/agentic/guides/modules/assisted_selling/index.md +1 -1
  9. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  10. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  11. package/dist/agentic/guides/modules/auth/index.md +1 -1
  12. package/dist/agentic/guides/modules/availability/index.md +1 -1
  13. package/dist/agentic/guides/modules/backups/index.md +1 -1
  14. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  15. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  16. package/dist/agentic/guides/modules/cart/index.md +1 -1
  17. package/dist/agentic/guides/modules/catalog/index.md +1 -1
  18. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  19. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  20. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  21. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  22. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  23. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  24. package/dist/agentic/guides/modules/channel_ms365/index.md +1 -1
  25. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  26. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  27. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  28. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  29. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  30. package/dist/agentic/guides/modules/configs/index.md +1 -1
  31. package/dist/agentic/guides/modules/content/index.md +1 -1
  32. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  33. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  34. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  35. package/dist/agentic/guides/modules/customers/index.md +1 -1
  36. package/dist/agentic/guides/modules/dashboards/index.md +1 -1
  37. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  38. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  39. package/dist/agentic/guides/modules/devices/index.md +1 -1
  40. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  41. package/dist/agentic/guides/modules/directory/index.md +1 -1
  42. package/dist/agentic/guides/modules/documents/index.md +1 -1
  43. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  44. package/dist/agentic/guides/modules/entities/index.md +1 -1
  45. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  46. package/dist/agentic/guides/modules/events/index.md +1 -1
  47. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  48. package/dist/agentic/guides/modules/forms/index.md +1 -1
  49. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  50. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  51. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  52. package/dist/agentic/guides/modules/generators/index.md +1 -1
  53. package/dist/agentic/guides/modules/gus_regon/index.md +1 -1
  54. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  55. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  56. package/dist/agentic/guides/modules/ledger/index.md +1 -1
  57. package/dist/agentic/guides/modules/maintenance/index.md +1 -1
  58. package/dist/agentic/guides/modules/messages/index.md +1 -1
  59. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  60. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  61. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  62. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  63. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  64. package/dist/agentic/guides/modules/planner/index.md +1 -1
  65. package/dist/agentic/guides/modules/portal/index.md +1 -1
  66. package/dist/agentic/guides/modules/progress/index.md +1 -1
  67. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  68. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  69. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  70. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  71. package/dist/agentic/guides/modules/resources/index.md +1 -1
  72. package/dist/agentic/guides/modules/sales/index.md +1 -1
  73. package/dist/agentic/guides/modules/sales_invoices_gl_posting/index.md +1 -1
  74. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  75. package/dist/agentic/guides/modules/search/index.md +1 -1
  76. package/dist/agentic/guides/modules/security/index.md +1 -1
  77. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  78. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  79. package/dist/agentic/guides/modules/sso/index.md +1 -1
  80. package/dist/agentic/guides/modules/staff/index.md +1 -1
  81. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  82. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  83. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  84. package/dist/agentic/guides/modules/sync_shopify/index.md +1 -1
  85. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  86. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  87. package/dist/agentic/guides/modules/tenant_boundaries/index.md +1 -1
  88. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  89. package/dist/agentic/guides/modules/translations/index.md +1 -1
  90. package/dist/agentic/guides/modules/upgrade_actions/index.md +1 -1
  91. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  92. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  93. package/dist/agentic/guides/modules/wms/index.md +1 -1
  94. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  95. package/dist/agentic/guides/reference-module-facts.json +2 -2
  96. package/dist/agentic/guides/reference-modules/example/index.md +1 -1
  97. package/dist/agentic/guides/upstream/manifest.json +1 -1
  98. package/dist/lib/db/commands.js +6 -2
  99. package/dist/lib/db/commands.js.map +2 -2
  100. package/package.json +7 -7
  101. package/src/lib/db/__tests__/commands.migrate-reindex.test.ts +83 -1
  102. package/src/lib/db/commands.ts +7 -2
@@ -1,5 +1,5 @@
1
1
  # sales_invoices_gl_posting — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/core 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/core 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/core/src/modules/sales_invoices_gl_posting
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # scheduler — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/scheduler 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/scheduler 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/scheduler/src/modules/scheduler
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # search — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/search 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/search 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/search/src/modules/search
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # security — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/enterprise 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/enterprise 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/enterprise/src/modules/security
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # seeds — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/core 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/core 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/core/src/modules/seeds
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # shipping_carriers — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/core 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/core 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/core/src/modules/shipping_carriers
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # sso — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/enterprise 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/enterprise 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/enterprise/src/modules/sso
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # staff — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/core 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/core 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/core/src/modules/staff
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # storage_s3 — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/storage-s3 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/storage-s3 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/storage-s3/src/modules/storage_s3
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # sync_akeneo — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/sync-akeneo 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/sync-akeneo 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/sync-akeneo/src/modules/sync_akeneo
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # sync_excel — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/core 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/core 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/core/src/modules/sync_excel
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # sync_shopify — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/sync-shopify 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/sync-shopify 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/sync-shopify/src/modules/sync_shopify
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # system_status_overlays — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/enterprise 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/enterprise 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/enterprise/src/modules/system_status_overlays
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # telemetry — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/telemetry 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/telemetry 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/telemetry/src/modules/telemetry
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # tenant_boundaries — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/enterprise 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/enterprise 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/enterprise/src/modules/tenant_boundaries
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # tillio — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/tillio 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/tillio 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/tillio/src/modules/tillio
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # translations — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/core 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/core 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/core/src/modules/translations
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # upgrade_actions — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/upgrade-actions 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/upgrade-actions 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/upgrade-actions/src/modules/upgrade_actions
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # warranty_claims — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/core 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/core 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/core/src/modules/warranty_claims
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # webhooks — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/webhooks 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/webhooks 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/webhooks/src/modules/webhooks
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # wms — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/core 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/core 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/core/src/modules/wms
4
4
 
5
5
  ## Sections
@@ -1,5 +1,5 @@
1
1
  # workflows — module facts (generated, do not edit)
2
- <!-- generated from @open-mercato/core 0.11.1-develop.8951.1.108985f0c9; core 0.11.1-develop.8951.1.108985f0c9 — R1 staleness stamp -->
2
+ <!-- generated from @open-mercato/core 0.11.1-develop.8960.1.1345cbafca; core 0.11.1-develop.8960.1.1345cbafca — R1 staleness stamp -->
3
3
  Source root: node_modules/@open-mercato/core/src/modules/workflows
4
4
 
5
5
  ## Sections
@@ -4,7 +4,7 @@
4
4
  "projectionKind": "activated-reference",
5
5
  "sourceKind": "local-reference",
6
6
  "runtimeSelected": false,
7
- "sourceFingerprint": "23d16301deb79c2f2553e6f202cb7480a041d133cf544682eb40dab1b8082f4c",
7
+ "sourceFingerprint": "81e057aac3cdda4a14fefccb14e33045211522452a6c0089d825a377e634c0de",
8
8
  "taxonomyFingerprint": "2313a7e21c5035b75f662405dad75acfe976c796cd5b4c4f2f2f41635a009aee",
9
9
  "factCoverage": [
10
10
  {
@@ -1191,7 +1191,7 @@
1191
1191
  "facts": {
1192
1192
  "title": "Example Module",
1193
1193
  "description": "Demonstrates pages, APIs, entities and DI.",
1194
- "coreVersion": "0.11.1-develop.8951.1.108985f0c9",
1194
+ "coreVersion": "0.11.1-develop.8960.1.1345cbafca",
1195
1195
  "sourcePackage": null,
1196
1196
  "sourceVersion": null,
1197
1197
  "sourceRoot": "src/modules/example",
@@ -1,5 +1,5 @@
1
1
  # example — module facts (generated reference projection, do not edit)
2
- <!-- generated from local reference src/modules/example; source-fingerprint 23d16301deb79c2f2553e6f202cb7480a041d133cf544682eb40dab1b8082f4c; taxonomy-fingerprint 2313a7e21c5035b75f662405dad75acfe976c796cd5b4c4f2f2f41635a009aee — R1 staleness stamp -->
2
+ <!-- generated from local reference src/modules/example; source-fingerprint 81e057aac3cdda4a14fefccb14e33045211522452a6c0089d825a377e634c0de; taxonomy-fingerprint 2313a7e21c5035b75f662405dad75acfe976c796cd5b4c4f2f2f41635a009aee — R1 staleness stamp -->
3
3
  > Reference projection: `example` is not selected by the current runtime. Its activations and exact override targets describe behavior only after opt-in in `src/modules.ts`.
4
4
  Source root: src/modules/example
5
5
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "version": 1,
3
- "generator": "@open-mercato/cli@0.11.1-develop.8951.1.108985f0c9",
3
+ "generator": "@open-mercato/cli@0.11.1-develop.8960.1.1345cbafca",
4
4
  "files": {
5
5
  "AGENTS.md": "b5dc75ec890c2e8cc834cf36861be3b7b78ab1a714ecb83c8160f3d3e8834140",
6
6
  "BACKWARD_COMPATIBILITY.md": "ded01a2a24e7a97dbe0883ebeee4358ba05d85eb0906ac097d7a22c4a5b18883"
@@ -433,10 +433,12 @@ async function migrateModules(resolver, _options) {
433
433
  reconciled = true;
434
434
  } finally {
435
435
  console.log(results.join("\n"));
436
- if (!recoverHistory || reconciled) await dischargeQueryIndexReindexRequests(appliedMigrations);
436
+ if (!recoverHistory || reconciled) {
437
+ await dischargeQueryIndexReindexRequests(appliedMigrations, () => resolver.getAppDir());
438
+ }
437
439
  }
438
440
  }
439
- async function dischargeQueryIndexReindexRequests(applied) {
441
+ async function dischargeQueryIndexReindexRequests(applied, resolveAppRoot) {
440
442
  if (!applied.length || !isMigrationReindexEnabled()) return;
441
443
  try {
442
444
  const entityTypes = await collectQueryIndexReindexEntityTypes(applied, {
@@ -446,6 +448,8 @@ async function dischargeQueryIndexReindexRequests(applied) {
446
448
  if (!entityTypes.length) return;
447
449
  await requestQueryIndexReindex(entityTypes, {
448
450
  createContainer: async () => {
451
+ const { bootstrapFromAppRoot } = await import("@open-mercato/shared/lib/bootstrap/dynamicLoader");
452
+ await bootstrapFromAppRoot(resolveAppRoot?.());
449
453
  const { createRequestContainer } = await import("@open-mercato/shared/lib/di/container");
450
454
  return await createRequestContainer();
451
455
  },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/db/commands.ts"],
4
- "sourcesContent": ["import path from 'node:path'\nimport fs from 'node:fs'\nimport { pathToFileURL } from 'node:url'\nimport ts from 'typescript-js'\nimport { MikroORM, MetadataStorage, type Logger } from '@mikro-orm/core'\nimport { ReflectMetadataProvider } from '@mikro-orm/decorators/legacy'\nimport { Migrator } from '@mikro-orm/migrations'\nimport { PostgreSqlDriver } from '@mikro-orm/postgresql'\nimport { getSslConfig } from '@open-mercato/shared/lib/db/ssl'\nimport { afterDatabaseMigrate, beforeDatabaseMigrate, resolveDatabaseConnectionUrl, runWithDatabaseExecutionContext, shouldRecoverDatabaseMigrationReindex } from '@open-mercato/shared/lib/db/runtime'\nimport type { PackageResolver, ModuleEntry } from '../resolver'\nimport { quotePostgresIdentifier } from './identifiers'\nimport { preserveUnconstrainedNumericSnapshots } from './numeric-snapshots'\nimport {\n checkEncryptionMapBackfills,\n isEncryptionBackfillCheckEnabled,\n readDeclaredEncryptionMaps,\n type DeclaredEncryptionMap,\n type EncryptionMapRow,\n} from './encryption-backfill-check'\nimport {\n collectQueryIndexReindexEntityTypes,\n isMigrationReindexEnabled,\n requestQueryIndexReindex,\n type AppliedMigration,\n} from './migration-reindex'\n\nconst QUIET_MODE = process.env.OM_CLI_QUIET === '1' || process.env.MERCATO_QUIET === '1'\nconst PROGRESS_EMOJI = ''\n\nfunction formatResult(modId: string, message: string, emoji = '\\u2022') {\n return `${emoji} ${modId}: ${message}`\n}\n\nfunction createProgressRenderer(total: number) {\n const width = 20\n const normalizedTotal = total > 0 ? total : 1\n return (current: number) => {\n const clamped = Math.min(Math.max(current, 0), normalizedTotal)\n const filled = Math.round((clamped / normalizedTotal) * width)\n const bar = `${'='.repeat(filled)}${'.'.repeat(Math.max(width - filled, 0))}`\n return `[${bar}] ${clamped}/${normalizedTotal}`\n }\n}\n\nfunction createMinimalLogger(): Logger {\n return {\n log: () => { },\n error: (_namespace, message) => console.error(message),\n warn: (_namespace, message) => {\n if (!QUIET_MODE) console.warn(message)\n },\n logQuery: () => { },\n setDebugMode: () => { },\n isEnabled: () => false,\n }\n}\n\nfunction getClientUrl(): string {\n const url = process.env.DATABASE_URL\n if (!url) throw new Error('DATABASE_URL is not set')\n return url\n}\n\nfunction sortModules(mods: ModuleEntry[]): ModuleEntry[] {\n // Sort modules alphabetically since they are now isomorphic\n return mods.slice().sort((a, b) => a.id.localeCompare(b.id))\n}\n\n/**\n * Convert a filesystem path into a specifier `import()` can resolve under plain\n * Node ESM on every platform (#6238).\n *\n * Windows already needed `file:` URLs for drive-letter absolute paths. On POSIX,\n * cwd-relative paths such as `node_modules/.../Migration.js` are treated as\n * bare package names (`node_modules`), so migration reindex declarations were\n * logged and skipped. Absolute paths become `file:` URLs on every platform.\n * Already-URL / `node:` / bare package (and package-subpath) specifiers stay as-is.\n */\nexport function toImportableModuleSpecifier(id: string): string {\n if (\n id.startsWith('file:') ||\n id.startsWith('data:') ||\n id.startsWith('node:') ||\n id.startsWith('http:') ||\n id.startsWith('https:')\n ) {\n return id\n }\n\n const isWindowsAbsolute = /^[a-zA-Z]:[\\\\/]/.test(id)\n const isFilesystemRelative =\n id.startsWith('./') ||\n id.startsWith('../') ||\n id.startsWith('.\\\\') ||\n id.startsWith('..\\\\') ||\n /(^|[\\\\/])node_modules([\\\\/]|$)/.test(id)\n\n if (path.isAbsolute(id) || isWindowsAbsolute || isFilesystemRelative) {\n return pathToFileURL(path.resolve(id)).href\n }\n\n return id\n}\n\n/**\n * Custom dynamic import provider for MikroORM and migration reindex loading.\n * Always converts filesystem paths to `file:` URLs before `import()` (#6238).\n */\nasync function dynamicImportProvider(id: string): Promise<any> {\n return import(toImportableModuleSpecifier(id))\n}\n\n/**\n * Sanitizes a module ID for use in SQL identifiers (table names).\n * Replaces non-alphanumeric characters with underscores to prevent SQL injection.\n * @public Exported for testing\n */\nexport function sanitizeModuleId(modId: string): string {\n return modId.replace(/[^a-z0-9_]/gi, '_')\n}\n\n/**\n * Validates that a table name is safe for use in SQL queries.\n * @throws Error if the table name contains invalid characters.\n * @public Exported for testing\n */\nexport function validateTableName(tableName: string): void {\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tableName)) {\n throw new Error(`Invalid table name: ${tableName}. Table names must start with a letter or underscore and contain only alphanumeric characters and underscores.`)\n }\n}\n\nexport function makeConstraintDropsIdempotent(sql: string): string {\n return sql.replace(/alter table\\s+(\"[^\"]+\"|\\S+)\\s+drop constraint\\s+(\"[^\"]+\"|\\S+);/gi, 'alter table $1 drop constraint if exists $2;')\n}\n\nexport function getMigrationSnapshotName(resolver: Pick<PackageResolver, 'getRootDir'>): string {\n void resolver\n return '.snapshot-open-mercato'\n}\n\nexport function shouldCreateInitialModuleMigration(migrationsPath: string, snapshotName: string): boolean {\n const snapshotPath = path.join(migrationsPath, `${snapshotName}.json`)\n if (fs.existsSync(snapshotPath)) return false\n if (!fs.existsSync(migrationsPath)) return true\n\n const migrationFiles = fs\n .readdirSync(migrationsPath)\n .filter((file) => /^Migration.*\\.(ts|js)$/.test(file) && !file.endsWith('.d.ts'))\n\n return migrationFiles.length === 0\n}\n\nexport function resolveGeneratedMigrationPath(fileName: string, migrationsPath: string): string {\n return path.isAbsolute(fileName) ? fileName : path.join(migrationsPath, fileName)\n}\n\nlet tsxLoaderRegistered = false\nlet temporaryModuleCounter = 0\n\nasync function ensureTsxLoaderRegistered() {\n if (tsxLoaderRegistered) return\n try {\n const { register } = await import('tsx/esm/api')\n register()\n tsxLoaderRegistered = true\n } catch {\n // Continue without the loader. Relative TypeScript imports may fail in this case.\n }\n}\n\nasync function importWithTypeScriptFile(filePath: string): Promise<any> {\n await ensureTsxLoaderRegistered()\n const source = fs.readFileSync(filePath, 'utf8')\n const compiled = ts.transpileModule(source, {\n fileName: filePath,\n compilerOptions: {\n module: ts.ModuleKind.ESNext,\n target: ts.ScriptTarget.ES2022,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n esModuleInterop: true,\n resolveJsonModule: true,\n jsx: ts.JsxEmit.ReactJSX,\n experimentalDecorators: true,\n emitDecoratorMetadata: false,\n useDefineForClassFields: false,\n },\n }).outputText\n const tempPath = `${filePath}.mercato-db-generate-${process.pid}-${temporaryModuleCounter++}.mjs`\n fs.writeFileSync(tempPath, compiled, 'utf8')\n try {\n return await import(pathToFileURL(tempPath).href)\n } finally {\n try {\n fs.unlinkSync(tempPath)\n } catch {\n // Ignore cleanup failures for temporary compiled modules.\n }\n }\n}\n\nasync function loadModuleEntities(entry: ModuleEntry, resolver: PackageResolver): Promise<any[]> {\n const roots = resolver.getModulePaths(entry)\n const imps = resolver.getModuleImportBase(entry)\n const isAppModule = entry.from === '@app'\n const shouldImportFromSource = isAppModule || resolver.isMonorepo()\n const bases = [\n path.join(roots.appBase, 'data'),\n path.join(roots.pkgBase, 'data'),\n path.join(roots.appBase, 'db'),\n path.join(roots.pkgBase, 'db'),\n ]\n const candidates = ['entities.ts', 'schema.ts']\n\n for (const base of bases) {\n for (const f of candidates) {\n const p = path.join(base, f)\n if (fs.existsSync(p)) {\n const sub = path.basename(base)\n const fromApp = base.startsWith(roots.appBase)\n const importPath = fromApp || shouldImportFromSource\n ? pathToFileURL(p).href\n : `${imps.pkgBase}/${sub}/${f.replace(/\\.ts$/, '')}`\n try {\n const mod = fromApp || shouldImportFromSource\n ? await importWithTypeScriptFile(p)\n : await import(importPath)\n const entities = Object.values(mod).filter((v) => typeof v === 'function')\n if (entities.length) return entities as any[]\n } catch (err) {\n // For @app modules we try a TS loader fallback; otherwise propagate errors\n if (isAppModule) {\n if (process.env.MERCATO_CLI_DEBUG_IMPORTS === '1') {\n console.warn(`[db] failed to load app module entities from ${p}: ${(err as Error)?.message || String(err)}`)\n }\n continue\n }\n throw err\n }\n }\n }\n }\n return []\n}\n\nfunction getMigrationsPath(entry: ModuleEntry, resolver: PackageResolver): string {\n const roots = resolver.getModulePaths(entry)\n\n if (entry.from === '@app') {\n // @app modules: use src/ (user's TypeScript source)\n // Normalize to forward slashes for ESM compatibility on Windows\n return path.join(roots.appBase, 'migrations').replace(/\\\\/g, '/')\n }\n\n // Package modules: in standalone mode, use dist/ (compiled JS) since Node.js\n // can't run TypeScript from node_modules. In monorepo, use src/ (TypeScript).\n if (!resolver.isMonorepo()) {\n // Replace src/modules with dist/modules for standalone apps\n // Use regex to handle both forward and backslashes\n const distPath = roots.pkgBase.replace(/[/\\\\]src[/\\\\]modules[/\\\\]/, '/dist/modules/')\n return path.join(distPath, 'migrations').replace(/\\\\/g, '/')\n }\n\n // Normalize to forward slashes for ESM compatibility on Windows\n return path.join(roots.pkgBase, 'migrations').replace(/\\\\/g, '/')\n}\n\nasync function loadModuleEncryptionMaps(entry: ModuleEntry, resolver: PackageResolver): Promise<DeclaredEncryptionMap[]> {\n const roots = resolver.getModulePaths(entry)\n const appFile = path.join(roots.appBase, 'encryption.ts')\n const pkgFile = path.join(roots.pkgBase, 'encryption.ts')\n try {\n if (fs.existsSync(appFile)) return readDeclaredEncryptionMaps(entry.id, await importWithTypeScriptFile(appFile))\n if (entry.from === '@app' || resolver.isMonorepo()) {\n return fs.existsSync(pkgFile) ? readDeclaredEncryptionMaps(entry.id, await importWithTypeScriptFile(pkgFile)) : []\n }\n return readDeclaredEncryptionMaps(entry.id, await import(`${resolver.getModuleImportBase(entry).pkgBase}/encryption`))\n } catch {\n return []\n }\n}\n\nfunction readModuleMigrationSources(modules: ModuleEntry[], resolver: PackageResolver): string[] {\n const sources: string[] = []\n for (const entry of modules) {\n const migrationsPath = getMigrationsPath(entry, resolver)\n if (!fs.existsSync(migrationsPath)) continue\n for (const file of fs.readdirSync(migrationsPath)) {\n if (!/^Migration.*\\.(ts|js)$/.test(file) || file.endsWith('.d.ts')) continue\n sources.push(fs.readFileSync(path.join(migrationsPath, file), 'utf8'))\n }\n }\n return sources\n}\n\nasync function queryEncryptionMapRows(): Promise<EncryptionMapRow[] | null> {\n const { Client } = await import('pg')\n const client = new Client({ connectionString: getClientUrl(), ssl: getSslConfig(), connectionTimeoutMillis: 5000 })\n await client.connect()\n try {\n const table = await client.query(`select to_regclass('encryption_maps') is not null as \"exists\"`)\n if (!table.rows[0]?.exists) return null\n const result = await client.query(\n `select \"tenant_id\", \"organization_id\", \"entity_id\", \"fields_json\", \"is_active\" from \"encryption_maps\" where \"deleted_at\" is null`,\n )\n return result.rows.map((row) => ({\n tenantId: row.tenant_id ?? null,\n organizationId: row.organization_id ?? null,\n entityId: String(row.entity_id),\n fieldsJson: row.fields_json,\n isActive: row.is_active === true,\n }))\n } finally {\n try {\n await client.end()\n } catch { }\n }\n}\n\nexport async function warnAboutMissingEncryptionMapBackfills(modules: ModuleEntry[], resolver: PackageResolver): Promise<void> {\n if (!isEncryptionBackfillCheckEnabled()) return\n await checkEncryptionMapBackfills({\n loadDeclaredMaps: async () => {\n const declared: DeclaredEncryptionMap[] = []\n for (const entry of modules) declared.push(...(await loadModuleEncryptionMaps(entry, resolver)))\n return declared\n },\n loadMigrationSources: () => readModuleMigrationSources(modules, resolver),\n queryEncryptionMaps: queryEncryptionMapRows,\n warn: (message) => console.warn(message),\n })\n}\n\nexport interface DbOptions {\n quiet?: boolean\n}\n\nexport interface GreenfieldOptions extends DbOptions {\n yes: boolean\n}\n\nexport async function dbGenerate(resolver: PackageResolver, options: DbOptions = {}): Promise<void> {\n const modules = resolver.loadEnabledModules()\n const ordered = sortModules(modules)\n const results: string[] = []\n\n const sslConfig = getSslConfig()\n const usedFileNames = new Set<string>()\n\n for (const entry of ordered) {\n // Clear the global @Entity() decorator registry before loading this module's\n // entities. MikroORM's migrator reads MetadataStorage at createMigration()\n // time, so without this clear, every module's migration would include every\n // previously-loaded module's tables (see issue #1911).\n MetadataStorage.clear()\n\n const modId = entry.id\n const sanitizedModId = sanitizeModuleId(modId)\n const entities = await loadModuleEntities(entry, resolver)\n if (!entities.length) {\n if (entry.from === '@app') {\n results.push(formatResult(modId, 'no entities discovered', ''))\n }\n continue\n }\n\n const migrationsPath = getMigrationsPath(entry, resolver)\n fs.mkdirSync(migrationsPath, { recursive: true })\n\n const tableName = `mikro_orm_migrations_${sanitizedModId}`\n validateTableName(tableName)\n const snapshotName = getMigrationSnapshotName(resolver)\n const createInitialMigration = shouldCreateInitialModuleMigration(migrationsPath, snapshotName)\n\n const orm = await MikroORM.init<PostgreSqlDriver>({\n driver: PostgreSqlDriver,\n clientUrl: getClientUrl(),\n loggerFactory: () => createMinimalLogger(),\n dynamicImportProvider,\n entities,\n metadataProvider: ReflectMetadataProvider,\n migrations: {\n path: migrationsPath,\n glob: '!(*.d).{ts,js}',\n tableName,\n snapshotName,\n dropTables: false,\n },\n schemaGenerator: {\n disableForeignKeys: true,\n },\n pool: {\n min: 1,\n max: 3,\n idleTimeoutMillis: 30000,\n // acquireTimeoutMillis removed for v7 (pg.Pool doesn't support it; use connectionTimeoutMillis in driverOptions if needed)\n },\n driverOptions: sslConfig ? {\n ssl: sslConfig,\n } : undefined,\n })\n\n try {\n preserveUnconstrainedNumericSnapshots(orm.em.getDriver().getPlatform())\n const diff = await orm.migrator.create(undefined, false, createInitialMigration)\n if (diff && diff.fileName) {\n try {\n const orig = resolveGeneratedMigrationPath(diff.fileName, migrationsPath)\n const base = path.basename(orig)\n const dir = path.dirname(orig)\n const ext = path.extname(base)\n const stem = base.replace(ext, '')\n const suffix = `_${modId}`\n let candidate = stem.endsWith(suffix) ? base : `${stem}${suffix}${ext}`\n let dedupe = 1\n\n while (usedFileNames.has(path.join(dir, candidate))) {\n candidate = `${stem}${suffix}_${dedupe++}${ext}`\n }\n\n const newPath = path.join(dir, candidate)\n let content = fs.readFileSync(orig, 'utf8')\n content = makeConstraintDropsIdempotent(content)\n content = content.replace(\n /export class (Migration\\d+)/,\n `export class $1_${modId.replace(/[^a-zA-Z0-9]/g, '_')}`\n )\n fs.writeFileSync(newPath, content, 'utf8')\n if (newPath !== orig) fs.unlinkSync(orig)\n usedFileNames.add(newPath)\n results.push(formatResult(modId, `generated ${path.basename(newPath)}`, ''))\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n results.push(formatResult(modId, `generated ${path.basename(diff.fileName)} (rename failed: ${message})`, ''))\n }\n } else {\n results.push(formatResult(modId, 'no changes', ''))\n }\n } finally {\n await orm.close(true)\n }\n }\n\n console.log(results.join('\\n'))\n await warnAboutMissingEncryptionMapBackfills(ordered, resolver)\n}\n\nexport async function dbMigrate(resolver: PackageResolver, options: DbOptions = {}): Promise<void> {\n return runWithDatabaseExecutionContext({ kind: 'maintenance', tenantId: null, source: 'cli', operation: 'db:migrate' }, () => migrateModules(resolver, options))\n}\n\nasync function migrateModules(resolver: PackageResolver, _options: DbOptions): Promise<void> {\n const modules = resolver.loadEnabledModules()\n const ordered = sortModules(modules)\n const results: string[] = []\n const appliedMigrations: AppliedMigration[] = []\n const recoverHistory = shouldRecoverDatabaseMigrationReindex()\n let reconciled = false\n\n await beforeDatabaseMigrate()\n try {\n for (const entry of ordered) {\n const modId = entry.id\n const sanitizedModId = sanitizeModuleId(modId)\n const entities = await loadModuleEntities(entry, resolver)\n\n const migrationsPath = getMigrationsPath(entry, resolver)\n\n // Skip if no entities AND no migrations directory exists\n // (allows @app modules to run migrations even if entities can't be dynamically imported)\n if (!entities.length && !fs.existsSync(migrationsPath)) continue\n fs.mkdirSync(migrationsPath, { recursive: true })\n\n const tableName = `mikro_orm_migrations_${sanitizedModId}`\n validateTableName(tableName)\n\n // dbMigrate only runs existing migration files \u2014 entities are intentionally\n // omitted so MikroORM does not compare them against the snapshot and\n // auto-generate a phantom diff migration (that would duplicate tables\n // already created by committed migrations).\n const sslConfig = getSslConfig()\n const orm = await MikroORM.init<PostgreSqlDriver>({\n driver: PostgreSqlDriver,\n clientUrl: resolveDatabaseConnectionUrl('maintenance', getClientUrl()),\n loggerFactory: () => createMinimalLogger(),\n dynamicImportProvider,\n entities: [],\n metadataProvider: ReflectMetadataProvider,\n discovery: { warnWhenNoEntities: false },\n migrations: {\n path: migrationsPath,\n glob: '!(*.d).{ts,js}',\n tableName,\n snapshot: false,\n dropTables: false,\n },\n schemaGenerator: {\n disableForeignKeys: true,\n },\n pool: {\n min: 1,\n max: 3,\n idleTimeoutMillis: 30000,\n // acquireTimeoutMillis removed for v7 (pg.Pool doesn't support it; use connectionTimeoutMillis in driverOptions if needed)\n },\n driverOptions: sslConfig ? {\n ssl: sslConfig,\n } : undefined,\n })\n\n try {\n const migrator = orm.migrator as Migrator\n if (recoverHistory) {\n const executed = await migrator.getExecuted()\n for (const migration of executed) {\n appliedMigrations.push({ moduleId: modId, migrationsPath, name: migration.name })\n }\n }\n const pending = await migrator.getPending()\n if (!pending.length) {\n results.push(formatResult(modId, 'no pending migrations', ''))\n } else {\n const renderProgress = createProgressRenderer(pending.length)\n let applied = 0\n if (!QUIET_MODE) {\n process.stdout.write(` ${PROGRESS_EMOJI} ${modId}: ${renderProgress(applied)}`)\n }\n for (const migration of pending) {\n const migrationName =\n typeof migration === 'string' ? migration : migration.name\n await migrator.up(migrationName ? { migrations: [migrationName] } : undefined)\n if (migrationName) {\n appliedMigrations.push({\n moduleId: modId,\n migrationsPath,\n name: String(migrationName),\n filePath: typeof migration === 'string' ? null : migration.path ?? null,\n })\n }\n applied += 1\n if (!QUIET_MODE) {\n process.stdout.write(`\\r ${PROGRESS_EMOJI} ${modId}: ${renderProgress(applied)}`)\n }\n }\n if (!QUIET_MODE) process.stdout.write('\\n')\n results.push(\n formatResult(modId, `${pending.length} migration${pending.length === 1 ? '' : 's'} applied`, '')\n )\n }\n } finally {\n await orm.close(true)\n }\n }\n await afterDatabaseMigrate()\n reconciled = true\n } finally {\n console.log(results.join('\\n'))\n if (!recoverHistory || reconciled) await dischargeQueryIndexReindexRequests(appliedMigrations)\n }\n}\n\n/**\n * Runs after every module migrated and after `orm.close()`, so the rewrites the declarations\n * refer to are committed before the reindex is queued.\n *\n * Reached from a `finally`, so it also runs when a later migration threw: the migrations that\n * did apply already committed, and their declarations are the only record that their projections\n * are stale \u2014 a re-run cannot recover them, because `getPending()` no longer lists them. It must\n * therefore never throw, or it would replace the migration failure the operator needs to see.\n */\nexport async function dischargeQueryIndexReindexRequests(\n applied: readonly AppliedMigration[],\n): Promise<void> {\n if (!applied.length || !isMigrationReindexEnabled()) return\n\n try {\n const entityTypes = await collectQueryIndexReindexEntityTypes(applied, {\n importModule: dynamicImportProvider,\n onWarn: (message) => console.warn(message),\n })\n if (!entityTypes.length) return\n\n await requestQueryIndexReindex(entityTypes, {\n createContainer: async () => {\n const { createRequestContainer } = await import('@open-mercato/shared/lib/di/container')\n return (await createRequestContainer()) as any\n },\n onInfo: (message) => {\n if (!QUIET_MODE) console.log(message)\n },\n onWarn: (message) => console.warn(message),\n })\n } catch (error) {\n console.warn(\n `[query_index] Could not determine which projections the migrations invalidated: ${\n error instanceof Error ? error.message : String(error)\n }`,\n )\n }\n}\n\nexport async function dbGreenfield(resolver: PackageResolver, options: GreenfieldOptions): Promise<void> {\n if (!options.yes) {\n console.error('This command will DELETE all data. Use --yes to confirm.')\n process.exit(1)\n }\n\n console.log('Cleaning up migrations and snapshots for greenfield setup...')\n\n const modules = resolver.loadEnabledModules()\n const ordered = sortModules(modules)\n const results: string[] = []\n const outputDir = resolver.getOutputDir()\n\n for (const entry of ordered) {\n const modId = entry.id\n const migrationsPath = getMigrationsPath(entry, resolver)\n\n if (fs.existsSync(migrationsPath)) {\n // Remove all migration files\n const migrationFiles = fs\n .readdirSync(migrationsPath)\n .filter((file) => file.endsWith('.ts') && file.startsWith('Migration'))\n\n for (const file of migrationFiles) {\n fs.unlinkSync(path.join(migrationsPath, file))\n }\n\n // Remove snapshot files\n const snapshotFiles = fs\n .readdirSync(migrationsPath)\n .filter((file) => file.endsWith('.json') && file.includes('snapshot'))\n\n for (const file of snapshotFiles) {\n fs.unlinkSync(path.join(migrationsPath, file))\n }\n\n if (migrationFiles.length > 0 || snapshotFiles.length > 0) {\n results.push(\n formatResult(modId, `cleaned ${migrationFiles.length} migrations, ${snapshotFiles.length} snapshots`, '')\n )\n } else {\n results.push(formatResult(modId, 'already clean', ''))\n }\n } else {\n results.push(formatResult(modId, 'no migrations directory', ''))\n }\n\n // Clean up checksum files using glob pattern\n if (fs.existsSync(outputDir)) {\n const files = fs.readdirSync(outputDir)\n const checksumFiles = files.filter((file) => file.endsWith('.checksum'))\n\n for (const file of checksumFiles) {\n fs.unlinkSync(path.join(outputDir, file))\n }\n\n if (checksumFiles.length > 0) {\n results.push(formatResult(modId, `cleaned ${checksumFiles.length} checksum files`, ''))\n }\n }\n }\n\n console.log(results.join('\\n'))\n\n // Drop per-module MikroORM migration tables to ensure clean slate\n console.log('Dropping per-module migration tables...')\n try {\n const { Client } = await import('pg')\n const client = new Client({ connectionString: getClientUrl(), ssl: getSslConfig() })\n await client.connect()\n try {\n await client.query('BEGIN')\n for (const entry of ordered) {\n const modId = entry.id\n const sanitizedModId = sanitizeModuleId(modId)\n const tableName = `mikro_orm_migrations_${sanitizedModId}`\n validateTableName(tableName)\n await client.query(`DROP TABLE IF EXISTS \"${tableName}\"`)\n console.log(` ${modId}: dropped table ${tableName}`)\n }\n await client.query('COMMIT')\n } catch (e) {\n await client.query('ROLLBACK')\n throw e\n } finally {\n try {\n await client.end()\n } catch { }\n }\n } catch (e) {\n console.error('Failed to drop migration tables:', (e as any)?.message || e)\n throw e\n }\n\n // Drop all existing user tables to ensure fresh CREATE-only migrations\n console.log('Dropping ALL public tables for true greenfield...')\n try {\n const { Client } = await import('pg')\n const client = new Client({ connectionString: getClientUrl(), ssl: getSslConfig() })\n await client.connect()\n try {\n const res = await client.query(`SELECT tablename FROM pg_tables WHERE schemaname = current_schema()`)\n const tables: string[] = (res.rows || []).map((r: any) => String(r.tablename))\n if (tables.length) {\n await client.query('BEGIN')\n try {\n await client.query(\"SET session_replication_role = 'replica'\")\n for (const t of tables) {\n await client.query(`DROP TABLE IF EXISTS ${quotePostgresIdentifier(t)} CASCADE`)\n }\n await client.query(\"SET session_replication_role = 'origin'\")\n await client.query('COMMIT')\n console.log(` Dropped ${tables.length} tables.`)\n } catch (e) {\n await client.query('ROLLBACK')\n throw e\n }\n } else {\n console.log(' No tables found to drop.')\n }\n } finally {\n try {\n await client.end()\n } catch { }\n }\n } catch (e) {\n console.error('Failed to drop public tables:', (e as any)?.message || e)\n throw e\n }\n\n // Generate fresh migrations for all modules\n console.log('Generating fresh migrations for all modules...')\n await dbGenerate(resolver)\n\n // Apply migrations\n console.log('Applying migrations...')\n await dbMigrate(resolver)\n\n console.log('Greenfield reset complete! Fresh migrations generated and applied.')\n}\n"],
5
- "mappings": "AAAA,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,SAAS,qBAAqB;AAC9B,OAAO,QAAQ;AACf,SAAS,UAAU,uBAAoC;AACvD,SAAS,+BAA+B;AAExC,SAAS,wBAAwB;AACjC,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB,uBAAuB,8BAA8B,iCAAiC,6CAA6C;AAElK,SAAS,+BAA+B;AACxC,SAAS,6CAA6C;AACtD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAEP,MAAM,aAAa,QAAQ,IAAI,iBAAiB,OAAO,QAAQ,IAAI,kBAAkB;AACrF,MAAM,iBAAiB;AAEvB,SAAS,aAAa,OAAe,SAAiB,QAAQ,UAAU;AACtE,SAAO,GAAG,KAAK,IAAI,KAAK,KAAK,OAAO;AACtC;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AAO;AACL,gBAAQ,IAAI,6BAA6B;AAAA,MAC3C;AAAA,IACF,UAAE;AACA,UAAI;AACF,cAAM,OAAO,IAAI;AAAA,MACnB,QAAQ;AAAA,MAAE;AAAA,IACZ;AAAA,EACF,SAAS,GAAG;AACV,YAAQ,MAAM,iCAAkC,GAAW,WAAW,CAAC;AACvE,UAAM;AAAA,EACR;AAGA,UAAQ,IAAI,gDAAgD;AAC5D,QAAM,WAAW,QAAQ;AAGzB,UAAQ,IAAI,wBAAwB;AACpC,QAAM,UAAU,QAAQ;AAExB,UAAQ,IAAI,oEAAoE;AAClF;",
4
+ "sourcesContent": ["import path from 'node:path'\nimport fs from 'node:fs'\nimport { pathToFileURL } from 'node:url'\nimport ts from 'typescript-js'\nimport { MikroORM, MetadataStorage, type Logger } from '@mikro-orm/core'\nimport { ReflectMetadataProvider } from '@mikro-orm/decorators/legacy'\nimport { Migrator } from '@mikro-orm/migrations'\nimport { PostgreSqlDriver } from '@mikro-orm/postgresql'\nimport { getSslConfig } from '@open-mercato/shared/lib/db/ssl'\nimport { afterDatabaseMigrate, beforeDatabaseMigrate, resolveDatabaseConnectionUrl, runWithDatabaseExecutionContext, shouldRecoverDatabaseMigrationReindex } from '@open-mercato/shared/lib/db/runtime'\nimport type { PackageResolver, ModuleEntry } from '../resolver'\nimport { quotePostgresIdentifier } from './identifiers'\nimport { preserveUnconstrainedNumericSnapshots } from './numeric-snapshots'\nimport {\n checkEncryptionMapBackfills,\n isEncryptionBackfillCheckEnabled,\n readDeclaredEncryptionMaps,\n type DeclaredEncryptionMap,\n type EncryptionMapRow,\n} from './encryption-backfill-check'\nimport {\n collectQueryIndexReindexEntityTypes,\n isMigrationReindexEnabled,\n requestQueryIndexReindex,\n type AppliedMigration,\n} from './migration-reindex'\n\nconst QUIET_MODE = process.env.OM_CLI_QUIET === '1' || process.env.MERCATO_QUIET === '1'\nconst PROGRESS_EMOJI = ''\n\nfunction formatResult(modId: string, message: string, emoji = '\\u2022') {\n return `${emoji} ${modId}: ${message}`\n}\n\nfunction createProgressRenderer(total: number) {\n const width = 20\n const normalizedTotal = total > 0 ? total : 1\n return (current: number) => {\n const clamped = Math.min(Math.max(current, 0), normalizedTotal)\n const filled = Math.round((clamped / normalizedTotal) * width)\n const bar = `${'='.repeat(filled)}${'.'.repeat(Math.max(width - filled, 0))}`\n return `[${bar}] ${clamped}/${normalizedTotal}`\n }\n}\n\nfunction createMinimalLogger(): Logger {\n return {\n log: () => { },\n error: (_namespace, message) => console.error(message),\n warn: (_namespace, message) => {\n if (!QUIET_MODE) console.warn(message)\n },\n logQuery: () => { },\n setDebugMode: () => { },\n isEnabled: () => false,\n }\n}\n\nfunction getClientUrl(): string {\n const url = process.env.DATABASE_URL\n if (!url) throw new Error('DATABASE_URL is not set')\n return url\n}\n\nfunction sortModules(mods: ModuleEntry[]): ModuleEntry[] {\n // Sort modules alphabetically since they are now isomorphic\n return mods.slice().sort((a, b) => a.id.localeCompare(b.id))\n}\n\n/**\n * Convert a filesystem path into a specifier `import()` can resolve under plain\n * Node ESM on every platform (#6238).\n *\n * Windows already needed `file:` URLs for drive-letter absolute paths. On POSIX,\n * cwd-relative paths such as `node_modules/.../Migration.js` are treated as\n * bare package names (`node_modules`), so migration reindex declarations were\n * logged and skipped. Absolute paths become `file:` URLs on every platform.\n * Already-URL / `node:` / bare package (and package-subpath) specifiers stay as-is.\n */\nexport function toImportableModuleSpecifier(id: string): string {\n if (\n id.startsWith('file:') ||\n id.startsWith('data:') ||\n id.startsWith('node:') ||\n id.startsWith('http:') ||\n id.startsWith('https:')\n ) {\n return id\n }\n\n const isWindowsAbsolute = /^[a-zA-Z]:[\\\\/]/.test(id)\n const isFilesystemRelative =\n id.startsWith('./') ||\n id.startsWith('../') ||\n id.startsWith('.\\\\') ||\n id.startsWith('..\\\\') ||\n /(^|[\\\\/])node_modules([\\\\/]|$)/.test(id)\n\n if (path.isAbsolute(id) || isWindowsAbsolute || isFilesystemRelative) {\n return pathToFileURL(path.resolve(id)).href\n }\n\n return id\n}\n\n/**\n * Custom dynamic import provider for MikroORM and migration reindex loading.\n * Always converts filesystem paths to `file:` URLs before `import()` (#6238).\n */\nasync function dynamicImportProvider(id: string): Promise<any> {\n return import(toImportableModuleSpecifier(id))\n}\n\n/**\n * Sanitizes a module ID for use in SQL identifiers (table names).\n * Replaces non-alphanumeric characters with underscores to prevent SQL injection.\n * @public Exported for testing\n */\nexport function sanitizeModuleId(modId: string): string {\n return modId.replace(/[^a-z0-9_]/gi, '_')\n}\n\n/**\n * Validates that a table name is safe for use in SQL queries.\n * @throws Error if the table name contains invalid characters.\n * @public Exported for testing\n */\nexport function validateTableName(tableName: string): void {\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tableName)) {\n throw new Error(`Invalid table name: ${tableName}. Table names must start with a letter or underscore and contain only alphanumeric characters and underscores.`)\n }\n}\n\nexport function makeConstraintDropsIdempotent(sql: string): string {\n return sql.replace(/alter table\\s+(\"[^\"]+\"|\\S+)\\s+drop constraint\\s+(\"[^\"]+\"|\\S+);/gi, 'alter table $1 drop constraint if exists $2;')\n}\n\nexport function getMigrationSnapshotName(resolver: Pick<PackageResolver, 'getRootDir'>): string {\n void resolver\n return '.snapshot-open-mercato'\n}\n\nexport function shouldCreateInitialModuleMigration(migrationsPath: string, snapshotName: string): boolean {\n const snapshotPath = path.join(migrationsPath, `${snapshotName}.json`)\n if (fs.existsSync(snapshotPath)) return false\n if (!fs.existsSync(migrationsPath)) return true\n\n const migrationFiles = fs\n .readdirSync(migrationsPath)\n .filter((file) => /^Migration.*\\.(ts|js)$/.test(file) && !file.endsWith('.d.ts'))\n\n return migrationFiles.length === 0\n}\n\nexport function resolveGeneratedMigrationPath(fileName: string, migrationsPath: string): string {\n return path.isAbsolute(fileName) ? fileName : path.join(migrationsPath, fileName)\n}\n\nlet tsxLoaderRegistered = false\nlet temporaryModuleCounter = 0\n\nasync function ensureTsxLoaderRegistered() {\n if (tsxLoaderRegistered) return\n try {\n const { register } = await import('tsx/esm/api')\n register()\n tsxLoaderRegistered = true\n } catch {\n // Continue without the loader. Relative TypeScript imports may fail in this case.\n }\n}\n\nasync function importWithTypeScriptFile(filePath: string): Promise<any> {\n await ensureTsxLoaderRegistered()\n const source = fs.readFileSync(filePath, 'utf8')\n const compiled = ts.transpileModule(source, {\n fileName: filePath,\n compilerOptions: {\n module: ts.ModuleKind.ESNext,\n target: ts.ScriptTarget.ES2022,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n esModuleInterop: true,\n resolveJsonModule: true,\n jsx: ts.JsxEmit.ReactJSX,\n experimentalDecorators: true,\n emitDecoratorMetadata: false,\n useDefineForClassFields: false,\n },\n }).outputText\n const tempPath = `${filePath}.mercato-db-generate-${process.pid}-${temporaryModuleCounter++}.mjs`\n fs.writeFileSync(tempPath, compiled, 'utf8')\n try {\n return await import(pathToFileURL(tempPath).href)\n } finally {\n try {\n fs.unlinkSync(tempPath)\n } catch {\n // Ignore cleanup failures for temporary compiled modules.\n }\n }\n}\n\nasync function loadModuleEntities(entry: ModuleEntry, resolver: PackageResolver): Promise<any[]> {\n const roots = resolver.getModulePaths(entry)\n const imps = resolver.getModuleImportBase(entry)\n const isAppModule = entry.from === '@app'\n const shouldImportFromSource = isAppModule || resolver.isMonorepo()\n const bases = [\n path.join(roots.appBase, 'data'),\n path.join(roots.pkgBase, 'data'),\n path.join(roots.appBase, 'db'),\n path.join(roots.pkgBase, 'db'),\n ]\n const candidates = ['entities.ts', 'schema.ts']\n\n for (const base of bases) {\n for (const f of candidates) {\n const p = path.join(base, f)\n if (fs.existsSync(p)) {\n const sub = path.basename(base)\n const fromApp = base.startsWith(roots.appBase)\n const importPath = fromApp || shouldImportFromSource\n ? pathToFileURL(p).href\n : `${imps.pkgBase}/${sub}/${f.replace(/\\.ts$/, '')}`\n try {\n const mod = fromApp || shouldImportFromSource\n ? await importWithTypeScriptFile(p)\n : await import(importPath)\n const entities = Object.values(mod).filter((v) => typeof v === 'function')\n if (entities.length) return entities as any[]\n } catch (err) {\n // For @app modules we try a TS loader fallback; otherwise propagate errors\n if (isAppModule) {\n if (process.env.MERCATO_CLI_DEBUG_IMPORTS === '1') {\n console.warn(`[db] failed to load app module entities from ${p}: ${(err as Error)?.message || String(err)}`)\n }\n continue\n }\n throw err\n }\n }\n }\n }\n return []\n}\n\nfunction getMigrationsPath(entry: ModuleEntry, resolver: PackageResolver): string {\n const roots = resolver.getModulePaths(entry)\n\n if (entry.from === '@app') {\n // @app modules: use src/ (user's TypeScript source)\n // Normalize to forward slashes for ESM compatibility on Windows\n return path.join(roots.appBase, 'migrations').replace(/\\\\/g, '/')\n }\n\n // Package modules: in standalone mode, use dist/ (compiled JS) since Node.js\n // can't run TypeScript from node_modules. In monorepo, use src/ (TypeScript).\n if (!resolver.isMonorepo()) {\n // Replace src/modules with dist/modules for standalone apps\n // Use regex to handle both forward and backslashes\n const distPath = roots.pkgBase.replace(/[/\\\\]src[/\\\\]modules[/\\\\]/, '/dist/modules/')\n return path.join(distPath, 'migrations').replace(/\\\\/g, '/')\n }\n\n // Normalize to forward slashes for ESM compatibility on Windows\n return path.join(roots.pkgBase, 'migrations').replace(/\\\\/g, '/')\n}\n\nasync function loadModuleEncryptionMaps(entry: ModuleEntry, resolver: PackageResolver): Promise<DeclaredEncryptionMap[]> {\n const roots = resolver.getModulePaths(entry)\n const appFile = path.join(roots.appBase, 'encryption.ts')\n const pkgFile = path.join(roots.pkgBase, 'encryption.ts')\n try {\n if (fs.existsSync(appFile)) return readDeclaredEncryptionMaps(entry.id, await importWithTypeScriptFile(appFile))\n if (entry.from === '@app' || resolver.isMonorepo()) {\n return fs.existsSync(pkgFile) ? readDeclaredEncryptionMaps(entry.id, await importWithTypeScriptFile(pkgFile)) : []\n }\n return readDeclaredEncryptionMaps(entry.id, await import(`${resolver.getModuleImportBase(entry).pkgBase}/encryption`))\n } catch {\n return []\n }\n}\n\nfunction readModuleMigrationSources(modules: ModuleEntry[], resolver: PackageResolver): string[] {\n const sources: string[] = []\n for (const entry of modules) {\n const migrationsPath = getMigrationsPath(entry, resolver)\n if (!fs.existsSync(migrationsPath)) continue\n for (const file of fs.readdirSync(migrationsPath)) {\n if (!/^Migration.*\\.(ts|js)$/.test(file) || file.endsWith('.d.ts')) continue\n sources.push(fs.readFileSync(path.join(migrationsPath, file), 'utf8'))\n }\n }\n return sources\n}\n\nasync function queryEncryptionMapRows(): Promise<EncryptionMapRow[] | null> {\n const { Client } = await import('pg')\n const client = new Client({ connectionString: getClientUrl(), ssl: getSslConfig(), connectionTimeoutMillis: 5000 })\n await client.connect()\n try {\n const table = await client.query(`select to_regclass('encryption_maps') is not null as \"exists\"`)\n if (!table.rows[0]?.exists) return null\n const result = await client.query(\n `select \"tenant_id\", \"organization_id\", \"entity_id\", \"fields_json\", \"is_active\" from \"encryption_maps\" where \"deleted_at\" is null`,\n )\n return result.rows.map((row) => ({\n tenantId: row.tenant_id ?? null,\n organizationId: row.organization_id ?? null,\n entityId: String(row.entity_id),\n fieldsJson: row.fields_json,\n isActive: row.is_active === true,\n }))\n } finally {\n try {\n await client.end()\n } catch { }\n }\n}\n\nexport async function warnAboutMissingEncryptionMapBackfills(modules: ModuleEntry[], resolver: PackageResolver): Promise<void> {\n if (!isEncryptionBackfillCheckEnabled()) return\n await checkEncryptionMapBackfills({\n loadDeclaredMaps: async () => {\n const declared: DeclaredEncryptionMap[] = []\n for (const entry of modules) declared.push(...(await loadModuleEncryptionMaps(entry, resolver)))\n return declared\n },\n loadMigrationSources: () => readModuleMigrationSources(modules, resolver),\n queryEncryptionMaps: queryEncryptionMapRows,\n warn: (message) => console.warn(message),\n })\n}\n\nexport interface DbOptions {\n quiet?: boolean\n}\n\nexport interface GreenfieldOptions extends DbOptions {\n yes: boolean\n}\n\nexport async function dbGenerate(resolver: PackageResolver, options: DbOptions = {}): Promise<void> {\n const modules = resolver.loadEnabledModules()\n const ordered = sortModules(modules)\n const results: string[] = []\n\n const sslConfig = getSslConfig()\n const usedFileNames = new Set<string>()\n\n for (const entry of ordered) {\n // Clear the global @Entity() decorator registry before loading this module's\n // entities. MikroORM's migrator reads MetadataStorage at createMigration()\n // time, so without this clear, every module's migration would include every\n // previously-loaded module's tables (see issue #1911).\n MetadataStorage.clear()\n\n const modId = entry.id\n const sanitizedModId = sanitizeModuleId(modId)\n const entities = await loadModuleEntities(entry, resolver)\n if (!entities.length) {\n if (entry.from === '@app') {\n results.push(formatResult(modId, 'no entities discovered', ''))\n }\n continue\n }\n\n const migrationsPath = getMigrationsPath(entry, resolver)\n fs.mkdirSync(migrationsPath, { recursive: true })\n\n const tableName = `mikro_orm_migrations_${sanitizedModId}`\n validateTableName(tableName)\n const snapshotName = getMigrationSnapshotName(resolver)\n const createInitialMigration = shouldCreateInitialModuleMigration(migrationsPath, snapshotName)\n\n const orm = await MikroORM.init<PostgreSqlDriver>({\n driver: PostgreSqlDriver,\n clientUrl: getClientUrl(),\n loggerFactory: () => createMinimalLogger(),\n dynamicImportProvider,\n entities,\n metadataProvider: ReflectMetadataProvider,\n migrations: {\n path: migrationsPath,\n glob: '!(*.d).{ts,js}',\n tableName,\n snapshotName,\n dropTables: false,\n },\n schemaGenerator: {\n disableForeignKeys: true,\n },\n pool: {\n min: 1,\n max: 3,\n idleTimeoutMillis: 30000,\n // acquireTimeoutMillis removed for v7 (pg.Pool doesn't support it; use connectionTimeoutMillis in driverOptions if needed)\n },\n driverOptions: sslConfig ? {\n ssl: sslConfig,\n } : undefined,\n })\n\n try {\n preserveUnconstrainedNumericSnapshots(orm.em.getDriver().getPlatform())\n const diff = await orm.migrator.create(undefined, false, createInitialMigration)\n if (diff && diff.fileName) {\n try {\n const orig = resolveGeneratedMigrationPath(diff.fileName, migrationsPath)\n const base = path.basename(orig)\n const dir = path.dirname(orig)\n const ext = path.extname(base)\n const stem = base.replace(ext, '')\n const suffix = `_${modId}`\n let candidate = stem.endsWith(suffix) ? base : `${stem}${suffix}${ext}`\n let dedupe = 1\n\n while (usedFileNames.has(path.join(dir, candidate))) {\n candidate = `${stem}${suffix}_${dedupe++}${ext}`\n }\n\n const newPath = path.join(dir, candidate)\n let content = fs.readFileSync(orig, 'utf8')\n content = makeConstraintDropsIdempotent(content)\n content = content.replace(\n /export class (Migration\\d+)/,\n `export class $1_${modId.replace(/[^a-zA-Z0-9]/g, '_')}`\n )\n fs.writeFileSync(newPath, content, 'utf8')\n if (newPath !== orig) fs.unlinkSync(orig)\n usedFileNames.add(newPath)\n results.push(formatResult(modId, `generated ${path.basename(newPath)}`, ''))\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n results.push(formatResult(modId, `generated ${path.basename(diff.fileName)} (rename failed: ${message})`, ''))\n }\n } else {\n results.push(formatResult(modId, 'no changes', ''))\n }\n } finally {\n await orm.close(true)\n }\n }\n\n console.log(results.join('\\n'))\n await warnAboutMissingEncryptionMapBackfills(ordered, resolver)\n}\n\nexport async function dbMigrate(resolver: PackageResolver, options: DbOptions = {}): Promise<void> {\n return runWithDatabaseExecutionContext({ kind: 'maintenance', tenantId: null, source: 'cli', operation: 'db:migrate' }, () => migrateModules(resolver, options))\n}\n\nasync function migrateModules(resolver: PackageResolver, _options: DbOptions): Promise<void> {\n const modules = resolver.loadEnabledModules()\n const ordered = sortModules(modules)\n const results: string[] = []\n const appliedMigrations: AppliedMigration[] = []\n const recoverHistory = shouldRecoverDatabaseMigrationReindex()\n let reconciled = false\n\n await beforeDatabaseMigrate()\n try {\n for (const entry of ordered) {\n const modId = entry.id\n const sanitizedModId = sanitizeModuleId(modId)\n const entities = await loadModuleEntities(entry, resolver)\n\n const migrationsPath = getMigrationsPath(entry, resolver)\n\n // Skip if no entities AND no migrations directory exists\n // (allows @app modules to run migrations even if entities can't be dynamically imported)\n if (!entities.length && !fs.existsSync(migrationsPath)) continue\n fs.mkdirSync(migrationsPath, { recursive: true })\n\n const tableName = `mikro_orm_migrations_${sanitizedModId}`\n validateTableName(tableName)\n\n // dbMigrate only runs existing migration files \u2014 entities are intentionally\n // omitted so MikroORM does not compare them against the snapshot and\n // auto-generate a phantom diff migration (that would duplicate tables\n // already created by committed migrations).\n const sslConfig = getSslConfig()\n const orm = await MikroORM.init<PostgreSqlDriver>({\n driver: PostgreSqlDriver,\n clientUrl: resolveDatabaseConnectionUrl('maintenance', getClientUrl()),\n loggerFactory: () => createMinimalLogger(),\n dynamicImportProvider,\n entities: [],\n metadataProvider: ReflectMetadataProvider,\n discovery: { warnWhenNoEntities: false },\n migrations: {\n path: migrationsPath,\n glob: '!(*.d).{ts,js}',\n tableName,\n snapshot: false,\n dropTables: false,\n },\n schemaGenerator: {\n disableForeignKeys: true,\n },\n pool: {\n min: 1,\n max: 3,\n idleTimeoutMillis: 30000,\n // acquireTimeoutMillis removed for v7 (pg.Pool doesn't support it; use connectionTimeoutMillis in driverOptions if needed)\n },\n driverOptions: sslConfig ? {\n ssl: sslConfig,\n } : undefined,\n })\n\n try {\n const migrator = orm.migrator as Migrator\n if (recoverHistory) {\n const executed = await migrator.getExecuted()\n for (const migration of executed) {\n appliedMigrations.push({ moduleId: modId, migrationsPath, name: migration.name })\n }\n }\n const pending = await migrator.getPending()\n if (!pending.length) {\n results.push(formatResult(modId, 'no pending migrations', ''))\n } else {\n const renderProgress = createProgressRenderer(pending.length)\n let applied = 0\n if (!QUIET_MODE) {\n process.stdout.write(` ${PROGRESS_EMOJI} ${modId}: ${renderProgress(applied)}`)\n }\n for (const migration of pending) {\n const migrationName =\n typeof migration === 'string' ? migration : migration.name\n await migrator.up(migrationName ? { migrations: [migrationName] } : undefined)\n if (migrationName) {\n appliedMigrations.push({\n moduleId: modId,\n migrationsPath,\n name: String(migrationName),\n filePath: typeof migration === 'string' ? null : migration.path ?? null,\n })\n }\n applied += 1\n if (!QUIET_MODE) {\n process.stdout.write(`\\r ${PROGRESS_EMOJI} ${modId}: ${renderProgress(applied)}`)\n }\n }\n if (!QUIET_MODE) process.stdout.write('\\n')\n results.push(\n formatResult(modId, `${pending.length} migration${pending.length === 1 ? '' : 's'} applied`, '')\n )\n }\n } finally {\n await orm.close(true)\n }\n }\n await afterDatabaseMigrate()\n reconciled = true\n } finally {\n console.log(results.join('\\n'))\n if (!recoverHistory || reconciled) {\n await dischargeQueryIndexReindexRequests(appliedMigrations, () => resolver.getAppDir())\n }\n }\n}\n\n/**\n * Runs after every module migrated and after `orm.close()`, so the rewrites the declarations\n * refer to are committed before the reindex is queued.\n *\n * Reached from a `finally`, so it also runs when a later migration threw: the migrations that\n * did apply already committed, and their declarations are the only record that their projections\n * are stale \u2014 a re-run cannot recover them, because `getPending()` no longer lists them. It must\n * therefore never throw, or it would replace the migration failure the operator needs to see.\n */\nexport async function dischargeQueryIndexReindexRequests(\n applied: readonly AppliedMigration[],\n resolveAppRoot?: () => string,\n): Promise<void> {\n if (!applied.length || !isMigrationReindexEnabled()) return\n\n try {\n const entityTypes = await collectQueryIndexReindexEntityTypes(applied, {\n importModule: dynamicImportProvider,\n onWarn: (message) => console.warn(message),\n })\n if (!entityTypes.length) return\n\n await requestQueryIndexReindex(entityTypes, {\n createContainer: async () => {\n const { bootstrapFromAppRoot } = await import('@open-mercato/shared/lib/bootstrap/dynamicLoader')\n await bootstrapFromAppRoot(resolveAppRoot?.())\n const { createRequestContainer } = await import('@open-mercato/shared/lib/di/container')\n return await createRequestContainer()\n },\n onInfo: (message) => {\n if (!QUIET_MODE) console.log(message)\n },\n onWarn: (message) => console.warn(message),\n })\n } catch (error) {\n console.warn(\n `[query_index] Could not determine which projections the migrations invalidated: ${\n error instanceof Error ? error.message : String(error)\n }`,\n )\n }\n}\n\nexport async function dbGreenfield(resolver: PackageResolver, options: GreenfieldOptions): Promise<void> {\n if (!options.yes) {\n console.error('This command will DELETE all data. Use --yes to confirm.')\n process.exit(1)\n }\n\n console.log('Cleaning up migrations and snapshots for greenfield setup...')\n\n const modules = resolver.loadEnabledModules()\n const ordered = sortModules(modules)\n const results: string[] = []\n const outputDir = resolver.getOutputDir()\n\n for (const entry of ordered) {\n const modId = entry.id\n const migrationsPath = getMigrationsPath(entry, resolver)\n\n if (fs.existsSync(migrationsPath)) {\n // Remove all migration files\n const migrationFiles = fs\n .readdirSync(migrationsPath)\n .filter((file) => file.endsWith('.ts') && file.startsWith('Migration'))\n\n for (const file of migrationFiles) {\n fs.unlinkSync(path.join(migrationsPath, file))\n }\n\n // Remove snapshot files\n const snapshotFiles = fs\n .readdirSync(migrationsPath)\n .filter((file) => file.endsWith('.json') && file.includes('snapshot'))\n\n for (const file of snapshotFiles) {\n fs.unlinkSync(path.join(migrationsPath, file))\n }\n\n if (migrationFiles.length > 0 || snapshotFiles.length > 0) {\n results.push(\n formatResult(modId, `cleaned ${migrationFiles.length} migrations, ${snapshotFiles.length} snapshots`, '')\n )\n } else {\n results.push(formatResult(modId, 'already clean', ''))\n }\n } else {\n results.push(formatResult(modId, 'no migrations directory', ''))\n }\n\n // Clean up checksum files using glob pattern\n if (fs.existsSync(outputDir)) {\n const files = fs.readdirSync(outputDir)\n const checksumFiles = files.filter((file) => file.endsWith('.checksum'))\n\n for (const file of checksumFiles) {\n fs.unlinkSync(path.join(outputDir, file))\n }\n\n if (checksumFiles.length > 0) {\n results.push(formatResult(modId, `cleaned ${checksumFiles.length} checksum files`, ''))\n }\n }\n }\n\n console.log(results.join('\\n'))\n\n // Drop per-module MikroORM migration tables to ensure clean slate\n console.log('Dropping per-module migration tables...')\n try {\n const { Client } = await import('pg')\n const client = new Client({ connectionString: getClientUrl(), ssl: getSslConfig() })\n await client.connect()\n try {\n await client.query('BEGIN')\n for (const entry of ordered) {\n const modId = entry.id\n const sanitizedModId = sanitizeModuleId(modId)\n const tableName = `mikro_orm_migrations_${sanitizedModId}`\n validateTableName(tableName)\n await client.query(`DROP TABLE IF EXISTS \"${tableName}\"`)\n console.log(` ${modId}: dropped table ${tableName}`)\n }\n await client.query('COMMIT')\n } catch (e) {\n await client.query('ROLLBACK')\n throw e\n } finally {\n try {\n await client.end()\n } catch { }\n }\n } catch (e) {\n console.error('Failed to drop migration tables:', (e as any)?.message || e)\n throw e\n }\n\n // Drop all existing user tables to ensure fresh CREATE-only migrations\n console.log('Dropping ALL public tables for true greenfield...')\n try {\n const { Client } = await import('pg')\n const client = new Client({ connectionString: getClientUrl(), ssl: getSslConfig() })\n await client.connect()\n try {\n const res = await client.query(`SELECT tablename FROM pg_tables WHERE schemaname = current_schema()`)\n const tables: string[] = (res.rows || []).map((r: any) => String(r.tablename))\n if (tables.length) {\n await client.query('BEGIN')\n try {\n await client.query(\"SET session_replication_role = 'replica'\")\n for (const t of tables) {\n await client.query(`DROP TABLE IF EXISTS ${quotePostgresIdentifier(t)} CASCADE`)\n }\n await client.query(\"SET session_replication_role = 'origin'\")\n await client.query('COMMIT')\n console.log(` Dropped ${tables.length} tables.`)\n } catch (e) {\n await client.query('ROLLBACK')\n throw e\n }\n } else {\n console.log(' No tables found to drop.')\n }\n } finally {\n try {\n await client.end()\n } catch { }\n }\n } catch (e) {\n console.error('Failed to drop public tables:', (e as any)?.message || e)\n throw e\n }\n\n // Generate fresh migrations for all modules\n console.log('Generating fresh migrations for all modules...')\n await dbGenerate(resolver)\n\n // Apply migrations\n console.log('Applying migrations...')\n await dbMigrate(resolver)\n\n console.log('Greenfield reset complete! Fresh migrations generated and applied.')\n}\n"],
5
+ "mappings": "AAAA,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,SAAS,qBAAqB;AAC9B,OAAO,QAAQ;AACf,SAAS,UAAU,uBAAoC;AACvD,SAAS,+BAA+B;AAExC,SAAS,wBAAwB;AACjC,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB,uBAAuB,8BAA8B,iCAAiC,6CAA6C;AAElK,SAAS,+BAA+B;AACxC,SAAS,6CAA6C;AACtD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAEP,MAAM,aAAa,QAAQ,IAAI,iBAAiB,OAAO,QAAQ,IAAI,kBAAkB;AACrF,MAAM,iBAAiB;AAEvB,SAAS,aAAa,OAAe,SAAiB,QAA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BAAM,OAAO,MAAM,yCAAyC;AAC5D,gBAAM,OAAO,MAAM,QAAQ;AAC3B,kBAAQ,IAAI,cAAc,OAAO,MAAM,UAAU;AAAA,QACnD,SAAS,GAAG;AACV,gBAAM,OAAO,MAAM,UAAU;AAC7B,gBAAM;AAAA,QACR;AAAA,MACF,OAAO;AACL,gBAAQ,IAAI,6BAA6B;AAAA,MAC3C;AAAA,IACF,UAAE;AACA,UAAI;AACF,cAAM,OAAO,IAAI;AAAA,MACnB,QAAQ;AAAA,MAAE;AAAA,IACZ;AAAA,EACF,SAAS,GAAG;AACV,YAAQ,MAAM,iCAAkC,GAAW,WAAW,CAAC;AACvE,UAAM;AAAA,EACR;AAGA,UAAQ,IAAI,gDAAgD;AAC5D,QAAM,WAAW,QAAQ;AAGzB,UAAQ,IAAI,wBAAwB;AACpC,QAAM,UAAU,QAAQ;AAExB,UAAQ,IAAI,oEAAoE;AAClF;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/cli",
3
- "version": "0.11.1-develop.8951.1.108985f0c9",
3
+ "version": "0.11.1-develop.8960.1.1345cbafca",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -60,10 +60,10 @@
60
60
  "@mikro-orm/decorators": "^7.1.14",
61
61
  "@mikro-orm/migrations": "^7.1.14",
62
62
  "@mikro-orm/postgresql": "^7.1.14",
63
- "@open-mercato/events": "0.11.1-develop.8951.1.108985f0c9",
64
- "@open-mercato/queue": "0.11.1-develop.8951.1.108985f0c9",
65
- "@open-mercato/shared": "0.11.1-develop.8951.1.108985f0c9",
66
- "@open-mercato/telemetry": "0.11.1-develop.8951.1.108985f0c9",
63
+ "@open-mercato/events": "0.11.1-develop.8960.1.1345cbafca",
64
+ "@open-mercato/queue": "0.11.1-develop.8960.1.1345cbafca",
65
+ "@open-mercato/shared": "0.11.1-develop.8960.1.1345cbafca",
66
+ "@open-mercato/telemetry": "0.11.1-develop.8960.1.1345cbafca",
67
67
  "cross-spawn": "^7.0.6",
68
68
  "minisearch": "7.2.0",
69
69
  "pg": "8.23.0",
@@ -75,10 +75,10 @@
75
75
  "typescript-js": "npm:typescript@6.0.3"
76
76
  },
77
77
  "peerDependencies": {
78
- "@open-mercato/shared": "0.11.1-develop.8951.1.108985f0c9"
78
+ "@open-mercato/shared": "0.11.1-develop.8960.1.1345cbafca"
79
79
  },
80
80
  "devDependencies": {
81
- "@open-mercato/shared": "0.11.1-develop.8951.1.108985f0c9",
81
+ "@open-mercato/shared": "0.11.1-develop.8960.1.1345cbafca",
82
82
  "@types/jest": "^30.0.0",
83
83
  "jest": "^30.4.2",
84
84
  "ts-jest": "^29.4.12"
@@ -4,6 +4,18 @@ import path from 'node:path'
4
4
  import { MikroORM } from '@mikro-orm/core'
5
5
  import { dbMigrate } from '../commands'
6
6
  import type { ModuleEntry, PackageResolver } from '../../resolver'
7
+ import type { RequestQueryIndexReindexDeps } from '../migration-reindex'
8
+
9
+ const bootstrapFromAppRoot = jest.fn<Promise<void>, [string | undefined]>()
10
+ const createRequestContainer = jest.fn<Promise<{ resolve: jest.Mock; dispose: jest.Mock }>, []>()
11
+
12
+ jest.mock('@open-mercato/shared/lib/bootstrap/dynamicLoader', () => ({
13
+ bootstrapFromAppRoot: (appRoot?: string) => bootstrapFromAppRoot(appRoot),
14
+ }))
15
+
16
+ jest.mock('@open-mercato/shared/lib/di/container', () => ({
17
+ createRequestContainer: () => createRequestContainer(),
18
+ }))
7
19
 
8
20
  const collectQueryIndexReindexEntityTypes = jest.fn<Promise<string[]>, [any, any]>()
9
21
  const requestQueryIndexReindex = jest.fn<Promise<{ requested: string[]; queued: boolean }>, [any, any]>()
@@ -109,6 +121,9 @@ describe('dbMigrate discharges query-index reindex declarations', () => {
109
121
  initSpy = jest.spyOn(MikroORM, 'init').mockImplementation((...args: any[]) => ormInit(...args))
110
122
  collectQueryIndexReindexEntityTypes.mockReset()
111
123
  requestQueryIndexReindex.mockReset()
124
+ bootstrapFromAppRoot.mockReset()
125
+ bootstrapFromAppRoot.mockResolvedValue(undefined)
126
+ createRequestContainer.mockReset()
112
127
  isMigrationReindexEnabled.mockReset()
113
128
  isMigrationReindexEnabled.mockReturnValue(true)
114
129
  collectQueryIndexReindexEntityTypes.mockResolvedValue(['customers:customer_dictionary_entry'])
@@ -201,6 +216,74 @@ describe('dbMigrate discharges query-index reindex declarations', () => {
201
216
  expect(collectQueryIndexReindexEntityTypes).not.toHaveBeenCalled()
202
217
  expect(requestQueryIndexReindex).not.toHaveBeenCalled()
203
218
  })
219
+
220
+ it('does not resolve the application directory when no migrations ran', async () => {
221
+ const moduleA = { id: 'alpha', dir: createTempModule('alpha') }
222
+ stubOrmsFor({ alpha: { pending: [] } })
223
+ const resolver = createMockResolver([moduleA])
224
+ const getAppDir = jest.spyOn(resolver, 'getAppDir').mockImplementation(() => {
225
+ throw new Error('application directory unavailable')
226
+ })
227
+
228
+ await expect(dbMigrate(resolver)).resolves.toBeUndefined()
229
+
230
+ expect(getAppDir).not.toHaveBeenCalled()
231
+ expect(bootstrapFromAppRoot).not.toHaveBeenCalled()
232
+ expect(requestQueryIndexReindex).not.toHaveBeenCalled()
233
+ })
234
+
235
+ it('bootstraps DI after migrations and reconciliation, before creating the reindex container', async () => {
236
+ const moduleA = { id: 'alpha', dir: createTempModule('alpha') }
237
+ stubOrmsFor({ alpha: { pending: ['Migration20260901120000_reindex_alpha'] } })
238
+ recoverHistory.mockReturnValue(true)
239
+ let bootstrapped = false
240
+ bootstrapFromAppRoot.mockImplementation(async () => {
241
+ expect(ormCloses).toEqual(['alpha'])
242
+ expect(afterMigrate).toHaveBeenCalledTimes(1)
243
+ bootstrapped = true
244
+ })
245
+ const emitEvent = jest.fn().mockResolvedValue(undefined)
246
+ const dispose = jest.fn().mockResolvedValue(undefined)
247
+ createRequestContainer.mockImplementation(async () => {
248
+ if (!bootstrapped) throw new Error('[Bootstrap] DI registrars not registered.')
249
+ return { resolve: jest.fn().mockReturnValue({ emitEvent }), dispose }
250
+ })
251
+ const actual = jest.requireActual<typeof import('../migration-reindex')>('../migration-reindex')
252
+ requestQueryIndexReindex.mockImplementationOnce((entityTypes: string[], deps: RequestQueryIndexReindexDeps) =>
253
+ actual.requestQueryIndexReindex(entityTypes, deps),
254
+ )
255
+
256
+ await dbMigrate(createMockResolver([moduleA]))
257
+
258
+ expect(bootstrapFromAppRoot).toHaveBeenCalledTimes(1)
259
+ expect(bootstrapFromAppRoot).toHaveBeenCalledWith('/tmp/test-app')
260
+ expect(emitEvent).toHaveBeenCalledWith(
261
+ 'query_index.reindex',
262
+ { entityType: 'customers:customer_dictionary_entry', allowAllTenants: true, force: false },
263
+ { persistent: true, tenantId: null, allowAllTenants: true },
264
+ )
265
+ expect(dispose).toHaveBeenCalledTimes(1)
266
+ expect(warnSpy).not.toHaveBeenCalled()
267
+ })
268
+
269
+ it('keeps manual reindex instructions when bootstrap fails without failing migrations', async () => {
270
+ const moduleA = { id: 'alpha', dir: createTempModule('alpha') }
271
+ stubOrmsFor({ alpha: { pending: ['Migration20260901120000_reindex_alpha'] } })
272
+ bootstrapFromAppRoot.mockRejectedValue(new Error('generated registry unavailable'))
273
+ const actual = jest.requireActual<typeof import('../migration-reindex')>('../migration-reindex')
274
+ requestQueryIndexReindex.mockImplementationOnce((entityTypes: string[], deps: RequestQueryIndexReindexDeps) =>
275
+ actual.requestQueryIndexReindex(entityTypes, deps),
276
+ )
277
+
278
+ await expect(dbMigrate(createMockResolver([moduleA]))).resolves.toBeUndefined()
279
+
280
+ expect(createRequestContainer).not.toHaveBeenCalled()
281
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('generated registry unavailable'))
282
+ expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining(
283
+ 'mercato query_index rebuild --entity customers:customer_dictionary_entry --global',
284
+ ))
285
+ })
286
+
204
287
  it('preflights before opening module ORMs and reconciles even with no pending migrations', async () => {
205
288
  recoverHistory.mockReturnValue(true)
206
289
  const module = { id: 'alpha', dir: createTempModule('alpha') }
@@ -256,5 +339,4 @@ describe('dbMigrate discharges query-index reindex declarations', () => {
256
339
  expect(ormInit).not.toHaveBeenCalled()
257
340
  expect(requestQueryIndexReindex).not.toHaveBeenCalled()
258
341
  })
259
-
260
342
  })