@open-mercato/cli 0.10.1-develop.8289.1.9a25111d49 → 0.10.1-develop.8291.1.6ec3aee41c

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/.turbo/turbo-build.log +2 -2
  2. package/dist/agentic/guides/module-facts.json +287 -240
  3. package/dist/agentic/guides/module-facts.v2.json +287 -240
  4. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  5. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  6. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  7. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  8. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  9. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  10. package/dist/agentic/guides/modules/auth/index.md +1 -1
  11. package/dist/agentic/guides/modules/availability/index.md +1 -1
  12. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  13. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  14. package/dist/agentic/guides/modules/cart/index.md +1 -1
  15. package/dist/agentic/guides/modules/catalog/index.md +1 -1
  16. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  17. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  18. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  19. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  20. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  21. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  22. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  23. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  24. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  25. package/dist/agentic/guides/modules/checkout/exact-override-targets.md +1 -1
  26. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  27. package/dist/agentic/guides/modules/checkout/workers.md +1 -1
  28. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  29. package/dist/agentic/guides/modules/configs/index.md +1 -1
  30. package/dist/agentic/guides/modules/content/index.md +1 -1
  31. package/dist/agentic/guides/modules/currencies/di-registrations-rich.md +11 -0
  32. package/dist/agentic/guides/modules/currencies/di-service-tokens.md +11 -0
  33. package/dist/agentic/guides/modules/currencies/exact-override-targets.md +1 -0
  34. package/dist/agentic/guides/modules/currencies/index.md +4 -2
  35. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  36. package/dist/agentic/guides/modules/customer_groups/active-extension-bindings.md +1 -1
  37. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  38. package/dist/agentic/guides/modules/customers/active-extension-bindings.md +2 -2
  39. package/dist/agentic/guides/modules/customers/index.md +1 -1
  40. package/dist/agentic/guides/modules/dashboards/index.md +1 -1
  41. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  42. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  43. package/dist/agentic/guides/modules/devices/index.md +1 -1
  44. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  45. package/dist/agentic/guides/modules/directory/index.md +1 -1
  46. package/dist/agentic/guides/modules/documents/index.md +1 -1
  47. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  48. package/dist/agentic/guides/modules/entities/index.md +1 -1
  49. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  50. package/dist/agentic/guides/modules/events/index.md +1 -1
  51. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  52. package/dist/agentic/guides/modules/forms/index.md +1 -1
  53. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  54. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  55. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  56. package/dist/agentic/guides/modules/generators/index.md +1 -1
  57. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  58. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  59. package/dist/agentic/guides/modules/messages/index.md +1 -1
  60. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  61. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  62. package/dist/agentic/guides/modules/payment_gateways/active-extension-bindings.md +1 -1
  63. package/dist/agentic/guides/modules/payment_gateways/di-registrations-rich.md +4 -4
  64. package/dist/agentic/guides/modules/payment_gateways/di-service-tokens.md +2 -2
  65. package/dist/agentic/guides/modules/payment_gateways/exact-override-targets.md +4 -4
  66. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  67. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  68. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  69. package/dist/agentic/guides/modules/planner/index.md +1 -1
  70. package/dist/agentic/guides/modules/portal/index.md +1 -1
  71. package/dist/agentic/guides/modules/progress/index.md +1 -1
  72. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  73. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  74. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  75. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  76. package/dist/agentic/guides/modules/resources/index.md +1 -1
  77. package/dist/agentic/guides/modules/sales/active-extension-bindings.md +1 -1
  78. package/dist/agentic/guides/modules/sales/di-registrations-rich.md +30 -30
  79. package/dist/agentic/guides/modules/sales/di-service-tokens.md +5 -5
  80. package/dist/agentic/guides/modules/sales/exact-override-targets.md +30 -30
  81. package/dist/agentic/guides/modules/sales/index.md +1 -1
  82. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  83. package/dist/agentic/guides/modules/search/index.md +1 -1
  84. package/dist/agentic/guides/modules/security/index.md +1 -1
  85. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  86. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  87. package/dist/agentic/guides/modules/sso/index.md +1 -1
  88. package/dist/agentic/guides/modules/staff/active-extension-bindings.md +2 -2
  89. package/dist/agentic/guides/modules/staff/index.md +1 -1
  90. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  91. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  92. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  93. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  94. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  95. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  96. package/dist/agentic/guides/modules/translations/index.md +1 -1
  97. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  98. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  99. package/dist/agentic/guides/modules/wms/index.md +1 -1
  100. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  101. package/dist/agentic/guides/reference-module-facts.json +1 -1
  102. package/dist/agentic/guides/upstream/BACKWARD_COMPATIBILITY.md +23 -0
  103. package/dist/agentic/guides/upstream/manifest.json +2 -2
  104. package/dist/agentic/shared/ai/harness/cases.json +5 -5
  105. package/dist/lib/db/commands.js +2 -0
  106. package/dist/lib/db/commands.js.map +2 -2
  107. package/dist/lib/db/numeric-snapshots.js +13 -0
  108. package/dist/lib/db/numeric-snapshots.js.map +7 -0
  109. package/package.json +7 -7
  110. package/src/lib/db/__tests__/numeric-snapshots.test.ts +79 -0
  111. package/src/lib/db/commands.ts +2 -0
  112. package/src/lib/db/numeric-snapshots.ts +12 -0
