@open-mercato/cli 0.11.1-develop.8910.1.d07a49d70a → 0.11.1-develop.8929.1.493f6c653c
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.
- package/.turbo/turbo-build.log +6 -2
- package/dist/agentic/guides/module-facts.json +356 -399
- package/dist/agentic/guides/module-facts.v2.json +356 -399
- package/dist/agentic/guides/modules/agent_orchestrator/active-extension-bindings.md +1 -1
- package/dist/agentic/guides/modules/agent_orchestrator/exact-override-targets.md +1 -1
- package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
- package/dist/agentic/guides/modules/agent_orchestrator/workers.md +1 -1
- package/dist/agentic/guides/modules/ai_assistant/exact-override-targets.md +2 -2
- package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
- package/dist/agentic/guides/modules/ai_assistant/workers.md +2 -2
- package/dist/agentic/guides/modules/api_docs/index.md +1 -1
- package/dist/agentic/guides/modules/api_keys/index.md +1 -1
- package/dist/agentic/guides/modules/assisted_selling/index.md +1 -1
- package/dist/agentic/guides/modules/attachments/index.md +1 -1
- package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
- package/dist/agentic/guides/modules/auth/entities.md +1 -0
- package/dist/agentic/guides/modules/auth/index.md +2 -2
- package/dist/agentic/guides/modules/auth/umes-hosts.md +1 -0
- package/dist/agentic/guides/modules/availability/index.md +1 -1
- package/dist/agentic/guides/modules/backups/index.md +1 -1
- package/dist/agentic/guides/modules/business_rules/index.md +1 -1
- package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
- package/dist/agentic/guides/modules/cart/index.md +1 -1
- package/dist/agentic/guides/modules/catalog/domain-commands.md +0 -1
- package/dist/agentic/guides/modules/catalog/index.md +1 -1
- package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
- package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
- package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
- package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
- package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
- package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
- package/dist/agentic/guides/modules/channel_ms365/index.md +1 -1
- package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
- package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
- package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
- package/dist/agentic/guides/modules/checkout/index.md +1 -1
- package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
- package/dist/agentic/guides/modules/configs/index.md +1 -1
- package/dist/agentic/guides/modules/content/index.md +1 -1
- package/dist/agentic/guides/modules/currencies/index.md +1 -1
- package/dist/agentic/guides/modules/customer_accounts/exact-override-targets.md +4 -4
- package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
- package/dist/agentic/guides/modules/customer_accounts/workers.md +4 -4
- package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
- package/dist/agentic/guides/modules/customers/index.md +1 -1
- package/dist/agentic/guides/modules/dashboards/index.md +1 -1
- package/dist/agentic/guides/modules/data_sync/index.md +1 -1
- package/dist/agentic/guides/modules/design_system/index.md +1 -1
- package/dist/agentic/guides/modules/devices/index.md +1 -1
- package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
- package/dist/agentic/guides/modules/directory/index.md +1 -1
- package/dist/agentic/guides/modules/documents/index.md +1 -1
- package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
- package/dist/agentic/guides/modules/entities/index.md +1 -1
- package/dist/agentic/guides/modules/eudr/index.md +1 -1
- package/dist/agentic/guides/modules/events/index.md +1 -1
- package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
- package/dist/agentic/guides/modules/forms/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
- package/dist/agentic/guides/modules/generators/index.md +1 -1
- package/dist/agentic/guides/modules/gus_regon/index.md +1 -1
- package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
- package/dist/agentic/guides/modules/integrations/index.md +1 -1
- package/dist/agentic/guides/modules/ledger/index.md +1 -1
- package/dist/agentic/guides/modules/maintenance/index.md +1 -1
- package/dist/agentic/guides/modules/messages/index.md +1 -1
- package/dist/agentic/guides/modules/notifications/index.md +1 -1
- package/dist/agentic/guides/modules/onboarding/index.md +1 -1
- package/dist/agentic/guides/modules/payment_gateways/exact-override-targets.md +1 -1
- package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
- package/dist/agentic/guides/modules/payment_gateways/workers.md +1 -1
- package/dist/agentic/guides/modules/perspectives/index.md +1 -1
- package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
- package/dist/agentic/guides/modules/planner/index.md +1 -1
- package/dist/agentic/guides/modules/portal/index.md +1 -1
- package/dist/agentic/guides/modules/progress/index.md +1 -1
- package/dist/agentic/guides/modules/promotions/index.md +1 -1
- package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
- package/dist/agentic/guides/modules/query_index/index.md +1 -1
- package/dist/agentic/guides/modules/record_locks/index.md +1 -1
- package/dist/agentic/guides/modules/resources/index.md +1 -1
- package/dist/agentic/guides/modules/sales/exact-override-targets.md +4 -4
- package/dist/agentic/guides/modules/sales/index.md +1 -1
- package/dist/agentic/guides/modules/sales/setup.md +1 -1
- package/dist/agentic/guides/modules/sales_invoices_gl_posting/index.md +1 -1
- package/dist/agentic/guides/modules/scheduler/di-registrations-rich.md +3 -3
- package/dist/agentic/guides/modules/scheduler/di-service-tokens.md +3 -3
- package/dist/agentic/guides/modules/scheduler/exact-override-targets.md +4 -9
- package/dist/agentic/guides/modules/scheduler/index.md +3 -4
- package/dist/agentic/guides/modules/scheduler/workers.md +1 -1
- package/dist/agentic/guides/modules/search/di-registrations-rich.md +4 -4
- package/dist/agentic/guides/modules/search/di-service-tokens.md +13 -0
- package/dist/agentic/guides/modules/search/exact-override-targets.md +4 -4
- package/dist/agentic/guides/modules/search/index.md +3 -2
- package/dist/agentic/guides/modules/security/index.md +1 -1
- package/dist/agentic/guides/modules/seeds/index.md +1 -1
- package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
- package/dist/agentic/guides/modules/sso/index.md +1 -1
- package/dist/agentic/guides/modules/staff/index.md +1 -1
- package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
- package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
- package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
- package/dist/agentic/guides/modules/sync_shopify/index.md +1 -1
- package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
- package/dist/agentic/guides/modules/telemetry/index.md +1 -1
- package/dist/agentic/guides/modules/tenant_boundaries/generator-plugins.md +11 -0
- package/dist/agentic/guides/modules/tenant_boundaries/index.md +13 -0
- package/dist/agentic/guides/modules/tenant_boundaries/owned-contract-module-metadata.md +11 -0
- package/dist/agentic/guides/modules/tillio/index.md +1 -1
- package/dist/agentic/guides/modules/translations/index.md +1 -1
- package/dist/agentic/guides/modules/upgrade_actions/index.md +1 -1
- package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
- package/dist/agentic/guides/modules/webhooks/index.md +1 -1
- package/dist/agentic/guides/modules/wms/index.md +1 -1
- package/dist/agentic/guides/modules/workflows/index.md +1 -1
- package/dist/agentic/guides/reference-module-facts.json +2 -2
- package/dist/agentic/guides/reference-modules/example/index.md +1 -1
- package/dist/agentic/guides/upstream/manifest.json +1 -1
- package/dist/agentic/shared/AGENTS.md.template +3 -3
- package/dist/agentic/shared/ai/harness/cases.json +4 -4
- package/dist/bin.js +6 -3
- package/dist/bin.js.map +2 -2
- package/dist/i18n/de.json +5 -1
- package/dist/i18n/en.json +5 -1
- package/dist/i18n/es.json +5 -1
- package/dist/i18n/ko.json +5 -1
- package/dist/i18n/pl.json +5 -1
- package/dist/lib/cli-bootstrap-mode.js +10 -1
- package/dist/lib/cli-bootstrap-mode.js.map +2 -2
- package/dist/lib/db/commands.js +18 -3
- package/dist/lib/db/commands.js.map +2 -2
- package/dist/lib/db/maintenance-client.js +72 -0
- package/dist/lib/db/maintenance-client.js.map +7 -0
- package/dist/lib/generate-watch-structure.js +2 -1
- package/dist/lib/generate-watch-structure.js.map +2 -2
- package/dist/lib/generators/database-declarations.js +21 -0
- package/dist/lib/generators/database-declarations.js.map +7 -0
- package/dist/lib/generators/module-registry.js +19 -3
- package/dist/lib/generators/module-registry.js.map +2 -2
- package/dist/lib/init-existing-database.js +91 -1
- package/dist/lib/init-existing-database.js.map +2 -2
- package/dist/lib/init-i18n.js +13 -0
- package/dist/lib/init-i18n.js.map +7 -0
- package/dist/lib/init-secrets.js +2 -10
- package/dist/lib/init-secrets.js.map +2 -2
- package/dist/lib/scheduler-supervisor.js +47 -7
- package/dist/lib/scheduler-supervisor.js.map +2 -2
- package/dist/lib/server-start-lock.js +120 -21
- package/dist/lib/server-start-lock.js.map +2 -2
- package/dist/lib/worker-job-handler.js +36 -26
- package/dist/lib/worker-job-handler.js.map +2 -2
- package/dist/mercato.js +93 -54
- package/dist/mercato.js.map +3 -3
- package/package.json +7 -7
- package/src/__tests__/mercato.test.ts +166 -9
- package/src/bin.ts +10 -4
- package/src/i18n/de.json +5 -1
- package/src/i18n/en.json +5 -1
- package/src/i18n/es.json +5 -1
- package/src/i18n/ko.json +5 -1
- package/src/i18n/pl.json +5 -1
- package/src/lib/__tests__/cli-bootstrap-mode.test.ts +76 -1
- package/src/lib/__tests__/generate-watch-structure.test.ts +26 -0
- package/src/lib/__tests__/rotation-kms-warning-presentation.test.ts +1 -1
- package/src/lib/__tests__/scheduler-supervisor.test.ts +107 -0
- package/src/lib/__tests__/server-start-lock.test.ts +400 -0
- package/src/lib/__tests__/worker-job-handler.database.test.ts +76 -0
- package/src/lib/cli-bootstrap-mode.ts +12 -2
- package/src/lib/db/__tests__/commands.migrate-reindex.test.ts +72 -1
- package/src/lib/db/__tests__/maintenance-client.test.ts +70 -0
- package/src/lib/db/commands.ts +20 -6
- package/src/lib/db/maintenance-client.ts +54 -0
- package/src/lib/generate-watch-structure.ts +2 -1
- package/src/lib/generators/__tests__/database-declarations.test.ts +69 -0
- package/src/lib/generators/__tests__/incremental-registry.test.ts +1 -1
- package/src/lib/generators/__tests__/module-subset.test.ts +17 -1
- package/src/lib/generators/database-declarations.ts +19 -0
- package/src/lib/generators/module-registry.ts +23 -4
- package/src/lib/init-existing-database.ts +107 -0
- package/src/lib/init-i18n.ts +11 -0
- package/src/lib/init-secrets.ts +2 -12
- package/src/lib/scheduler-supervisor.ts +40 -7
- package/src/lib/server-start-lock.ts +170 -19
- package/src/lib/worker-job-handler.ts +39 -28
- package/src/mercato.ts +92 -53
- package/dist/agentic/guides/modules/scheduler/cli-commands.md +0 -15
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"projectionKind": "activated-reference",
|
|
5
5
|
"sourceKind": "local-reference",
|
|
6
6
|
"runtimeSelected": false,
|
|
7
|
-
"sourceFingerprint": "
|
|
7
|
+
"sourceFingerprint": "23d16301deb79c2f2553e6f202cb7480a041d133cf544682eb40dab1b8082f4c",
|
|
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.
|
|
1194
|
+
"coreVersion": "0.11.1-develop.8929.1.493f6c653c",
|
|
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
|
|
2
|
+
<!-- generated from local reference src/modules/example; source-fingerprint 23d16301deb79c2f2553e6f202cb7480a041d133cf544682eb40dab1b8082f4c; 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.
|
|
3
|
+
"generator": "@open-mercato/cli@0.11.1-develop.8929.1.493f6c653c",
|
|
4
4
|
"files": {
|
|
5
5
|
"AGENTS.md": "b5dc75ec890c2e8cc834cf36861be3b7b78ab1a714ecb83c8160f3d3e8834140",
|
|
6
6
|
"BACKWARD_COMPATIBILITY.md": "ded01a2a24e7a97dbe0883ebeee4358ba05d85eb0906ac097d7a22c4a5b18883"
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
- Never edit `node_modules`/`.mercato/generated/**`/generated facts/shipped migrations.
|
|
25
25
|
- Never use cross-module ORM relations; use IDs/snapshots/events/enrichers/extensions/optional DI.
|
|
26
26
|
- Never use raw admin `fetch`/`<form>`, ad hoc crypto/cache/queues, role-name guards, or direct mutations when helpers exist.
|
|
27
|
-
- Never hard-code user strings/status colors
|
|
27
|
+
- Never hard-code user strings/status colors, expose secrets/transcripts, or guess contracts.
|
|
28
28
|
|
|
29
29
|
## Validation
|
|
30
30
|
|
|
@@ -32,7 +32,7 @@ Broad: `yarn ci` (generate, typecheck, lint, ds:check, test, build — stops at
|
|
|
32
32
|
|
|
33
33
|
## Production Deployment
|
|
34
34
|
|
|
35
|
-
Route production
|
|
35
|
+
Route production readiness/maintenance pages to `architecture` and `.ai/guides/production-deployment.md`. During routing, do not open `.env*`. Use tracked `.env.example` names/comments. Never read or report live `.env` values. Ask before credentials, billable infrastructure, or live deployment.
|
|
36
36
|
|
|
37
37
|
## Three-Axis Context Assembler
|
|
38
38
|
|
|
@@ -106,7 +106,7 @@ Read `.agents/skills/<id>/SKILL.md` AND any `.ai/skills/<id>/SKILL.md` override.
|
|
|
106
106
|
|
|
107
107
|
### Token-Efficient Assembly Policy
|
|
108
108
|
|
|
109
|
-
- Read
|
|
109
|
+
- Read matched guides once, then required skills, references, and facts.
|
|
110
110
|
- `spec-pr` reads template via spec-delivery.
|
|
111
111
|
- Inspect app call sites before bounded `framework-context`. Skip it for additive page/form/table/conflict UI.
|
|
112
112
|
- Never bulk-read guide, skill, fact, or source trees.
|
|
@@ -520,7 +520,7 @@
|
|
|
520
520
|
],
|
|
521
521
|
"maxContextFiles": 8,
|
|
522
522
|
"maxInitialContextBytes": 65536,
|
|
523
|
-
"maxTotalContextBytes":
|
|
523
|
+
"maxTotalContextBytes": 142902,
|
|
524
524
|
"relatedCases": [
|
|
525
525
|
"OMH-008"
|
|
526
526
|
]
|
|
@@ -4557,7 +4557,7 @@
|
|
|
4557
4557
|
],
|
|
4558
4558
|
"maxContextFiles": 5,
|
|
4559
4559
|
"maxInitialContextBytes": 40960,
|
|
4560
|
-
"maxTotalContextBytes":
|
|
4560
|
+
"maxTotalContextBytes": 135457,
|
|
4561
4561
|
"relatedCases": [
|
|
4562
4562
|
"OMH-058"
|
|
4563
4563
|
],
|
|
@@ -5148,7 +5148,7 @@
|
|
|
5148
5148
|
],
|
|
5149
5149
|
"maxContextFiles": 8,
|
|
5150
5150
|
"maxInitialContextBytes": 65536,
|
|
5151
|
-
"maxTotalContextBytes":
|
|
5151
|
+
"maxTotalContextBytes": 142902,
|
|
5152
5152
|
"relatedCases": [
|
|
5153
5153
|
"OMH-065"
|
|
5154
5154
|
]
|
|
@@ -22128,7 +22128,7 @@
|
|
|
22128
22128
|
],
|
|
22129
22129
|
"maxContextFiles": 16,
|
|
22130
22130
|
"maxInitialContextBytes": 74752,
|
|
22131
|
-
"maxTotalContextBytes":
|
|
22131
|
+
"maxTotalContextBytes": 388608,
|
|
22132
22132
|
"relatedCases": [
|
|
22133
22133
|
"OMH-030",
|
|
22134
22134
|
"OMH-088",
|
package/dist/bin.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { isTelemetryBackendEnabled } from "@open-mercato/shared/lib/telemetry/runtime";
|
|
3
3
|
import { installNextSubpathResolveHook } from "@open-mercato/shared/lib/bootstrap/next-subpath-resolve-hook";
|
|
4
|
-
import { resolveCliBootstrapMode } from "./lib/cli-bootstrap-mode.js";
|
|
4
|
+
import { requiresDatabaseRuntimeForMigration, resolveCliBootstrapMode } from "./lib/cli-bootstrap-mode.js";
|
|
5
5
|
import { flushBeforeExit } from "./lib/flush-before-exit.js";
|
|
6
6
|
import { runWithRotationKmsWarningPresentation } from "./lib/rotation-kms-warning-presentation.js";
|
|
7
7
|
function assertNode24Runtime() {
|
|
@@ -51,10 +51,13 @@ async function tryBootstrap(mode) {
|
|
|
51
51
|
async function main() {
|
|
52
52
|
assertNode24Runtime();
|
|
53
53
|
installNextSubpathResolveHook();
|
|
54
|
-
const
|
|
55
|
-
if (
|
|
54
|
+
const requestedBootstrapMode = resolveCliBootstrapMode(process.argv);
|
|
55
|
+
if (requestedBootstrapMode !== "none") {
|
|
56
56
|
const { loadAppEnv } = await import("./lib/load-env.js");
|
|
57
57
|
await loadAppEnv();
|
|
58
|
+
}
|
|
59
|
+
const bootstrapMode = requestedBootstrapMode === "database-migrate" ? requiresDatabaseRuntimeForMigration() ? "full" : "none" : requestedBootstrapMode;
|
|
60
|
+
if (bootstrapMode !== "none") {
|
|
58
61
|
if (isTelemetryBackendEnabled()) {
|
|
59
62
|
const { initTelemetry } = await import("@open-mercato/telemetry");
|
|
60
63
|
await initTelemetry();
|
package/dist/bin.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/bin.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * CLI binary entry point for @open-mercato/cli package.\n *\n * Called from within a Next.js app directory as: yarn mercato <command>\n * Uses dynamic app resolution to find generated files at .mercato/generated/\n */\nimport { isTelemetryBackendEnabled } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { installNextSubpathResolveHook } from '@open-mercato/shared/lib/bootstrap/next-subpath-resolve-hook'\nimport { resolveCliBootstrapMode, type CliBootstrapMode } from './lib/cli-bootstrap-mode.js'\nimport { flushBeforeExit } from './lib/flush-before-exit.js'\nimport { runWithRotationKmsWarningPresentation } from './lib/rotation-kms-warning-presentation.js'\n// `run` is imported dynamically inside `main()` so telemetry can initialize\n// before the mercato entry (and its Postgres driver) loads \u2014 see main().\n\nfunction assertNode24Runtime(): void {\n const detectedNodeVersion = process.versions.node\n const majorVersion = Number.parseInt(detectedNodeVersion.split('.')[0] ?? '0', 10)\n if (majorVersion >= 24) {\n return\n }\n throw new Error(\n [\n 'Unsupported Node.js runtime.',\n `Cause: Detected Node ${detectedNodeVersion}, but Open Mercato requires Node 24.x.`,\n 'What to do: switch your shell to Node 24 (for example `nvm use 24`), run `yarn install`, then retry.',\n ].join(' '),\n )\n}\n\nasync function tryBootstrap(mode:
|
|
5
|
-
"mappings": "AAMA,SAAS,iCAAiC;AAC1C,SAAS,qCAAqC;AAC9C,SAAS,+BAAsD;
|
|
4
|
+
"sourcesContent": ["/**\n * CLI binary entry point for @open-mercato/cli package.\n *\n * Called from within a Next.js app directory as: yarn mercato <command>\n * Uses dynamic app resolution to find generated files at .mercato/generated/\n */\nimport { isTelemetryBackendEnabled } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { installNextSubpathResolveHook } from '@open-mercato/shared/lib/bootstrap/next-subpath-resolve-hook'\nimport { requiresDatabaseRuntimeForMigration, resolveCliBootstrapMode, type CliBootstrapMode } from './lib/cli-bootstrap-mode.js'\nimport { flushBeforeExit } from './lib/flush-before-exit.js'\nimport { runWithRotationKmsWarningPresentation } from './lib/rotation-kms-warning-presentation.js'\n// `run` is imported dynamically inside `main()` so telemetry can initialize\n// before the mercato entry (and its Postgres driver) loads \u2014 see main().\n\nfunction assertNode24Runtime(): void {\n const detectedNodeVersion = process.versions.node\n const majorVersion = Number.parseInt(detectedNodeVersion.split('.')[0] ?? '0', 10)\n if (majorVersion >= 24) {\n return\n }\n throw new Error(\n [\n 'Unsupported Node.js runtime.',\n `Cause: Detected Node ${detectedNodeVersion}, but Open Mercato requires Node 24.x.`,\n 'What to do: switch your shell to Node 24 (for example `nvm use 24`), run `yarn install`, then retry.',\n ].join(' '),\n )\n}\n\nasync function tryBootstrap(mode: Extract<CliBootstrapMode, 'dev-supervisor' | 'full'>): Promise<boolean> {\n try {\n // Use the CLI resolver to find the app directory (handles monorepo detection)\n const { createResolver } = await import('./lib/resolver.js')\n const resolver = createResolver()\n const appDir = resolver.getAppDir()\n\n if (mode === 'dev-supervisor') {\n const {\n canUseLightweightDevSupervisor,\n loadDevSupervisorManifest,\n registerDevSupervisorManifest,\n } = await import(\n './lib/dev-supervisor-manifest.js'\n )\n const manifest = loadDevSupervisorManifest(appDir)\n if (canUseLightweightDevSupervisor(manifest)) {\n registerDevSupervisorManifest(manifest)\n return true\n }\n }\n\n const { bootstrapFromAppRoot } = await import('@open-mercato/shared/lib/bootstrap/dynamicLoader')\n const { registerCliModules } = await import('./mercato.js')\n const data = await bootstrapFromAppRoot(appDir)\n // Register CLI modules directly to avoid module resolution issues\n registerCliModules(data.modules)\n return true\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n // Check if the error is about missing generated files\n if (\n message.includes('dev-supervisor.generated.json') ||\n (\n message.includes('Cannot find module') &&\n (message.includes('/generated/') || message.includes('.generated') || message.includes('.mercato'))\n )\n ) {\n return false\n }\n // Re-throw other errors\n throw err\n }\n}\n\nasync function main(): Promise<void> {\n assertNode24Runtime()\n // Commands and workers run in plain Node, where a bare `next/<subpath>` such\n // as `next/dynamic` or `next/link` does not resolve (#7102). Install the\n // retry-with-`.js` hook before any package dist can be imported.\n installNextSubpathResolveHook()\n const requestedBootstrapMode = resolveCliBootstrapMode(process.argv)\n\n if (requestedBootstrapMode !== 'none') {\n // Load the app's `.env` BEFORE initTelemetry(): `run()` only dotenv-loads it\n // later (ensureEnvLoaded), which is too late \u2014 TELEMETRY_BACKEND set only in\n // `.env` would silently resolve to `noop` for worker/scheduler processes.\n // The loader touches only the resolver + dotenv (no `pg`), preserving the\n // instrumentation load-order guarantee below.\n const { loadAppEnv } = await import('./lib/load-env.js')\n await loadAppEnv()\n }\n\n const bootstrapMode = requestedBootstrapMode === 'database-migrate'\n ? (requiresDatabaseRuntimeForMigration() ? 'full' : 'none')\n : requestedBootstrapMode\n\n if (bootstrapMode !== 'none') {\n // Initialize telemetry BEFORE bootstrapping the app graph. Bootstrap and the\n // per-command handlers load MikroORM's Postgres driver \u2192 `pg`, and the\n // OpenTelemetry pg/undici auto-instrumentation only records spans for a\n // driver required AFTER the SDK has started. Registering here \u2014 ahead of any\n // app module \u2014 is what lets long-running worker/scheduler processes emit DB\n // spans (not just the bullmq-otel add/process envelope). The package itself\n // is not imported unless an explicit supported backend is selected.\n if (isTelemetryBackendEnabled()) {\n const { initTelemetry } = await import('@open-mercato/telemetry')\n await initTelemetry()\n }\n\n const bootstrapSucceeded = await tryBootstrap(bootstrapMode)\n if (!bootstrapSucceeded) {\n console.error('\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557')\n console.error('\u2551 Generated files not found! \u2551')\n console.error('\u2551 \u2551')\n console.error('\u2551 The CLI requires generated files to discover modules. \u2551')\n console.error('\u2551 Please run the following command first: \u2551')\n console.error('\u2551 \u2551')\n console.error('\u2551 yarn mercato generate \u2551')\n console.error('\u2551 \u2551')\n console.error('\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D')\n process.exit(1)\n }\n }\n\n // Dynamic import (not a top-level static import) so the mercato entry \u2014 and the\n // Postgres driver it pulls in \u2014 loads only after initTelemetry() above.\n const { run } = await import('./mercato.js')\n const code = await run(process.argv)\n // Flush the coalesced browser broadcasts, then spans/logs, for commands that\n // return (workers block forever and flush via their own shutdown handler instead).\n await flushBeforeExit()\n process.exit(code ?? 0)\n}\n\nrunWithRotationKmsWarningPresentation(process.argv, main).catch((error: unknown) => {\n if (error instanceof Error) {\n console.error(error.message)\n } else {\n console.error(error)\n }\n process.exit(1)\n})\n"],
|
|
5
|
+
"mappings": "AAMA,SAAS,iCAAiC;AAC1C,SAAS,qCAAqC;AAC9C,SAAS,qCAAqC,+BAAsD;AACpG,SAAS,uBAAuB;AAChC,SAAS,6CAA6C;AAItD,SAAS,sBAA4B;AACnC,QAAM,sBAAsB,QAAQ,SAAS;AAC7C,QAAM,eAAe,OAAO,SAAS,oBAAoB,MAAM,GAAG,EAAE,CAAC,KAAK,KAAK,EAAE;AACjF,MAAI,gBAAgB,IAAI;AACtB;AAAA,EACF;AACA,QAAM,IAAI;AAAA,IACR;AAAA,MACE;AAAA,MACA,wBAAwB,mBAAmB;AAAA,MAC3C;AAAA,IACF,EAAE,KAAK,GAAG;AAAA,EACZ;AACF;AAEA,e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A,UAAM,qBAAqB,MAAM,aAAa,aAAa;AAC3D,QAAI,CAAC,oBAAoB;AACvB,cAAQ,MAAM,gaAAuE;AACrF,cAAQ,MAAM,iFAAuE;AACrF,cAAQ,MAAM,iFAAuE;AACrF,cAAQ,MAAM,gFAAsE;AACpF,cAAQ,MAAM,gFAAsE;AACpF,cAAQ,MAAM,iFAAuE;AACrF,cAAQ,MAAM,gFAAsE;AACpF,cAAQ,MAAM,iFAAuE;AACrF,cAAQ,MAAM,gaAAuE;AACrF,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AAIA,QAAM,EAAE,IAAI,IAAI,MAAM,OAAO,cAAc;AAC3C,QAAM,OAAO,MAAM,IAAI,QAAQ,IAAI;AAGnC,QAAM,gBAAgB;AACtB,UAAQ,KAAK,QAAQ,CAAC;AACxB;AAEA,sCAAsC,QAAQ,MAAM,IAAI,EAAE,MAAM,CAAC,UAAmB;AAClF,MAAI,iBAAiB,OAAO;AAC1B,YAAQ,MAAM,MAAM,OAAO;AAAA,EAC7B,OAAO;AACL,YAAQ,MAAM,KAAK;AAAA,EACrB;AACA,UAAQ,KAAK,CAAC;AAChB,CAAC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/i18n/de.json
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
{
|
|
2
|
+
"cli.init.errors.concurrentInitialization": "Für diese Datenbank wurde bereits eine andere Initialisierung gestartet. Prüfen Sie deren Ergebnis vor einem erneuten Versuch.",
|
|
3
|
+
"cli.init.errors.incompleteInitialization": "Die Initialisierung von {database} wurde gestartet, aber noch nicht abgeschlossen. Prüfen Sie die bisherigen Initialisierungsprotokolle. Verwenden Sie --reinstall nur, wenn Sie die Datenbank löschen und neu beginnen möchten.",
|
|
4
|
+
"cli.init.errors.initializationStateMissing": "Der Abschluss dieses Initialisierungsversuchs konnte nicht gespeichert werden. Prüfen Sie die Datenbank und die Initialisierungsprotokolle vor einem erneuten Versuch.",
|
|
2
5
|
"cli.init.errors.superadminPasswordPolicy": "Das Superadmin-Passwort für die Produktion erfüllt die konfigurierte Passwortrichtlinie nicht. Flags zum Umgehen der Passwortrichtlinie gelten nur außerhalb der Produktion.",
|
|
3
|
-
"cli.init.errors.superadminPasswordRequired": "Die Produktionsinitialisierung erfordert ein eindeutiges Superadmin-Passwort über OM_INIT_SUPERADMIN_PASSWORD oder --password; integrierte Platzhalter sind nicht zulässig."
|
|
6
|
+
"cli.init.errors.superadminPasswordRequired": "Die Produktionsinitialisierung erfordert ein eindeutiges Superadmin-Passwort über OM_INIT_SUPERADMIN_PASSWORD oder --password; integrierte Platzhalter sind nicht zulässig.",
|
|
7
|
+
"cli.init.messages.interruptedAttemptCleared": "♻️ Ein unterbrochener Initialisierungsversuch ohne angelegte Benutzer wurde entfernt."
|
|
4
8
|
}
|
package/dist/i18n/en.json
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
{
|
|
2
|
+
"cli.init.errors.concurrentInitialization": "Another initialization already started for this database. Check its result before retrying.",
|
|
3
|
+
"cli.init.errors.incompleteInitialization": "Initialization has started but has not completed for {database}. Check the prior initialization logs. Use --reinstall only if you intend to erase the database and start over.",
|
|
4
|
+
"cli.init.errors.initializationStateMissing": "Could not record completion for this initialization attempt. Check the database and initialization logs before retrying.",
|
|
2
5
|
"cli.init.errors.superadminPasswordPolicy": "Production superadmin password does not meet the configured password policy. Password-policy bypass flags apply only outside production.",
|
|
3
|
-
"cli.init.errors.superadminPasswordRequired": "Production initialization requires a unique superadmin password via OM_INIT_SUPERADMIN_PASSWORD or --password; built-in placeholders are not allowed."
|
|
6
|
+
"cli.init.errors.superadminPasswordRequired": "Production initialization requires a unique superadmin password via OM_INIT_SUPERADMIN_PASSWORD or --password; built-in placeholders are not allowed.",
|
|
7
|
+
"cli.init.messages.interruptedAttemptCleared": "♻️ Cleared an interrupted initialization attempt that had not created any users."
|
|
4
8
|
}
|
package/dist/i18n/es.json
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
{
|
|
2
|
+
"cli.init.errors.concurrentInitialization": "Ya se inició otra inicialización para esta base de datos. Compruebe su resultado antes de volver a intentarlo.",
|
|
3
|
+
"cli.init.errors.incompleteInitialization": "La inicialización de {database} se inició pero sigue incompleta. Consulte los registros de la inicialización anterior. Use --reinstall solo si desea borrar la base de datos y empezar de nuevo.",
|
|
4
|
+
"cli.init.errors.initializationStateMissing": "No se pudo registrar la finalización de este intento de inicialización. Compruebe la base de datos y los registros de inicialización antes de volver a intentarlo.",
|
|
2
5
|
"cli.init.errors.superadminPasswordPolicy": "La contraseña de superadministrador en producción no cumple la política de contraseñas configurada. Las opciones para omitir la política solo se aplican fuera de producción.",
|
|
3
|
-
"cli.init.errors.superadminPasswordRequired": "La inicialización en producción requiere una contraseña única de superadministrador mediante OM_INIT_SUPERADMIN_PASSWORD o --password; no se permiten los valores predeterminados de ejemplo."
|
|
6
|
+
"cli.init.errors.superadminPasswordRequired": "La inicialización en producción requiere una contraseña única de superadministrador mediante OM_INIT_SUPERADMIN_PASSWORD o --password; no se permiten los valores predeterminados de ejemplo.",
|
|
7
|
+
"cli.init.messages.interruptedAttemptCleared": "♻️ Se eliminó un intento de inicialización interrumpido que no había creado ningún usuario."
|
|
4
8
|
}
|
package/dist/i18n/ko.json
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
{
|
|
2
|
+
"cli.init.errors.concurrentInitialization": "이 데이터베이스의 다른 초기화가 이미 시작되었습니다. 다시 시도하기 전에 그 결과를 확인하세요.",
|
|
3
|
+
"cli.init.errors.incompleteInitialization": "{database}의 초기화가 시작되었지만 완료되지 않았습니다. 이전 초기화 로그를 확인하세요. 데이터베이스를 지우고 처음부터 시작하려는 경우에만 --reinstall을 사용하세요.",
|
|
4
|
+
"cli.init.errors.initializationStateMissing": "이번 초기화 시도의 완료 상태를 기록하지 못했습니다. 다시 시도하기 전에 데이터베이스와 초기화 로그를 확인하세요.",
|
|
2
5
|
"cli.init.errors.superadminPasswordPolicy": "프로덕션 슈퍼관리자 비밀번호가 설정된 비밀번호 정책을 충족하지 않습니다. 비밀번호 정책 우회 플래그는 프로덕션 외 환경에서만 적용됩니다.",
|
|
3
|
-
"cli.init.errors.superadminPasswordRequired": "프로덕션 초기화에는 OM_INIT_SUPERADMIN_PASSWORD 또는 --password로 지정한 고유한 슈퍼관리자 비밀번호가 필요합니다. 기본 예시 비밀번호는 사용할 수 없습니다."
|
|
6
|
+
"cli.init.errors.superadminPasswordRequired": "프로덕션 초기화에는 OM_INIT_SUPERADMIN_PASSWORD 또는 --password로 지정한 고유한 슈퍼관리자 비밀번호가 필요합니다. 기본 예시 비밀번호는 사용할 수 없습니다.",
|
|
7
|
+
"cli.init.messages.interruptedAttemptCleared": "♻️ 사용자를 생성하지 않은 채 중단된 초기화 시도를 정리했습니다."
|
|
4
8
|
}
|
package/dist/i18n/pl.json
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
{
|
|
2
|
+
"cli.init.errors.concurrentInitialization": "Dla tej bazy danych rozpoczęto już inną inicjalizację. Sprawdź jej wynik przed ponowną próbą.",
|
|
3
|
+
"cli.init.errors.incompleteInitialization": "Inicjalizacja bazy {database} została rozpoczęta, ale nie została ukończona. Sprawdź dzienniki poprzedniej inicjalizacji. Użyj --reinstall tylko wtedy, gdy chcesz usunąć bazę danych i zacząć od nowa.",
|
|
4
|
+
"cli.init.errors.initializationStateMissing": "Nie udało się zapisać zakończenia tej próby inicjalizacji. Przed ponowną próbą sprawdź bazę danych i dzienniki inicjalizacji.",
|
|
2
5
|
"cli.init.errors.superadminPasswordPolicy": "Hasło superadministratora w środowisku produkcyjnym nie spełnia skonfigurowanej polityki haseł. Flagi pomijające politykę haseł działają tylko poza środowiskiem produkcyjnym.",
|
|
3
|
-
"cli.init.errors.superadminPasswordRequired": "Inicjalizacja produkcyjna wymaga unikalnego hasła superadministratora podanego przez OM_INIT_SUPERADMIN_PASSWORD lub --password; wbudowane hasła przykładowe są niedozwolone."
|
|
6
|
+
"cli.init.errors.superadminPasswordRequired": "Inicjalizacja produkcyjna wymaga unikalnego hasła superadministratora podanego przez OM_INIT_SUPERADMIN_PASSWORD lub --password; wbudowane hasła przykładowe są niedozwolone.",
|
|
7
|
+
"cli.init.messages.interruptedAttemptCleared": "♻️ Usunięto przerwaną próbę inicjalizacji, która nie utworzyła żadnych użytkowników."
|
|
4
8
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { parseBooleanToken } from "@open-mercato/shared/lib/boolean";
|
|
1
2
|
const BOOTSTRAP_FREE_COMMANDS = /* @__PURE__ */ new Set([
|
|
2
3
|
"generate",
|
|
3
4
|
"module",
|
|
@@ -21,12 +22,20 @@ const BOOTSTRAP_FREE_COMMANDS = /* @__PURE__ */ new Set([
|
|
|
21
22
|
"-h"
|
|
22
23
|
]);
|
|
23
24
|
function resolveCliBootstrapMode(argv) {
|
|
24
|
-
const [, , first, second] = argv;
|
|
25
|
+
const [, , first, second, ...args] = argv;
|
|
26
|
+
if (first === "db" && second === "migrate" && !args.some((arg) => arg === "--help" || arg === "-h")) {
|
|
27
|
+
return "database-migrate";
|
|
28
|
+
}
|
|
25
29
|
if (!first || BOOTSTRAP_FREE_COMMANDS.has(first)) return "none";
|
|
26
30
|
if (first === "server" && second === "dev") return "dev-supervisor";
|
|
27
31
|
return "full";
|
|
28
32
|
}
|
|
33
|
+
function requiresDatabaseRuntimeForMigration(env = process.env) {
|
|
34
|
+
const configured = env.OM_TENANT_RLS?.trim();
|
|
35
|
+
return Boolean(configured) && parseBooleanToken(configured) !== false;
|
|
36
|
+
}
|
|
29
37
|
export {
|
|
38
|
+
requiresDatabaseRuntimeForMigration,
|
|
30
39
|
resolveCliBootstrapMode
|
|
31
40
|
};
|
|
32
41
|
//# sourceMappingURL=cli-bootstrap-mode.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/cli-bootstrap-mode.ts"],
|
|
4
|
-
"sourcesContent": ["
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\n\nexport type CliBootstrapMode = 'none' | 'dev-supervisor' | 'full' | 'database-migrate'\n\nconst BOOTSTRAP_FREE_COMMANDS = new Set([\n 'generate',\n 'module',\n 'deploy',\n 'db',\n 'init',\n 'agentic:init',\n 'telemetry',\n 'eject',\n 'test',\n 'test:integration',\n 'test:integration:coverage',\n 'test:integration:spec-coverage',\n 'test:ephemeral',\n 'test:integration:interactive',\n 'umes:list',\n 'umes:inspect',\n 'umes:check',\n 'help',\n '--help',\n '-h',\n])\n\nexport function resolveCliBootstrapMode(argv: readonly string[]): CliBootstrapMode {\n const [, , first, second, ...args] = argv\n if (first === 'db' && second === 'migrate' && !args.some((arg) => arg === '--help' || arg === '-h')) {\n return 'database-migrate'\n }\n if (!first || BOOTSTRAP_FREE_COMMANDS.has(first)) return 'none'\n if (first === 'server' && second === 'dev') return 'dev-supervisor'\n return 'full'\n}\n\nexport function requiresDatabaseRuntimeForMigration(env: NodeJS.ProcessEnv = process.env): boolean {\n const configured = env.OM_TENANT_RLS?.trim()\n return Boolean(configured) && parseBooleanToken(configured) !== false\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,yBAAyB;AAIlC,MAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,SAAS,wBAAwB,MAA2C;AACjF,QAAM,CAAC,EAAE,EAAE,OAAO,QAAQ,GAAG,IAAI,IAAI;AACrC,MAAI,UAAU,QAAQ,WAAW,aAAa,CAAC,KAAK,KAAK,CAAC,QAAQ,QAAQ,YAAY,QAAQ,IAAI,GAAG;AACnG,WAAO;AAAA,EACT;AACA,MAAI,CAAC,SAAS,wBAAwB,IAAI,KAAK,EAAG,QAAO;AACzD,MAAI,UAAU,YAAY,WAAW,MAAO,QAAO;AACnD,SAAO;AACT;AAEO,SAAS,oCAAoC,MAAyB,QAAQ,KAAc;AACjG,QAAM,aAAa,IAAI,eAAe,KAAK;AAC3C,SAAO,QAAQ,UAAU,KAAK,kBAAkB,UAAU,MAAM;AAClE;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/lib/db/commands.js
CHANGED
|
@@ -6,6 +6,7 @@ import { MikroORM, MetadataStorage } from "@mikro-orm/core";
|
|
|
6
6
|
import { ReflectMetadataProvider } from "@mikro-orm/decorators/legacy";
|
|
7
7
|
import { PostgreSqlDriver } from "@mikro-orm/postgresql";
|
|
8
8
|
import { getSslConfig } from "@open-mercato/shared/lib/db/ssl";
|
|
9
|
+
import { afterDatabaseMigrate, beforeDatabaseMigrate, resolveDatabaseConnectionUrl, runWithDatabaseExecutionContext, shouldRecoverDatabaseMigrationReindex } from "@open-mercato/shared/lib/db/runtime";
|
|
9
10
|
import { quotePostgresIdentifier } from "./identifiers.js";
|
|
10
11
|
import { preserveUnconstrainedNumericSnapshots } from "./numeric-snapshots.js";
|
|
11
12
|
import {
|
|
@@ -337,10 +338,16 @@ async function dbGenerate(resolver, options = {}) {
|
|
|
337
338
|
await warnAboutMissingEncryptionMapBackfills(ordered, resolver);
|
|
338
339
|
}
|
|
339
340
|
async function dbMigrate(resolver, options = {}) {
|
|
341
|
+
return runWithDatabaseExecutionContext({ kind: "maintenance", tenantId: null, source: "cli", operation: "db:migrate" }, () => migrateModules(resolver, options));
|
|
342
|
+
}
|
|
343
|
+
async function migrateModules(resolver, _options) {
|
|
340
344
|
const modules = resolver.loadEnabledModules();
|
|
341
345
|
const ordered = sortModules(modules);
|
|
342
346
|
const results = [];
|
|
343
347
|
const appliedMigrations = [];
|
|
348
|
+
const recoverHistory = shouldRecoverDatabaseMigrationReindex();
|
|
349
|
+
let reconciled = false;
|
|
350
|
+
await beforeDatabaseMigrate();
|
|
344
351
|
try {
|
|
345
352
|
for (const entry of ordered) {
|
|
346
353
|
const modId = entry.id;
|
|
@@ -354,7 +361,7 @@ async function dbMigrate(resolver, options = {}) {
|
|
|
354
361
|
const sslConfig = getSslConfig();
|
|
355
362
|
const orm = await MikroORM.init({
|
|
356
363
|
driver: PostgreSqlDriver,
|
|
357
|
-
clientUrl: getClientUrl(),
|
|
364
|
+
clientUrl: resolveDatabaseConnectionUrl("maintenance", getClientUrl()),
|
|
358
365
|
loggerFactory: () => createMinimalLogger(),
|
|
359
366
|
dynamicImportProvider,
|
|
360
367
|
entities: [],
|
|
@@ -382,6 +389,12 @@ async function dbMigrate(resolver, options = {}) {
|
|
|
382
389
|
});
|
|
383
390
|
try {
|
|
384
391
|
const migrator = orm.migrator;
|
|
392
|
+
if (recoverHistory) {
|
|
393
|
+
const executed = await migrator.getExecuted();
|
|
394
|
+
for (const migration of executed) {
|
|
395
|
+
appliedMigrations.push({ moduleId: modId, migrationsPath, name: migration.name });
|
|
396
|
+
}
|
|
397
|
+
}
|
|
385
398
|
const pending = await migrator.getPending();
|
|
386
399
|
if (!pending.length) {
|
|
387
400
|
results.push(formatResult(modId, "no pending migrations", ""));
|
|
@@ -392,7 +405,7 @@ async function dbMigrate(resolver, options = {}) {
|
|
|
392
405
|
process.stdout.write(` ${PROGRESS_EMOJI} ${modId}: ${renderProgress(applied)}`);
|
|
393
406
|
}
|
|
394
407
|
for (const migration of pending) {
|
|
395
|
-
const migrationName = typeof migration === "string" ? migration : migration.name
|
|
408
|
+
const migrationName = typeof migration === "string" ? migration : migration.name;
|
|
396
409
|
await migrator.up(migrationName ? { migrations: [migrationName] } : void 0);
|
|
397
410
|
if (migrationName) {
|
|
398
411
|
appliedMigrations.push({
|
|
@@ -416,9 +429,11 @@ async function dbMigrate(resolver, options = {}) {
|
|
|
416
429
|
await orm.close(true);
|
|
417
430
|
}
|
|
418
431
|
}
|
|
432
|
+
await afterDatabaseMigrate();
|
|
433
|
+
reconciled = true;
|
|
419
434
|
} finally {
|
|
420
435
|
console.log(results.join("\n"));
|
|
421
|
-
await dischargeQueryIndexReindexRequests(appliedMigrations);
|
|
436
|
+
if (!recoverHistory || reconciled) await dischargeQueryIndexReindexRequests(appliedMigrations);
|
|
422
437
|
}
|
|
423
438
|
}
|
|
424
439
|
async function dischargeQueryIndexReindexRequests(applied) {
|
|
@@ -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 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 const modules = resolver.loadEnabledModules()\n const ordered = sortModules(modules)\n const results: string[] = []\n const appliedMigrations: AppliedMigration[] = []\n\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: 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 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'\n ? migration\n : (migration as any).name ?? (migration as any).fileName\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 as any).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 } finally {\n console.log(results.join('\\n'))\n 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;AAE7B,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;AAEA,SAAS,uBAAuB,OAAe;AAC7C,QAAM,QAAQ;AACd,QAAM,kBAAkB,QAAQ,IAAI,QAAQ;AAC5C,SAAO,CAAC,YAAoB;AAC1B,UAAM,UAAU,KAAK,IAAI,KAAK,IAAI,SAAS,CAAC,GAAG,eAAe;AAC9D,UAAM,SAAS,KAAK,MAAO,UAAU,kBAAmB,KAAK;AAC7D,UAAM,MAAM,GAAG,IAAI,OAAO,MAAM,CAAC,GAAG,IAAI,OAAO,KAAK,IAAI,QAAQ,QAAQ,CAAC,CAAC,CAAC;AAC3E,WAAO,IAAI,GAAG,KAAK,OAAO,IAAI,eAAe;AAAA,EAC/C;AACF;AAEA,SAAS,sBAA8B;AACrC,SAAO;AAAA,IACL,KAAK,MAAM;AAAA,IAAE;AAAA,IACb,OAAO,CAAC,YAAY,YAAY,QAAQ,MAAM,OAAO;AA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CAAC,CAAC,UAAU;AAAA,UACjF;AACA,gBAAM,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;",
|
|
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;AA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