@open-mercato/cli 0.11.1-develop.8920.1.d3c2cc4681 → 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.
Files changed (183) hide show
  1. package/.turbo/turbo-build.log +6 -2
  2. package/dist/agentic/guides/module-facts.json +356 -385
  3. package/dist/agentic/guides/module-facts.v2.json +356 -385
  4. package/dist/agentic/guides/modules/agent_orchestrator/active-extension-bindings.md +1 -1
  5. package/dist/agentic/guides/modules/agent_orchestrator/exact-override-targets.md +1 -1
  6. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  7. package/dist/agentic/guides/modules/agent_orchestrator/workers.md +1 -1
  8. package/dist/agentic/guides/modules/ai_assistant/exact-override-targets.md +2 -2
  9. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  10. package/dist/agentic/guides/modules/ai_assistant/workers.md +2 -2
  11. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  12. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  13. package/dist/agentic/guides/modules/assisted_selling/index.md +1 -1
  14. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  15. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  16. package/dist/agentic/guides/modules/auth/entities.md +1 -0
  17. package/dist/agentic/guides/modules/auth/index.md +2 -2
  18. package/dist/agentic/guides/modules/auth/umes-hosts.md +1 -0
  19. package/dist/agentic/guides/modules/availability/index.md +1 -1
  20. package/dist/agentic/guides/modules/backups/index.md +1 -1
  21. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  22. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  23. package/dist/agentic/guides/modules/cart/index.md +1 -1
  24. package/dist/agentic/guides/modules/catalog/index.md +1 -1
  25. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  26. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  27. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  28. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  29. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  30. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  31. package/dist/agentic/guides/modules/channel_ms365/index.md +1 -1
  32. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  33. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  34. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  35. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  36. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  37. package/dist/agentic/guides/modules/configs/index.md +1 -1
  38. package/dist/agentic/guides/modules/content/index.md +1 -1
  39. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  40. package/dist/agentic/guides/modules/customer_accounts/exact-override-targets.md +4 -4
  41. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  42. package/dist/agentic/guides/modules/customer_accounts/workers.md +4 -4
  43. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  44. package/dist/agentic/guides/modules/customers/index.md +1 -1
  45. package/dist/agentic/guides/modules/dashboards/index.md +1 -1
  46. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  47. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  48. package/dist/agentic/guides/modules/devices/index.md +1 -1
  49. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  50. package/dist/agentic/guides/modules/directory/index.md +1 -1
  51. package/dist/agentic/guides/modules/documents/index.md +1 -1
  52. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  53. package/dist/agentic/guides/modules/entities/index.md +1 -1
  54. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  55. package/dist/agentic/guides/modules/events/index.md +1 -1
  56. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  57. package/dist/agentic/guides/modules/forms/index.md +1 -1
  58. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  59. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  60. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  61. package/dist/agentic/guides/modules/generators/index.md +1 -1
  62. package/dist/agentic/guides/modules/gus_regon/index.md +1 -1
  63. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  64. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  65. package/dist/agentic/guides/modules/ledger/index.md +1 -1
  66. package/dist/agentic/guides/modules/maintenance/index.md +1 -1
  67. package/dist/agentic/guides/modules/messages/index.md +1 -1
  68. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  69. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  70. package/dist/agentic/guides/modules/payment_gateways/exact-override-targets.md +1 -1
  71. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  72. package/dist/agentic/guides/modules/payment_gateways/workers.md +1 -1
  73. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  74. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  75. package/dist/agentic/guides/modules/planner/index.md +1 -1
  76. package/dist/agentic/guides/modules/portal/index.md +1 -1
  77. package/dist/agentic/guides/modules/progress/index.md +1 -1
  78. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  79. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  80. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  81. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  82. package/dist/agentic/guides/modules/resources/index.md +1 -1
  83. package/dist/agentic/guides/modules/sales/exact-override-targets.md +4 -4
  84. package/dist/agentic/guides/modules/sales/index.md +1 -1
  85. package/dist/agentic/guides/modules/sales/setup.md +1 -1
  86. package/dist/agentic/guides/modules/sales_invoices_gl_posting/index.md +1 -1
  87. package/dist/agentic/guides/modules/scheduler/di-registrations-rich.md +3 -3
  88. package/dist/agentic/guides/modules/scheduler/di-service-tokens.md +3 -3
  89. package/dist/agentic/guides/modules/scheduler/exact-override-targets.md +4 -9
  90. package/dist/agentic/guides/modules/scheduler/index.md +3 -4
  91. package/dist/agentic/guides/modules/scheduler/workers.md +1 -1
  92. package/dist/agentic/guides/modules/search/di-registrations-rich.md +4 -4
  93. package/dist/agentic/guides/modules/search/di-service-tokens.md +13 -0
  94. package/dist/agentic/guides/modules/search/exact-override-targets.md +4 -4
  95. package/dist/agentic/guides/modules/search/index.md +3 -2
  96. package/dist/agentic/guides/modules/security/index.md +1 -1
  97. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  98. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  99. package/dist/agentic/guides/modules/sso/index.md +1 -1
  100. package/dist/agentic/guides/modules/staff/index.md +1 -1
  101. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  102. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  103. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  104. package/dist/agentic/guides/modules/sync_shopify/index.md +1 -1
  105. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  106. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  107. package/dist/agentic/guides/modules/tenant_boundaries/generator-plugins.md +11 -0
  108. package/dist/agentic/guides/modules/tenant_boundaries/index.md +13 -0
  109. package/dist/agentic/guides/modules/tenant_boundaries/owned-contract-module-metadata.md +11 -0
  110. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  111. package/dist/agentic/guides/modules/translations/index.md +1 -1
  112. package/dist/agentic/guides/modules/upgrade_actions/index.md +1 -1
  113. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  114. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  115. package/dist/agentic/guides/modules/wms/index.md +1 -1
  116. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  117. package/dist/agentic/guides/reference-module-facts.json +2 -2
  118. package/dist/agentic/guides/reference-modules/example/index.md +1 -1
  119. package/dist/agentic/guides/upstream/manifest.json +1 -1
  120. package/dist/agentic/shared/AGENTS.md.template +3 -3
  121. package/dist/agentic/shared/ai/harness/cases.json +4 -4
  122. package/dist/bin.js +6 -3
  123. package/dist/bin.js.map +2 -2
  124. package/dist/i18n/de.json +5 -1
  125. package/dist/i18n/en.json +5 -1
  126. package/dist/i18n/es.json +5 -1
  127. package/dist/i18n/ko.json +5 -1
  128. package/dist/i18n/pl.json +5 -1
  129. package/dist/lib/cli-bootstrap-mode.js +10 -1
  130. package/dist/lib/cli-bootstrap-mode.js.map +2 -2
  131. package/dist/lib/db/commands.js +18 -3
  132. package/dist/lib/db/commands.js.map +2 -2
  133. package/dist/lib/db/maintenance-client.js +72 -0
  134. package/dist/lib/db/maintenance-client.js.map +7 -0
  135. package/dist/lib/generate-watch-structure.js +2 -1
  136. package/dist/lib/generate-watch-structure.js.map +2 -2
  137. package/dist/lib/generators/database-declarations.js +21 -0
  138. package/dist/lib/generators/database-declarations.js.map +7 -0
  139. package/dist/lib/generators/module-registry.js +19 -3
  140. package/dist/lib/generators/module-registry.js.map +2 -2
  141. package/dist/lib/init-existing-database.js +91 -1
  142. package/dist/lib/init-existing-database.js.map +2 -2
  143. package/dist/lib/init-i18n.js +13 -0
  144. package/dist/lib/init-i18n.js.map +7 -0
  145. package/dist/lib/init-secrets.js +2 -10
  146. package/dist/lib/init-secrets.js.map +2 -2
  147. package/dist/lib/scheduler-supervisor.js +47 -7
  148. package/dist/lib/scheduler-supervisor.js.map +2 -2
  149. package/dist/lib/worker-job-handler.js +36 -26
  150. package/dist/lib/worker-job-handler.js.map +2 -2
  151. package/dist/mercato.js +93 -54
  152. package/dist/mercato.js.map +3 -3
  153. package/package.json +7 -7
  154. package/src/__tests__/mercato.test.ts +166 -9
  155. package/src/bin.ts +10 -4
  156. package/src/i18n/de.json +5 -1
  157. package/src/i18n/en.json +5 -1
  158. package/src/i18n/es.json +5 -1
  159. package/src/i18n/ko.json +5 -1
  160. package/src/i18n/pl.json +5 -1
  161. package/src/lib/__tests__/cli-bootstrap-mode.test.ts +76 -1
  162. package/src/lib/__tests__/generate-watch-structure.test.ts +26 -0
  163. package/src/lib/__tests__/rotation-kms-warning-presentation.test.ts +1 -1
  164. package/src/lib/__tests__/scheduler-supervisor.test.ts +107 -0
  165. package/src/lib/__tests__/worker-job-handler.database.test.ts +76 -0
  166. package/src/lib/cli-bootstrap-mode.ts +12 -2
  167. package/src/lib/db/__tests__/commands.migrate-reindex.test.ts +72 -1
  168. package/src/lib/db/__tests__/maintenance-client.test.ts +70 -0
  169. package/src/lib/db/commands.ts +20 -6
  170. package/src/lib/db/maintenance-client.ts +54 -0
  171. package/src/lib/generate-watch-structure.ts +2 -1
  172. package/src/lib/generators/__tests__/database-declarations.test.ts +69 -0
  173. package/src/lib/generators/__tests__/incremental-registry.test.ts +1 -1
  174. package/src/lib/generators/__tests__/module-subset.test.ts +17 -1
  175. package/src/lib/generators/database-declarations.ts +19 -0
  176. package/src/lib/generators/module-registry.ts +23 -4
  177. package/src/lib/init-existing-database.ts +107 -0
  178. package/src/lib/init-i18n.ts +11 -0
  179. package/src/lib/init-secrets.ts +2 -12
  180. package/src/lib/scheduler-supervisor.ts +40 -7
  181. package/src/lib/worker-job-handler.ts +39 -28
  182. package/src/mercato.ts +92 -53
  183. package/dist/agentic/guides/modules/scheduler/cli-commands.md +0 -15