@@ -520,7 +520,7 @@
520
520
  ],
521
521
  "maxContextFiles": 8,
522
522
  "maxInitialContextBytes": 65536,
523
- "maxTotalContextBytes": 126976,
523
+ "maxTotalContextBytes": 132096,
524
524
  "relatedCases": [
525
525
  "OMH-008"
526
526
  ]
@@ -1736,7 +1736,7 @@
1736
1736
  ],
1737
1737
  "maxContextFiles": 6,
1738
1738
  "maxInitialContextBytes": 65536,
1739
- "maxTotalContextBytes": 110592,
1739
+ "maxTotalContextBytes": 119808,
1740
1740
  "relatedCases": [
1741
1741
  "OMH-023"
1742
1742
  ]
@@ -2431,7 +2431,7 @@
2431
2431
  ],
2432
2432
  "maxContextFiles": 6,
2433
2433
  "maxInitialContextBytes": 49152,
2434
- "maxTotalContextBytes": 126976,
2434
+ "maxTotalContextBytes": 135168,
2435
2435
  "relatedCases": [
2436
2436
  "OMH-031"
2437
2437
  ]
@@ -4556,7 +4556,7 @@
4556
4556
  ],
4557
4557
  "maxContextFiles": 5,
4558
4558
  "maxInitialContextBytes": 40960,
4559
- "maxTotalContextBytes": 118784,
4559
+ "maxTotalContextBytes": 124928,
4560
4560
  "relatedCases": [
4561
4561
  "OMH-058"
4562
4562
  ],
@@ -5147,7 +5147,7 @@
5147
5147
  ],
5148
5148
  "maxContextFiles": 8,
5149
5149
  "maxInitialContextBytes": 65536,
5150
- "maxTotalContextBytes": 126976,
5150
+ "maxTotalContextBytes": 132096,
5151
5151
  "relatedCases": [
5152
5152
  "OMH-065"
5153
5153
  ]
@@ -7,6 +7,7 @@ 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
9
  import { quotePostgresIdentifier } from "./identifiers.js";
10
+ import { preserveUnconstrainedNumericSnapshots } from "./numeric-snapshots.js";
10
11
  import {
11
12
  checkEncryptionMapBackfills,
12
13
  isEncryptionBackfillCheckEnabled,
@@ -295,6 +296,7 @@ async function dbGenerate(resolver, options = {}) {
295
296
  } : void 0
296
297
  });