@@ -1,10 +1,111 @@
1
+ import type { Client } from 'pg'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { createCliMaintenanceClient } from './db/maintenance-client'
4
+ import { createInitTranslator } from './init-i18n'
5
+
6
+ const INITIALIZATION_NAME = 'mercato-init'
7
+
1
8
  export type ExistingDatabaseDecision = 'proceed' | 'skip' | 'abort'
9
+ type InitializationClient = Pick<Client, 'query'>
2
10
 
3
11
  export function decideExistingDatabase(existingUsersCount: number, skipIfInitialized: boolean): ExistingDatabaseDecision {
4
12
  if (!Number.isFinite(existingUsersCount) || existingUsersCount <= 0) return 'proceed'
5
13
  return skipIfInitialized ? 'skip' : 'abort'
6
14
  }
7
15
 
16
+ export async function withInitializationClient<T>(
17
+ databaseUrl: string,
18
+ action: (client: InitializationClient) => Promise<T>,
19
+ ): Promise<T> {
20
+ const client = await createCliMaintenanceClient(databaseUrl)
21
+ try {
22
+ await client.connect()
23
+ return await action(client)
24
+ } finally {
25
+ await client.end()
26
+ }
27
+ }
28
+
29
+ export async function hasIncompleteInitialization(client: InitializationClient): Promise<boolean> {
30
+ const table = await client.query<{ regclass: string | null }>(
31
+ "SELECT to_regclass('app_initializations') AS regclass",
32
+ )
33
+ if (!table.rows[0]?.regclass) return false
34
+
35
+ const result = await client.query<{ pending: boolean }>(
36
+ 'SELECT completed_at IS NULL AS pending FROM app_initializations WHERE name = $1',
37
+ [INITIALIZATION_NAME],
38
+ )
39
+ return result.rows[0]?.pending === true
40
+ }
41
+
42
+ export type InitializationStart = { initializationId: string; clearedInterruptedAttempt: boolean }
43
+
44
+ export async function startInitialization(client: InitializationClient): Promise<InitializationStart> {
45
+ const translate = createInitTranslator(process.env)
46
+ const lock = await client.query<{ locked: boolean }>(
47
+ 'SELECT pg_try_advisory_lock(hashtext($1)) AS locked',
48
+ [INITIALIZATION_NAME],
49
+ )
50
+ if (lock.rows[0]?.locked !== true) {
51
+ throw new Error(translate('cli.init.errors.concurrentInitialization'))
52
+ }
53
+ const cleared = await client.query(
54
+ 'DELETE FROM app_initializations WHERE name = $1 AND completed_at IS NULL AND NOT EXISTS (SELECT 1 FROM users)',
55
+ [INITIALIZATION_NAME],
56
+ )
57
+ const initializationId = randomUUID()
58
+ const result = await client.query(
59
+ 'INSERT INTO app_initializations (id, name) VALUES ($1, $2) ON CONFLICT (name) DO NOTHING',
60
+ [initializationId, INITIALIZATION_NAME],
61
+ )
62
+ if (result.rowCount !== 1) {
63
+ throw new Error(translate('cli.init.errors.concurrentInitialization'))
64
+ }
65
+ return { initializationId, clearedInterruptedAttempt: cleared.rowCount === 1 }
66
+ }
67
+
68
+ export type InitializationSession = {
69
+ clearedInterruptedAttempt: boolean
70
+ cancelWithoutUsers: () => Promise<void>
71
+ complete: () => Promise<void>
72
+ close: () => Promise<void>
73
+ }
74
+
75
+ export async function openInitializationSession(databaseUrl: string): Promise<InitializationSession> {
76
+ const client = await createCliMaintenanceClient(databaseUrl, { pinned: true })
77
+ try {
78
+ await client.connect()
79
+ const { initializationId, clearedInterruptedAttempt } = await startInitialization(client)
80
+ return {
81
+ clearedInterruptedAttempt,
82
+ cancelWithoutUsers: () => cancelInitializationWithoutUsers(client, initializationId),
83
+ complete: () => completeInitialization(client, initializationId),
84
+ close: () => client.end(),
85
+ }
86
+ } catch (error) {
87
+ await client.end()
88
+ throw error
89
+ }
90
+ }
91
+
92
+ export async function cancelInitializationWithoutUsers(client: InitializationClient, initializationId: string): Promise<void> {
93
+ await client.query(
94
+ 'DELETE FROM app_initializations WHERE id = $1 AND completed_at IS NULL AND NOT EXISTS (SELECT 1 FROM users)',
95
+ [initializationId],
96
+ )
97
+ }
98
+
99
+ export async function completeInitialization(client: InitializationClient, initializationId: string): Promise<void> {
100
+ const result = await client.query(
101
+ 'UPDATE app_initializations SET completed_at = now() WHERE id = $1 AND completed_at IS NULL',
102
+ [initializationId],
103
+ )
104
+ if (result.rowCount !== 1) {
105
+ throw new Error(createInitTranslator(process.env)('cli.init.errors.initializationStateMissing'))
106
+ }
107
+ }
108
+
8
109
  export function describeDatabaseTarget(databaseUrl: string): string {
9
110
  try {
10
111
  const url = new URL(databaseUrl)
@@ -22,3 +123,9 @@ export function formatSkipIfInitializedMessage(existingUsersCount: number, datab
22
123
  ' Not the database you expected? Check DATABASE_URL in .env. To wipe it and seed from scratch: yarn mercato init --reinstall',
23
124
  ]
24
125
  }
126
+
127
+ export function formatIncompleteInitializationMessage(databaseUrl: string): string {
128
+ return createInitTranslator(process.env)('cli.init.errors.incompleteInitialization', {
129
+ database: describeDatabaseTarget(databaseUrl),
130
+ })
131
+ }
@@ -0,0 +1,11 @@
1
+ import { createTranslator } from '@open-mercato/shared/lib/i18n/translate'
2
+ import { createRequire } from 'node:module'
3
+
4
+ const requireLocale = createRequire(import.meta.url)
5
+
6
+ export function createInitTranslator(env: NodeJS.ProcessEnv) {
7
+ const locale = (env.LC_ALL || env.LC_MESSAGES || env.LANG || 'en').split(/[_.-]/)[0].toLowerCase()
8
+ const supportedLocale = ['en', 'pl', 'es', 'de', 'ko'].includes(locale) ? locale : 'en'
9
+ const dictionary: Record<string, string> = requireLocale(`../i18n/${supportedLocale}.json`)
10
+ return createTranslator(dictionary)
11
+ }
@@ -1,17 +1,7 @@
1
1
  import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'
2
2
  import { getPasswordPolicy, validatePassword } from '@open-mercato/shared/lib/auth/passwordPolicy'
3
3
  import { randomBytes } from 'node:crypto'
4
- import { createTranslator } from '@open-mercato/shared/lib/i18n/translate'
5
- import { createRequire } from 'node:module'
6
-
7
- const requireLocale = createRequire(import.meta.url)
8
-
9
- function initTranslator(env: NodeJS.ProcessEnv) {
10
- const locale = (env.LC_ALL || env.LC_MESSAGES || env.LANG || 'en').split(/[_.-]/)[0].toLowerCase()
11
- const supportedLocale = ['en', 'pl', 'es', 'de', 'ko'].includes(locale) ? locale : 'en'
12
- const dictionary: Record<string, string> = requireLocale(`../i18n/${supportedLocale}.json`)
13
- return createTranslator(dictionary)
14
- }
4
+ import { createInitTranslator } from './init-i18n'
15
5
 
16
6
  type EnvReader = (key: string) => string | undefined
17
7
 
@@ -97,7 +87,7 @@ export function resolveInitSuperadminCredentials(args: string[], env: NodeJS.Pro
97
87
  ? parseBooleanToken(skipPolicyArg.split('=')[1] ?? 'true') ?? true
98
88
  : true)
99
89
  if (isProduction) {
100
- const t = initTranslator(env)
90
+ const t = createInitTranslator(env)
101
91
  const placeholder = suppliedPassword?.trim().toLowerCase()
102
92
  if (!suppliedPassword || !placeholder || ['secret', 'password', 'changeme', 'change-me', 'change_me', 'replace-me', 'replace_me'].includes(placeholder)) {
103
93
  throw new Error(t('cli.init.errors.superadminPasswordRequired'))
@@ -10,6 +10,8 @@
10
10
  import { spawn as nodeSpawn } from 'node:child_process'
11
11
  import type { ChildProcess, SpawnOptions } from 'node:child_process'
12
12
  import { getSslConfig } from '@open-mercato/shared/lib/db/ssl'
13
+ import { configureDatabasePool, isDatabaseRuntimeEnabled, resolveDatabaseConnectionUrl, runWithFreshDatabaseExecutionContext } from '@open-mercato/shared/lib/db/runtime'
14
+ import type { DatabasePoolLifecycle } from '@open-mercato/shared/lib/db/runtime'
13
15
 
14
16
  export type SchedulerScheduleProbeResult = {
15
17
  enabledSchedules: number
@@ -80,15 +82,39 @@ export async function probeEnabledSchedules(env: NodeJS.ProcessEnv = process.env
80
82
  }
81
83
  }
82
84
 
83
- const { Client } = await import('pg')
84
- const client = new Client({
85
- connectionString: databaseUrl,
86
- ssl: getSslConfig(),
87
- })
85
+ if (isDatabaseRuntimeEnabled()) {
86
+ return runWithFreshDatabaseExecutionContext({
87
+ kind: 'maintenance', tenantId: null, source: 'scheduler', operation: 'scheduler.lazy-probe',
88
+ }, () => probeScheduleConnection(databaseUrl, true))
89
+ }
90
+ return probeScheduleConnection(databaseUrl, false)
91
+ }
88
92
 
93
+ async function probeScheduleConnection(databaseUrl: string, maintenance: boolean): Promise<SchedulerScheduleProbeResult> {
94
+ let clientEnded = false
95
+ let lifecycle: DatabasePoolLifecycle | undefined
96
+ let release: (() => void) | undefined
97
+ let client: InstanceType<typeof import('pg').Client> | undefined
89
98
  try {
99
+ const { Client } = await import('pg')
100
+ client = new Client({
101
+ connectionString: maintenance ? resolveDatabaseConnectionUrl('maintenance', databaseUrl) : databaseUrl,
102
+ ssl: getSslConfig(),
103
+ ...(maintenance ? { connectionTimeoutMillis: 5000, query_timeout: 5000 } : {}),
104
+ })
105
+
90
106
  await client.connect()
91
- const result = await client.query(`
107
+ let connection: Pick<InstanceType<typeof Client>, 'query'> = client
108
+ if (maintenance) {
109
+ const physical = { query: client.query.bind(client), release: () => undefined }
110
+ const pool = { connect: async () => physical, get ended() { return clientEnded } }
111
+ lifecycle = configureDatabasePool(pool, { id: 'scheduler-lazy-probe', purpose: 'maintenance', tables: ['scheduled_jobs'] })
112
+ await lifecycle.ready()
113
+ const guarded = await pool.connect()
114
+ connection = guarded
115
+ release = guarded.release
116
+ }
117
+ const result = await connection.query(`
92
118
  select
93
119
  count(*)::int as enabled_schedules,
94
120
  count(*) filter (where next_run_at <= now())::int as due_schedules
@@ -117,7 +143,14 @@ export async function probeEnabledSchedules(env: NodeJS.ProcessEnv = process.env
117
143
  errorMessage: error instanceof Error ? error.message : String(error),
118
144
  }
119
145
  } finally {
120
- await client.end().catch(() => undefined)
146
+ try { release?.() } finally {
147
+ try {
148
+ if (client) {
149
+ await client.end()
150
+ clientEnded = true
151
+ }
152
+ } finally { lifecycle?.dispose() }
153
+ }
121
154
  }
122
155
  }
123
156
 
@@ -1,3 +1,5 @@
1
+ import { isDatabaseRuntimeEnabled, runWithFreshDatabaseExecutionContext } from '@open-mercato/shared/lib/db/runtime'
2
+ import { resolveDeclaredDatabaseJobContext, validateDeclaredDatabaseBinding } from '@open-mercato/shared/lib/db/declarations'
1
3
  import type { JobContext, JobHandler } from '@open-mercato/queue'
2
4
  import type { ModuleWorker } from '@open-mercato/shared/modules/registry'
3
5
  import {
@@ -8,6 +10,7 @@ import { bindRequestScopeContainer, runInOwnedRequestScope, runWithRequestScopeC
8
10
 
9
11
  export type WorkerJobContainer = {
10
12
  resolve: <T = unknown>(name: string) => T
13
+ dispose?: () => void | Promise<void>
11
14
  /**
12
15
  * #8268 review Major 1 (re-review): optional — the factory's real container,
13
16
  * when it has one, so a worker that needs `.register()` (several command
@@ -41,35 +44,43 @@ export function createPerJobWorkerHandler(
41
44
  workers: ModuleWorker[],
42
45
  createContainer: WorkerJobContainerFactory,
43
46
  ): JobHandler {
44
- return (job, ctx: JobContext) => runInOwnedRequestScope(async (): Promise<void> => {
45
- const container = await createContainer()
46
- bindRequestScopeContainer(container)
47
- try {
48
- for (const worker of workers) {
49
- await withModuleResourceUsage(
50
- {
51
- moduleId: worker.moduleId ?? inferModuleIdFromResourceId(worker.id),
52
- surface: 'worker',
53
- operation: worker.id,
54
- resourceId: worker.id,
55
- },
56
- () => runWithRequestScopeContainer(container, () => worker.handler(job, {
57
- ...ctx,
58
- resolve: container.resolve.bind(container),
59
- // See `WorkerJobContainer.register`'s own doc — present only when the
60
- // factory handed back a real container, never a `{ resolve }`-only one.
61
- container: typeof container.register === 'function' ? container : undefined,
62
- })),
63
- )
64
- }
65
- } finally {
47
+ return async (job, ctx: JobContext) => {
48
+ const execute = () => runInOwnedRequestScope(async () => {
49
+ const container = await createContainer()
50
+ bindRequestScopeContainer(container)
66
51
  try {
67
- const em = container.resolve('em') as ClearableEntityManager | null
68
- em?.clear?.()
69
- } catch {
70
- // Best-effort: clearing the identity map is a memory optimization and
71
- // must never mask a job's own outcome.
52
+ for (const worker of workers) {
53
+ await withModuleResourceUsage(
54
+ {
55
+ moduleId: worker.moduleId ?? inferModuleIdFromResourceId(worker.id),
56
+ surface: 'worker',
57
+ operation: worker.id,
58
+ resourceId: worker.id,
59
+ },
60
+ () => runWithRequestScopeContainer(container, () => worker.handler(job, {
61
+ ...ctx,
62
+ resolve: container.resolve.bind(container),
63
+ container: typeof container.register === 'function' ? container : undefined,
64
+ })),
65
+ )
66
+ }
67
+ } finally {
68
+ try {
69
+ const em = container.resolve('em') as ClearableEntityManager | null
70
+ em?.clear?.()
71
+ } catch {
72
+ // Best-effort: clearing the identity map is a memory optimization and
73
+ // must never mask a job's own outcome.
74
+ }
75
+ await container.dispose?.()
72
76
  }
77
+ })
78
+ if (!isDatabaseRuntimeEnabled()) return execute()
79
+ const context = await resolveDeclaredDatabaseJobContext({ queue: ctx.queueName, workerIds: workers.map((worker) => worker.id), payload: job.payload, metadata: job.metadata })
80
+ if (context.kind === 'tenant') {
81
+ const valid = await runWithFreshDatabaseExecutionContext({ kind: 'identity', tenantId: context.tenantId, source: 'identity', operation: 'worker-tenant-binding' }, () => validateDeclaredDatabaseBinding({ context }, { requireValidator: true }))
82
+ if (!valid) throw new Error('[internal] Worker requires a persisted active tenant')
73
83
  }
74
- })
84
+ return runWithFreshDatabaseExecutionContext(context, execute)
85
+ }
75
86
  }
package/src/mercato.ts CHANGED
@@ -7,11 +7,25 @@ import type { Module, ModuleWorker } from '@open-mercato/shared/modules/registry
7
7
  import { getCliModules, hasCliModules, registerCliModules } from './registry'
8
8
  export { getCliModules, hasCliModules, registerCliModules }
9
9
  import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'
10
+ import { createCliMaintenanceClient } from './lib/db/maintenance-client'
11
+ import { requiresDatabaseRuntimeForMigration } from './lib/cli-bootstrap-mode'
12
+ import { runDatabaseTenantSetup } from '@open-mercato/shared/lib/db/setup'
13
+ import { runWithFreshDatabaseExecutionContext, isDatabaseRuntimeEnabled } from '@open-mercato/shared/lib/db/runtime'
14
+ import { runDatabaseCliCommand } from '@open-mercato/shared/lib/db/cli'
10
15
  import { getSslConfig } from '@open-mercato/shared/lib/db/ssl'
11
16
  import { getRedisUrl, getRedisUrlOrThrow, parseRedisUrl } from '@open-mercato/shared/lib/redis/connection'
12
17
  import { formatInitSummary } from './lib/init-summary'
13
18
  import { resolveInitDerivedSecrets, resolveInitSuperadminCredentials } from './lib/init-secrets'
14
- import { decideExistingDatabase, formatSkipIfInitializedMessage } from './lib/init-existing-database'
19
+ import { createInitTranslator } from './lib/init-i18n'
20
+ import {
21
+ decideExistingDatabase,
22
+ formatIncompleteInitializationMessage,
23
+ formatSkipIfInitializedMessage,
24
+ hasIncompleteInitialization,
25
+ openInitializationSession,
26
+ withInitializationClient,
27
+ type InitializationSession,
28
+ } from './lib/init-existing-database'
15
29
  import { assertEphemeralDatabaseConnection, assertEphemeralDatabaseOwnership, readEphemeralDatabaseGuard } from './lib/testing/ephemeral-database-guard'
16
30
  import {
17
31
  resolveAutoSpawnWorkersMode,
@@ -290,6 +304,7 @@ function formatInitFailureMessage(error: unknown): string {
290
304
  }
291
305
 
292
306
  async function ensureDatabaseExists(dbUrl: string): Promise<boolean> {
307
+ if (isDatabaseRuntimeEnabled()) return true
293
308
  let parsed: URL
294
309
  try {
295
310
  parsed = new URL(dbUrl)
@@ -814,7 +829,7 @@ async function runModuleCommand(
814
829
  }
815
830
  }
816
831
 
817
- await resolved.command.run(args)
832
+ await runDatabaseCliCommand(resolved.command, args, `${moduleName}:${commandName}`)
818
833
  return true
819
834
  }
820
835
 
@@ -1080,6 +1095,7 @@ export async function run(argv = process.argv) {
1080
1095
 
1081
1096
  console.log('šŸš€ Initializing Open Mercato app...\n')
1082
1097
 
1098
+ let initializationSession: InitializationSession | undefined
1083
1099
  try {
1084
1100
  const initArgs = parts.slice(1).filter(Boolean)
1085
1101
  const reinstall = initArgs.includes('--reinstall') || initArgs.includes('-r')
@@ -1158,7 +1174,6 @@ export async function run(argv = process.argv) {
1158
1174
  // Load env variables so DATABASE_URL is available
1159
1175
  await ensureEnvLoaded()
1160
1176
  console.log('ā™»ļø Reinstall mode enabled: dropping all database tables...')
1161
- const { Client } = await import('pg')
1162
1177
  const dbUrl = process.env.DATABASE_URL
1163
1178
  if (!dbUrl) {
1164
1179
  console.error('DATABASE_URL is not set. Aborting reinstall.')
@@ -1166,7 +1181,7 @@ export async function run(argv = process.argv) {
1166
1181
  }
1167
1182
  const dbExists = ephemeralDatabaseGuard ? true : await ensureDatabaseExists(dbUrl)
1168
1183
  if (!dbExists) return 1
1169
- const client = new Client({ connectionString: dbUrl, ssl: getSslConfig() })
1184
+ const client = await createCliMaintenanceClient(dbUrl)
1170
1185
  try {
1171
1186
  await client.connect()
1172
1187
  if (ephemeralDatabaseGuard) {
@@ -1247,37 +1262,37 @@ export async function run(argv = process.argv) {
1247
1262
  return 1
1248
1263
  }
1249
1264
 
1250
- const { Client } = await import('pg')
1251
1265
  const dbExists = ephemeralDatabaseGuard ? true : await ensureDatabaseExists(dbUrl)
1252
1266
  if (!dbExists) return 1
1253
- const client = new Client({ connectionString: dbUrl, ssl: getSslConfig() })
1267
+ const client = await createCliMaintenanceClient(dbUrl)
1254
1268
  try {
1255
1269
  await client.connect()
1256
1270
  const tableCheck = await client.query<{ regclass: string | null }>(
1257
- `SELECT to_regclass('public.users') AS regclass`,
1271
+ `SELECT to_regclass('users') AS regclass`,
1258
1272
  )
1259
- const hasUsersTable = Boolean(tableCheck.rows?.[0]?.regclass)
1260
- if (hasUsersTable) {
1261
- const countResult = await client.query<{ count: string }>(
1262
- 'SELECT COUNT(*)::text AS count FROM users',
1273
+ const countResult = tableCheck.rows[0]?.regclass
1274
+ ? await client.query<{ count: string }>('SELECT COUNT(*)::text AS count FROM users')
1275
+ : null
1276
+ const existingUsersCount = Number.parseInt(countResult?.rows[0]?.count ?? '0', 10)
1277
+ if (existingUsersCount > 0 && await hasIncompleteInitialization(client)) {
1278
+ console.error(formatIncompleteInitializationMessage(dbUrl))
1279
+ return 1
1280
+ }
1281
+ const existingDatabase = decideExistingDatabase(existingUsersCount, skipIfInitialized)
1282
+ if (existingDatabase === 'skip') {
1283
+ for (const line of formatSkipIfInitializedMessage(existingUsersCount, dbUrl)) console.log(line)
1284
+ return 0
1285
+ }
1286
+ if (existingDatabase === 'abort') {
1287
+ console.error(
1288
+ `āŒ Initialization aborted: found ${existingUsersCount} existing user(s) in the database.`,
1263
1289
  )
1264
- const existingUsersCount = Number.parseInt(countResult.rows?.[0]?.count ?? '0', 10)
1265
- const existingDatabase = decideExistingDatabase(existingUsersCount, skipIfInitialized)
1266
- if (existingDatabase === 'skip') {
1267
- for (const line of formatSkipIfInitializedMessage(existingUsersCount, dbUrl)) console.log(line)
1268
- return 0
1269
- }
1270
- if (existingDatabase === 'abort') {
1271
- console.error(
1272
- `āŒ Initialization aborted: found ${existingUsersCount} existing user(s) in the database.`,
1273
- )
1274
- console.error(
1275
- ' To reset and initialize from scratch, run: yarn mercato init --reinstall',
1276
- )
1277
- console.error(' Standalone shortcut: yarn setup --reinstall')
1278
- console.error(' Shortcut script: yarn reinstall')
1279
- return 1
1280
- }
1290
+ console.error(
1291
+ ' To reset and initialize from scratch, run: yarn mercato init --reinstall',
1292
+ )
1293
+ console.error(' Standalone shortcut: yarn setup --reinstall')
1294
+ console.error(' Shortcut script: yarn reinstall')
1295
+ return 1
1281
1296
  }
1282
1297
  } finally {
1283
1298
  try {
@@ -1321,10 +1336,26 @@ export async function run(argv = process.argv) {
1321
1336
  // Step 5: Build all modules for CLI commands
1322
1337
  const allModules = await buildAllModules()
1323
1338
 
1339
+ const dbUrl = process.env.DATABASE_URL
1340
+ if (!dbUrl) throw new Error('[internal] DATABASE_URL is missing after initialization preflight')
1341
+ const session = await openInitializationSession(dbUrl)
1342
+ initializationSession = session
1343
+ if (session.clearedInterruptedAttempt) {
1344
+ console.log(createInitTranslator(process.env)('cli.init.messages.interruptedAttemptCleared'))
1345
+ }
1346
+ const runBeforeUsersExist = async (action: () => Promise<unknown>) => {
1347
+ try {
1348
+ await action()
1349
+ } catch (error) {
1350
+ await session.cancelWithoutUsers()
1351
+ throw error
1352
+ }
1353
+ }
1354
+
1324
1355
  // Step 6: Restore configuration defaults
1325
1356
  if (allModules.some((module) => module.id === 'configs')) {
1326
1357
  console.log('āš™ļø Restoring module defaults...')
1327
- await runModuleCommand(allModules, 'configs', 'restore-defaults', [])
1358
+ await runBeforeUsersExist(() => runModuleCommand(allModules, 'configs', 'restore-defaults', []))
1328
1359
  console.log('āœ… Module defaults restored\n')
1329
1360
  }
1330
1361
 
@@ -1393,20 +1424,17 @@ export async function run(argv = process.argv) {
1393
1424
  if (skipPasswordPolicy) {
1394
1425
  setupArgs.push('--skip-password-policy')
1395
1426
  }
1396
- await runModuleCommand(allModules, 'auth', 'setup', setupArgs)
1397
- // Query DB to get tenant/org IDs using pg directly
1398
- const { Client } = await import('pg')
1399
- const dbUrl = process.env.DATABASE_URL
1400
- const pgClient = new Client({ connectionString: dbUrl, ssl: getSslConfig() })
1401
- await pgClient.connect()
1402
- const orgResult = await pgClient.query(
1403
- `SELECT o.id as org_id, o.tenant_id FROM organizations o
1404
- JOIN users u ON u.organization_id = o.id
1405
- LIMIT 1`
1406
- )
1407
- await pgClient.end()
1408
- const tenantId = orgResult?.rows?.[0]?.tenant_id ?? null
1409
- const orgId = orgResult?.rows?.[0]?.org_id ?? null
1427
+ await runBeforeUsersExist(() => runModuleCommand(allModules, 'auth', 'setup', setupArgs))
1428
+ const initializedOrganization = await withInitializationClient(dbUrl, async (client) => {
1429
+ const orgResult = await client.query<{ tenant_id: string; org_id: string }>(
1430
+ `SELECT o.id AS org_id, o.tenant_id FROM organizations o
1431
+ JOIN users u ON u.organization_id = o.id
1432
+ LIMIT 1`,
1433
+ )
1434
+ return orgResult.rows[0]
1435
+ })
1436
+ const tenantId = initializedOrganization?.tenant_id
1437
+ const orgId = initializedOrganization?.org_id
1410
1438
  if (!tenantId || !orgId) {
1411
1439
  throw new Error('Auth setup failed to create a tenant/org. Aborting init.')
1412
1440
  }
@@ -1447,13 +1475,13 @@ export async function run(argv = process.argv) {
1447
1475
  // Seed module defaults (structural data: dictionaries, tax rates, units, etc.)
1448
1476
  console.log('šŸ“š Seeding module defaults...')
1449
1477
  const { createRequestContainer } = await import('@open-mercato/shared/lib/di/container')
1450
- const seedContainer = await createRequestContainer()
1478
+ const seedContainer = await runWithFreshDatabaseExecutionContext({ kind: 'maintenance', tenantId: null, source: 'cli', operation: 'seed-bootstrap' }, () => createRequestContainer())
1451
1479
  const seedEm = seedContainer.resolve('em') as any
1452
1480
  const seedCtx = { em: seedEm, tenantId, organizationId: orgId, container: seedContainer }
1453
1481
  for (const mod of allModules) {
1454
1482
  if (mod.setup?.seedDefaults) {
1455
1483
  console.log(` šŸ“¦ ${mod.id}...`)
1456
- await mod.setup.seedDefaults(seedCtx)
1484
+ await runDatabaseTenantSetup(seedCtx, (context) => mod.setup!.seedDefaults!(context))
1457
1485
  }
1458
1486
  }
1459
1487
  console.log('āœ… Module defaults seeded\n')
@@ -1462,7 +1490,7 @@ export async function run(argv = process.argv) {
1462
1490
  // ensureDefaultRoleAcls runs before seedDefaults (in setupTenantAndPrimaryUser),
1463
1491
  // so custom roles don't exist yet at that point. This second pass picks them up.
1464
1492
  const { ensureCustomRoleAcls } = await import('@open-mercato/core/modules/auth/lib/setup-app')
1465
- await ensureCustomRoleAcls(seedEm, tenantId, allModules)
1493
+ await runDatabaseTenantSetup({ em: seedEm, tenantId, organizationId: orgId }, (context) => ensureCustomRoleAcls(context.em, tenantId, allModules))
1466
1494
 
1467
1495
  if (skipExamples) {
1468
1496
  console.log('🚫 Example data seeding skipped (--no-examples)\n')
@@ -1472,7 +1500,7 @@ export async function run(argv = process.argv) {
1472
1500
  for (const mod of allModules) {
1473
1501
  if (mod.setup?.seedExamples) {
1474
1502
  console.log(` šŸ“¦ ${mod.id}...`)
1475
- await mod.setup.seedExamples(seedCtx)
1503
+ await runDatabaseTenantSetup(seedCtx, (context) => mod.setup!.seedExamples!(context))
1476
1504
  }
1477
1505
  }
1478
1506
  console.log('āœ… Example data seeded\n')
@@ -1532,6 +1560,8 @@ export async function run(argv = process.argv) {
1532
1560
  console.log('')
1533
1561
  }
1534
1562
 
1563
+ await session.complete()
1564
+
1535
1565
  const adminPasswordOverride = derivedSecrets.adminPassword
1536
1566
  const employeePasswordOverride = derivedSecrets.employeePassword
1537
1567
  const createdUsers: Array<{ label: string; icon: string; email: string }> = []
@@ -1564,6 +1594,8 @@ export async function run(argv = process.argv) {
1564
1594
  } catch (error: unknown) {
1565
1595
  console.error('āŒ Initialization failed:', formatInitFailureMessage(error))
1566
1596
  return 1
1597
+ } finally {
1598
+ await initializationSession?.close().catch(() => undefined)
1567
1599
  }
1568
1600
  }
1569
1601
 
@@ -1723,11 +1755,14 @@ export async function run(argv = process.argv) {
1723
1755
  }
1724
1756
 
1725
1757
  const { createRequestContainer } = await import('@open-mercato/shared/lib/di/container')
1726
- const seedContainer = await createRequestContainer()
1758
+ const seedContainer = await runWithFreshDatabaseExecutionContext({ kind: 'maintenance', tenantId: null, source: 'cli', operation: 'seed-bootstrap' }, () => createRequestContainer())
1727
1759
  const seedEm = seedContainer.resolve('em') as any
1728
1760
 
1729
1761
  const { Organization } = await import('@open-mercato/core/modules/directory/data/entities')
1730
- const orgs = await seedEm.find(Organization, { deletedAt: null }, { populate: ['tenant'] as const })
1762
+ const orgs = !isDatabaseRuntimeEnabled() ? await seedEm.find(Organization, { deletedAt: null }, { populate: ['tenant'] as const }) : await runWithFreshDatabaseExecutionContext({ kind: 'maintenance', tenantId: null, source: 'cli', operation: 'seed-discovery' }, async () => {
1763
+ const discovery = await createRequestContainer()
1764
+ try { return await discovery.resolve<import('@mikro-orm/postgresql').EntityManager>('em').find(Organization, { deletedAt: null }, { populate: ['tenant'] as const }) } finally { await discovery.dispose() }
1765
+ })
1731
1766
 
1732
1767
  if (orgs.length === 0) {
1733
1768
  console.error('āŒ No organizations found. Run yarn initialize first.')
@@ -1744,12 +1779,12 @@ export async function run(argv = process.argv) {
1744
1779
  for (const mod of modulesToSeed) {
1745
1780
  if (mod.setup?.seedDefaults) {
1746
1781
  console.log(` šŸ“¦ ${mod.id}...`)
1747
- await mod.setup.seedDefaults(seedCtx)
1782
+ await runDatabaseTenantSetup(seedCtx, (context) => mod.setup!.seedDefaults!(context))
1748
1783
  }
1749
1784
  }
1750
1785
 
1751
1786
  const { ensureCustomRoleAcls } = await import('@open-mercato/core/modules/auth/lib/setup-app')
1752
- await ensureCustomRoleAcls(seedEm, tenantId, allModules)
1787
+ await runDatabaseTenantSetup({ em: seedEm, tenantId, organizationId }, (context) => ensureCustomRoleAcls(context.em, tenantId, allModules))
1753
1788
  }
1754
1789
 
1755
1790
  console.log('\nāœ… seed:defaults complete.')
@@ -2249,8 +2284,12 @@ export async function run(argv = process.argv) {
2249
2284
  },
2250
2285
  {
2251
2286
  command: 'migrate',
2252
- help: 'Applies every pending migration to the database DATABASE_URL points at.\nThis mutates the database — check .env before running it.',
2287
+ databaseAccess: 'maintenance',
2288
+ help: 'Applies every pending migration using the configured database connection.\nTenant boundaries use the maintenance login. This mutates the database — check .env before running it.',
2253
2289
  run: async () => {
2290
+ if (requiresDatabaseRuntimeForMigration() && !isDatabaseRuntimeEnabled()) {
2291
+ throw new Error('[internal] Tenant boundaries were requested but are not registered. Enable the tenant_boundaries module and run yarn generate before migrating.')
2292
+ }
2254
2293
  const { createResolver } = await import('./lib/resolver')
2255
2294
  const { dbMigrate } = await import('./lib/db')
2256
2295
  const resolver = createResolver()
@@ -2977,7 +3016,7 @@ export async function run(argv = process.argv) {
2977
3016
  }
2978
3017
  try {
2979
3018
  const commandExitCode = await runWithCapturedExitCode(async () => {
2980
- await cmd.run(rest)
3019
+ await runDatabaseCliCommand(cmd, rest, `${modName}:${cmdName}`)
2981
3020
  })
2982
3021
  if (!quietGeneration && (modName !== 'deploy' || cmdName !== 'railway')) {
2983
3022
  const ms = Date.now() - started
@@ -1,15 +0,0 @@
1
- # scheduler — CLI commands
2
-
3
- [Back to module index](index.md)
4
-
5
- ## CLI commands
6
-
7
- | ID / path | Source |
8
- |---|---|
9
- | list | [cli.ts](../../../../node_modules/@open-mercato/scheduler/src/modules/scheduler/cli.ts) |
10
- | status | [cli.ts](../../../../node_modules/@open-mercato/scheduler/src/modules/scheduler/cli.ts) |
11
- | run | [cli.ts](../../../../node_modules/@open-mercato/scheduler/src/modules/scheduler/cli.ts) |
12
- | start | [cli.ts](../../../../node_modules/@open-mercato/scheduler/src/modules/scheduler/cli.ts) |
13
- | audit-queue-targets | [cli.ts](../../../../node_modules/@open-mercato/scheduler/src/modules/scheduler/cli.ts) |
14
-
15
- <!-- end module facts section: scheduler/cli-commands -->