297
298
  try {
299
+ preserveUnconstrainedNumericSnapshots(orm.em.getDriver().getPlatform());
298
300
  const diff = await orm.migrator.create(void 0, false, createInitialMigration);
299
301
  if (diff && diff.fileName) {
300
302
  try {
@@ -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 {\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 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;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,S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C/D,MAAI;AACF,UAAM,EAAE,OAAO,IAAI,MAAM,OAAO,IAAI;AACpC,UAAM,SAAS,IAAI,OAAO,EAAE,kBAAkB,aAAa,GAAG,KAAK,aAAa,EAAE,CAAC;AACnF,UAAM,OAAO,QAAQ;AACrB,QAAI;AACF,YAAM,MAAM,MAAM,OAAO,MAAM,qEAAqE;AACpG,YAAM,UAAoB,IAAI,QAAQ,CAAC,GAAG,IAAI,CAAC,MAAW,OAAO,EAAE,SAAS,CAAC;AAC7E,UAAI,OAAO,QAAQ;AACjB,cAAM,OAAO,MAAM,OAAO;AAC1B,YAAI;AACF,gBAAM,OAAO,MAAM,0CAA0C;AAC7D,qBAAW,KAAK,QAAQ;AACtB,kBAAM,OAAO,MAAM,wBAAwB,wBAAwB,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 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,kB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;AAExB,UAAQ,IAAI,oEAAoE;AAClF;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,13 @@
1
+ function preserveUnconstrainedNumericSnapshots(platform) {
2
+ const normalizeColumnType = platform.normalizeColumnType.bind(platform);
3
+ platform.normalizeColumnType = (type, options) => {
4
+ if (/^(numeric|decimal)$/i.test(type) && options.precision == null && options.scale == null) {
5
+ return "numeric";
6
+ }
7
+ return normalizeColumnType(type, options);
8
+ };
9
+ }
10
+ export {
11
+ preserveUnconstrainedNumericSnapshots
12
+ };
13
+ //# sourceMappingURL=numeric-snapshots.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/lib/db/numeric-snapshots.ts"],
4
+ "sourcesContent": ["import type { Platform } from '@mikro-orm/core'\n\nexport function preserveUnconstrainedNumericSnapshots(platform: Pick<Platform, 'normalizeColumnType'>): void {\n const normalizeColumnType = platform.normalizeColumnType.bind(platform)\n\n platform.normalizeColumnType = (type, options) => {\n if (/^(numeric|decimal)$/i.test(type) && options.precision == null && options.scale == null) {\n return 'numeric'\n }\n return normalizeColumnType(type, options)\n }\n}\n"],
5
+ "mappings": "AAEO,SAAS,sCAAsC,UAAuD;AAC3G,QAAM,sBAAsB,SAAS,oBAAoB,KAAK,QAAQ;AAEtE,WAAS,sBAAsB,CAAC,MAAM,YAAY;AAChD,QAAI,uBAAuB,KAAK,IAAI,KAAK,QAAQ,aAAa,QAAQ,QAAQ,SAAS,MAAM;AAC3F,aAAO;AAAA,IACT;AACA,WAAO,oBAAoB,MAAM,OAAO;AAAA,EAC1C;AACF;",
6
+ "names": []
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/cli",
3
- "version": "0.10.1-develop.8289.1.9a25111d49",
3
+ "version": "0.10.1-develop.8291.1.6ec3aee41c",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -60,10 +60,10 @@
60
60
  "@mikro-orm/decorators": "^7.1.14",
61
61
  "@mikro-orm/migrations": "^7.1.14",
62
62
  "@mikro-orm/postgresql": "^7.1.14",
63
- "@open-mercato/events": "0.10.1-develop.8289.1.9a25111d49",
64
- "@open-mercato/queue": "0.10.1-develop.8289.1.9a25111d49",
65
- "@open-mercato/shared": "0.10.1-develop.8289.1.9a25111d49",
66
- "@open-mercato/telemetry": "0.10.1-develop.8289.1.9a25111d49",
63
+ "@open-mercato/events": "0.10.1-develop.8291.1.6ec3aee41c",
64
+ "@open-mercato/queue": "0.10.1-develop.8291.1.6ec3aee41c",
65
+ "@open-mercato/shared": "0.10.1-develop.8291.1.6ec3aee41c",
66
+ "@open-mercato/telemetry": "0.10.1-develop.8291.1.6ec3aee41c",
67
67
  "cross-spawn": "^7.0.6",
68
68
  "minisearch": "7.2.0",
69
69
  "pg": "8.23.0",
@@ -75,10 +75,10 @@
75
75
  "typescript-js": "npm:typescript@6.0.3"
76
76
  },
77
77
  "peerDependencies": {
78
- "@open-mercato/shared": "0.10.1-develop.8289.1.9a25111d49"
78
+ "@open-mercato/shared": "0.10.1-develop.8291.1.6ec3aee41c"
79
79
  },
80
80
  "devDependencies": {
81
- "@open-mercato/shared": "0.10.1-develop.8289.1.9a25111d49",
81
+ "@open-mercato/shared": "0.10.1-develop.8291.1.6ec3aee41c",
82
82
  "@types/jest": "^30.0.0",
83
83
  "jest": "^30.4.2",
84
84
  "ts-jest": "^29.4.12"
@@ -0,0 +1,79 @@
1
+ import fs from 'node:fs'
2
+ import os from 'node:os'
3
+ import path from 'node:path'
4
+ import { EntitySchema } from '@mikro-orm/core'
5
+ import { Migrator } from '@mikro-orm/migrations'
6
+ import { MikroORM } from '@mikro-orm/postgresql'
7
+ import { ExactDecimalType } from '@open-mercato/shared/lib/db/exactDecimalType'
8
+ import { preserveUnconstrainedNumericSnapshots } from '../numeric-snapshots'
9
+
10
+ class SnapshotProbeMigrator extends Migrator {
11
+ writeSnapshot() {
12
+ return this.storeCurrentSchema()
13
+ }
14
+ }
15
+
16
+ describe('unconstrained numeric migration snapshots', () => {
17
+ let orm: MikroORM
18
+ let migrationsPath: string
19
+
20
+ beforeAll(async () => {
21
+ migrationsPath = fs.mkdtempSync(path.join(os.tmpdir(), 'numeric-snapshots-'))
22
+ orm = await MikroORM.init({
23
+ entities: [new EntitySchema({
24
+ name: 'NumericSnapshotProbe',
25
+ tableName: 'numeric_snapshot_probes',
26
+ properties: {
27
+ id: { type: 'uuid', primary: true },
28
+ amount: { type: ExactDecimalType, columnType: 'numeric' },
29
+ rate: { type: ExactDecimalType },
30
+ percentage: { type: 'decimal', precision: 7, scale: 4 },
31
+ },
32
+ })],
33
+ dbName: 'numeric_snapshot_probe',
34
+ connect: false,
35
+ extensions: [Migrator],
36
+ migrations: {
37
+ path: migrationsPath,
38
+ pathTs: migrationsPath,
39
+ snapshotName: '.snapshot-probe',
40
+ },
41
+ })
42
+ preserveUnconstrainedNumericSnapshots(orm.em.getDriver().getPlatform())
43
+ })
44
+
45
+ afterAll(async () => {
46
+ await orm?.close(true)
47
+ if (migrationsPath) fs.rmSync(migrationsPath, { recursive: true, force: true })
48
+ })
49
+
50
+ it('preserves bare numeric aliases and delegates bounded and other types', () => {
51
+ const platform = orm.em.getDriver().getPlatform()
52
+
53
+ expect(platform.normalizeColumnType('numeric', {})).toBe('numeric')
54
+ expect(platform.normalizeColumnType('decimal', {})).toBe('numeric')
55
+ expect(platform.normalizeColumnType('numeric', { precision: 7, scale: 4 })).toBe('numeric(7,4)')
56
+ expect(platform.normalizeColumnType('numeric(7,4)', { precision: 7, scale: 4 })).toBe('numeric(7,4)')
57
+ expect(platform.normalizeColumnType('numeric', { precision: 7 })).toBe('numeric(7,0)')
58
+ expect(platform.normalizeColumnType('numeric', { scale: 4 })).toBe('numeric(10,4)')
59
+ expect(platform.normalizeColumnType('integer', {})).toBe('int')
60
+ expect(platform.normalizeColumnType('varchar', { length: 50 })).toBe('varchar(50)')
61
+ })
62
+
63
+ it('writes actual numeric snapshot columns and produces no migration on repeated generation', async () => {
64
+ const migrator = new SnapshotProbeMigrator(orm.em)
65
+ await migrator.writeSnapshot()
66
+
67
+ const snapshot: {
68
+ tables: { columns: Record<string, { type: string; precision: number | null; scale: number | null }> }[]
69
+ } = JSON.parse(fs.readFileSync(path.join(migrationsPath, '.snapshot-probe.json'), 'utf8'))
70
+ const columns = snapshot.tables[0].columns
71
+
72
+ expect(columns.amount).toMatchObject({ type: 'numeric', precision: null, scale: null })
73
+ expect(columns.rate).toMatchObject({ type: 'numeric', precision: null, scale: null })
74
+ expect(columns.percentage).toMatchObject({ type: 'numeric(7,4)', precision: 7, scale: 4 })
75
+ expect(await orm.migrator.create()).toMatchObject({ fileName: '', diff: { up: [], down: [] } })
76
+ expect(await orm.migrator.create()).toMatchObject({ fileName: '', diff: { up: [], down: [] } })
77
+ expect(fs.readdirSync(migrationsPath)).toEqual(['.snapshot-probe.json'])
78
+ })
79
+ })
@@ -9,6 +9,7 @@ import { PostgreSqlDriver } from '@mikro-orm/postgresql'
9
9
  import { getSslConfig } from '@open-mercato/shared/lib/db/ssl'
10
10
  import type { PackageResolver, ModuleEntry } from '../resolver'
11
11
  import { quotePostgresIdentifier } from './identifiers'
12
+ import { preserveUnconstrainedNumericSnapshots } from './numeric-snapshots'
12
13
  import {
13
14
  checkEncryptionMapBackfills,
14
15
  isEncryptionBackfillCheckEnabled,
@@ -400,6 +401,7 @@ export async function dbGenerate(resolver: PackageResolver, options: DbOptions =
400
401
  })
401
402
 
402
403
  try {
404
+ preserveUnconstrainedNumericSnapshots(orm.em.getDriver().getPlatform())
403
405
  const diff = await orm.migrator.create(undefined, false, createInitialMigration)
404
406
  if (diff && diff.fileName) {
405
407
  try {
@@ -0,0 +1,12 @@
1
+ import type { Platform } from '@mikro-orm/core'
2
+
3
+ export function preserveUnconstrainedNumericSnapshots(platform: Pick<Platform, 'normalizeColumnType'>): void {
4
+ const normalizeColumnType = platform.normalizeColumnType.bind(platform)
5
+
6
+ platform.normalizeColumnType = (type, options) => {
7
+ if (/^(numeric|decimal)$/i.test(type) && options.precision == null && options.scale == null) {
8
+ return 'numeric'
9
+ }
10
+ return normalizeColumnType(type, options)
11
+ }
12
+ }