@open-mercato/cli 0.11.1-develop.8920.1.d3c2cc4681 → 0.11.1-develop.8942.1.68c12f7f28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +6 -2
- package/dist/agentic/guides/module-facts.json +356 -385
- package/dist/agentic/guides/module-facts.v2.json +356 -385
- package/dist/agentic/guides/modules/agent_orchestrator/active-extension-bindings.md +1 -1
- package/dist/agentic/guides/modules/agent_orchestrator/exact-override-targets.md +1 -1
- package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
- package/dist/agentic/guides/modules/agent_orchestrator/workers.md +1 -1
- package/dist/agentic/guides/modules/ai_assistant/exact-override-targets.md +2 -2
- package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
- package/dist/agentic/guides/modules/ai_assistant/workers.md +2 -2
- package/dist/agentic/guides/modules/api_docs/index.md +1 -1
- package/dist/agentic/guides/modules/api_keys/index.md +1 -1
- package/dist/agentic/guides/modules/assisted_selling/index.md +1 -1
- package/dist/agentic/guides/modules/attachments/index.md +1 -1
- package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
- package/dist/agentic/guides/modules/auth/entities.md +1 -0
- package/dist/agentic/guides/modules/auth/index.md +2 -2
- package/dist/agentic/guides/modules/auth/umes-hosts.md +1 -0
- package/dist/agentic/guides/modules/availability/index.md +1 -1
- package/dist/agentic/guides/modules/backups/index.md +1 -1
- package/dist/agentic/guides/modules/business_rules/index.md +1 -1
- package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
- package/dist/agentic/guides/modules/cart/index.md +1 -1
- package/dist/agentic/guides/modules/catalog/index.md +1 -1
- package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
- package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
- package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
- package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
- package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
- package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
- package/dist/agentic/guides/modules/channel_ms365/index.md +1 -1
- package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
- package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
- package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
- package/dist/agentic/guides/modules/checkout/index.md +1 -1
- package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
- package/dist/agentic/guides/modules/configs/index.md +1 -1
- package/dist/agentic/guides/modules/content/index.md +1 -1
- package/dist/agentic/guides/modules/currencies/index.md +1 -1
- package/dist/agentic/guides/modules/customer_accounts/exact-override-targets.md +4 -4
- package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
- package/dist/agentic/guides/modules/customer_accounts/workers.md +4 -4
- package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
- package/dist/agentic/guides/modules/customers/index.md +1 -1
- package/dist/agentic/guides/modules/dashboards/index.md +1 -1
- package/dist/agentic/guides/modules/data_sync/index.md +1 -1
- package/dist/agentic/guides/modules/design_system/index.md +1 -1
- package/dist/agentic/guides/modules/devices/index.md +1 -1
- package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
- package/dist/agentic/guides/modules/directory/index.md +1 -1
- package/dist/agentic/guides/modules/documents/index.md +1 -1
- package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
- package/dist/agentic/guides/modules/entities/index.md +1 -1
- package/dist/agentic/guides/modules/eudr/index.md +1 -1
- package/dist/agentic/guides/modules/events/index.md +1 -1
- package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
- package/dist/agentic/guides/modules/forms/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
- package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
- package/dist/agentic/guides/modules/generators/index.md +1 -1
- package/dist/agentic/guides/modules/gus_regon/index.md +1 -1
- package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
- package/dist/agentic/guides/modules/integrations/index.md +1 -1
- package/dist/agentic/guides/modules/ledger/index.md +1 -1
- package/dist/agentic/guides/modules/maintenance/index.md +1 -1
- package/dist/agentic/guides/modules/messages/index.md +1 -1
- package/dist/agentic/guides/modules/notifications/index.md +1 -1
- package/dist/agentic/guides/modules/onboarding/index.md +1 -1
- package/dist/agentic/guides/modules/payment_gateways/exact-override-targets.md +1 -1
- package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
- package/dist/agentic/guides/modules/payment_gateways/workers.md +1 -1
- package/dist/agentic/guides/modules/perspectives/index.md +1 -1
- package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
- package/dist/agentic/guides/modules/planner/index.md +1 -1
- package/dist/agentic/guides/modules/portal/index.md +1 -1
- package/dist/agentic/guides/modules/progress/index.md +1 -1
- package/dist/agentic/guides/modules/promotions/index.md +1 -1
- package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
- package/dist/agentic/guides/modules/query_index/index.md +1 -1
- package/dist/agentic/guides/modules/record_locks/index.md +1 -1
- package/dist/agentic/guides/modules/resources/index.md +1 -1
- package/dist/agentic/guides/modules/sales/exact-override-targets.md +4 -4
- package/dist/agentic/guides/modules/sales/index.md +1 -1
- package/dist/agentic/guides/modules/sales/setup.md +1 -1
- package/dist/agentic/guides/modules/sales_invoices_gl_posting/index.md +1 -1
- package/dist/agentic/guides/modules/scheduler/di-registrations-rich.md +3 -3
- package/dist/agentic/guides/modules/scheduler/di-service-tokens.md +3 -3
- package/dist/agentic/guides/modules/scheduler/exact-override-targets.md +4 -9
- package/dist/agentic/guides/modules/scheduler/index.md +3 -4
- package/dist/agentic/guides/modules/scheduler/workers.md +1 -1
- package/dist/agentic/guides/modules/search/di-registrations-rich.md +4 -4
- package/dist/agentic/guides/modules/search/di-service-tokens.md +13 -0
- package/dist/agentic/guides/modules/search/exact-override-targets.md +4 -4
- package/dist/agentic/guides/modules/search/index.md +3 -2
- package/dist/agentic/guides/modules/security/index.md +1 -1
- package/dist/agentic/guides/modules/seeds/index.md +1 -1
- package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
- package/dist/agentic/guides/modules/sso/index.md +1 -1
- package/dist/agentic/guides/modules/staff/index.md +1 -1
- package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
- package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
- package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
- package/dist/agentic/guides/modules/sync_shopify/index.md +1 -1
- package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
- package/dist/agentic/guides/modules/telemetry/index.md +1 -1
- package/dist/agentic/guides/modules/tenant_boundaries/generator-plugins.md +11 -0
- package/dist/agentic/guides/modules/tenant_boundaries/index.md +13 -0
- package/dist/agentic/guides/modules/tenant_boundaries/owned-contract-module-metadata.md +11 -0
- package/dist/agentic/guides/modules/tillio/index.md +1 -1
- package/dist/agentic/guides/modules/translations/index.md +1 -1
- package/dist/agentic/guides/modules/upgrade_actions/index.md +1 -1
- package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
- package/dist/agentic/guides/modules/webhooks/index.md +1 -1
- package/dist/agentic/guides/modules/wms/index.md +1 -1
- package/dist/agentic/guides/modules/workflows/index.md +1 -1
- package/dist/agentic/guides/reference-module-facts.json +2 -2
- package/dist/agentic/guides/reference-modules/example/index.md +1 -1
- package/dist/agentic/guides/upstream/manifest.json +1 -1
- package/dist/agentic/shared/AGENTS.md.template +3 -3
- package/dist/agentic/shared/ai/harness/cases.json +4 -4
- package/dist/bin.js +6 -3
- package/dist/bin.js.map +2 -2
- package/dist/i18n/de.json +5 -1
- package/dist/i18n/en.json +5 -1
- package/dist/i18n/es.json +5 -1
- package/dist/i18n/ko.json +5 -1
- package/dist/i18n/pl.json +5 -1
- package/dist/lib/cli-bootstrap-mode.js +10 -1
- package/dist/lib/cli-bootstrap-mode.js.map +2 -2
- package/dist/lib/db/commands.js +18 -3
- package/dist/lib/db/commands.js.map +2 -2
- package/dist/lib/db/maintenance-client.js +72 -0
- package/dist/lib/db/maintenance-client.js.map +7 -0
- package/dist/lib/generate-watch-structure.js +2 -1
- package/dist/lib/generate-watch-structure.js.map +2 -2
- package/dist/lib/generators/database-declarations.js +21 -0
- package/dist/lib/generators/database-declarations.js.map +7 -0
- package/dist/lib/generators/module-registry.js +19 -3
- package/dist/lib/generators/module-registry.js.map +2 -2
- package/dist/lib/init-existing-database.js +91 -1
- package/dist/lib/init-existing-database.js.map +2 -2
- package/dist/lib/init-i18n.js +13 -0
- package/dist/lib/init-i18n.js.map +7 -0
- package/dist/lib/init-secrets.js +2 -10
- package/dist/lib/init-secrets.js.map +2 -2
- package/dist/lib/scheduler-supervisor.js +47 -7
- package/dist/lib/scheduler-supervisor.js.map +2 -2
- package/dist/lib/testing/integration-discovery.js +14 -0
- package/dist/lib/testing/integration-discovery.js.map +2 -2
- package/dist/lib/worker-job-handler.js +36 -26
- package/dist/lib/worker-job-handler.js.map +2 -2
- package/dist/mercato.js +93 -54
- package/dist/mercato.js.map +3 -3
- package/package.json +7 -7
- package/src/__tests__/mercato.test.ts +166 -9
- package/src/bin.ts +10 -4
- package/src/i18n/de.json +5 -1
- package/src/i18n/en.json +5 -1
- package/src/i18n/es.json +5 -1
- package/src/i18n/ko.json +5 -1
- package/src/i18n/pl.json +5 -1
- package/src/lib/__tests__/cli-bootstrap-mode.test.ts +76 -1
- package/src/lib/__tests__/generate-watch-structure.test.ts +26 -0
- package/src/lib/__tests__/rotation-kms-warning-presentation.test.ts +1 -1
- package/src/lib/__tests__/scheduler-supervisor.test.ts +107 -0
- package/src/lib/__tests__/worker-job-handler.database.test.ts +76 -0
- package/src/lib/cli-bootstrap-mode.ts +12 -2
- package/src/lib/db/__tests__/commands.migrate-reindex.test.ts +72 -1
- package/src/lib/db/__tests__/maintenance-client.test.ts +70 -0
- package/src/lib/db/commands.ts +20 -6
- package/src/lib/db/maintenance-client.ts +54 -0
- package/src/lib/generate-watch-structure.ts +2 -1
- package/src/lib/generators/__tests__/database-declarations.test.ts +69 -0
- package/src/lib/generators/__tests__/incremental-registry.test.ts +1 -1
- package/src/lib/generators/__tests__/module-subset.test.ts +17 -1
- package/src/lib/generators/database-declarations.ts +19 -0
- package/src/lib/generators/module-registry.ts +23 -4
- package/src/lib/init-existing-database.ts +107 -0
- package/src/lib/init-i18n.ts +11 -0
- package/src/lib/init-secrets.ts +2 -12
- package/src/lib/scheduler-supervisor.ts +40 -7
- package/src/lib/testing/integration-discovery.ts +18 -0
- package/src/lib/worker-job-handler.ts +39 -28
- package/src/mercato.ts +92 -53
- package/dist/agentic/guides/modules/scheduler/cli-commands.md +0 -15
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import type { ModuleWorker } from '@open-mercato/shared/modules/registry'
|
|
3
|
+
import { registerDatabaseRuntimeAdapter, type DatabaseExecutionContext } from '@open-mercato/shared/lib/db/runtime'
|
|
4
|
+
import { registerDatabaseModuleDeclarations } from '@open-mercato/shared/lib/db/declarations'
|
|
5
|
+
import { createPerJobWorkerHandler } from '../worker-job-handler'
|
|
6
|
+
|
|
7
|
+
const storage = new AsyncLocalStorage<DatabaseExecutionContext>()
|
|
8
|
+
const binding = jest.fn(async () => true)
|
|
9
|
+
const declarationsKey = Symbol.for('@open-mercato/shared.databaseModuleDeclarations.v1')
|
|
10
|
+
const runtimeKey = Symbol.for('@open-mercato/shared.databaseRuntime.v1')
|
|
11
|
+
const tenantId = '22222222-2222-4222-8222-222222222222'
|
|
12
|
+
const otherTenantId = '11111111-1111-4111-8111-111111111111'
|
|
13
|
+
const context = { jobId: 'job', attemptNumber: 1, queueName: 'extension' }
|
|
14
|
+
|
|
15
|
+
beforeEach(() => {
|
|
16
|
+
delete (globalThis as Record<symbol, unknown>)[runtimeKey]
|
|
17
|
+
delete (globalThis as Record<symbol, unknown>)[declarationsKey]
|
|
18
|
+
binding.mockReset().mockResolvedValue(true)
|
|
19
|
+
registerDatabaseModuleDeclarations([{ moduleId: 'fixture', declarations: { bindingValidators: [binding] } }])
|
|
20
|
+
registerDatabaseRuntimeAdapter({
|
|
21
|
+
id: 'test', version: '1', configurationKey: '1',
|
|
22
|
+
configurePool: () => ({ ready: async () => undefined, dispose: () => undefined }),
|
|
23
|
+
run: (scope, callback) => storage.run(scope, callback),
|
|
24
|
+
})
|
|
25
|
+
})
|
|
26
|
+
afterEach(() => { delete (globalThis as Record<symbol, unknown>)[runtimeKey]; delete (globalThis as Record<symbol, unknown>)[declarationsKey] })
|
|
27
|
+
|
|
28
|
+
function job(tenant: string) {
|
|
29
|
+
return { id: tenant, createdAt: new Date().toISOString(), payload: { tenantId: tenant } }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
test('binds each concurrent job before creating its container, through dispatch and cleanup', async () => {
|
|
33
|
+
const seen: string[] = []
|
|
34
|
+
const factory = jest.fn(async () => {
|
|
35
|
+
const owner = storage.getStore()
|
|
36
|
+
expect(owner?.kind).toBe('tenant')
|
|
37
|
+
seen.push(owner!.tenantId!)
|
|
38
|
+
return { resolve: <Result,>() => ({ clear: () => expect(storage.getStore()).toBe(owner) }) as Result }
|
|
39
|
+
})
|
|
40
|
+
const worker: ModuleWorker = { id: 'extension:work', queue: 'extension', concurrency: 2, handler: async (queued) => {
|
|
41
|
+
await new Promise<void>((resolve) => setImmediate(resolve))
|
|
42
|
+
expect(storage.getStore()?.tenantId).toBe((queued.payload as { tenantId: string }).tenantId)
|
|
43
|
+
} }
|
|
44
|
+
const handler = createPerJobWorkerHandler([worker], factory)
|
|
45
|
+
await Promise.all([handler(job(tenantId), context), handler(job(otherTenantId), context)])
|
|
46
|
+
expect(seen.sort()).toEqual([tenantId, otherTenantId].sort())
|
|
47
|
+
expect(storage.getStore()).toBeUndefined()
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
test('rejects invalid scope before container creation and preserves worker failure for retry', async () => {
|
|
51
|
+
const clear = jest.fn()
|
|
52
|
+
const factory = jest.fn(async () => ({ resolve: <Result,>() => ({ clear }) as Result }))
|
|
53
|
+
const failure = new Error('[internal] Retry me')
|
|
54
|
+
const handler = createPerJobWorkerHandler([{ id: 'extension:work', queue: 'extension', concurrency: 1, handler: async () => { throw failure } }], factory)
|
|
55
|
+
await expect(handler(job('invalid'), context)).rejects.toThrow('verified tenant UUID')
|
|
56
|
+
expect(factory).not.toHaveBeenCalled()
|
|
57
|
+
await expect(handler(job(tenantId), context)).rejects.toBe(failure)
|
|
58
|
+
await expect(handler(job(tenantId), { ...context, attemptNumber: 2 })).rejects.toBe(failure)
|
|
59
|
+
expect(clear).toHaveBeenCalledTimes(2)
|
|
60
|
+
expect(storage.getStore()).toBeUndefined()
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
test('rejects inactive persisted tenants before creating a container', async () => {
|
|
64
|
+
binding.mockImplementation(async () => { expect(storage.getStore()?.kind).toBe('identity'); return false })
|
|
65
|
+
const factory = jest.fn()
|
|
66
|
+
const handler = createPerJobWorkerHandler([], factory)
|
|
67
|
+
await expect(handler(job(tenantId), context)).rejects.toThrow('persisted active tenant')
|
|
68
|
+
expect(factory).not.toHaveBeenCalled()
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
test('awaits container disposal inside the live invocation after a failed job', async () => {
|
|
72
|
+
const dispose = jest.fn(async () => { await new Promise<void>((resolve) => setImmediate(resolve)); expect(storage.getStore()?.tenantId).toBe(tenantId) })
|
|
73
|
+
const handler = createPerJobWorkerHandler([{ id: 'extension:work', queue: 'extension', handler: async () => { throw new Error('retry') } }], async () => ({ resolve: <Result,>() => ({ clear: () => undefined }) as Result, dispose }))
|
|
74
|
+
await expect(handler(job(tenantId), context)).rejects.toThrow('retry')
|
|
75
|
+
expect(dispose).toHaveBeenCalledTimes(1)
|
|
76
|
+
})
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
import { parseBooleanToken } from '@open-mercato/shared/lib/boolean'
|
|
2
|
+
|
|
3
|
+
export type CliBootstrapMode = 'none' | 'dev-supervisor' | 'full' | 'database-migrate'
|
|
2
4
|
|
|
3
5
|
const BOOTSTRAP_FREE_COMMANDS = new Set([
|
|
4
6
|
'generate',
|
|
@@ -24,8 +26,16 @@ const BOOTSTRAP_FREE_COMMANDS = new Set([
|
|
|
24
26
|
])
|
|
25
27
|
|
|
26
28
|
export function resolveCliBootstrapMode(argv: readonly string[]): CliBootstrapMode {
|
|
27
|
-
const [, , first, second] = argv
|
|
29
|
+
const [, , first, second, ...args] = argv
|
|
30
|
+
if (first === 'db' && second === 'migrate' && !args.some((arg) => arg === '--help' || arg === '-h')) {
|
|
31
|
+
return 'database-migrate'
|
|
32
|
+
}
|
|
28
33
|
if (!first || BOOTSTRAP_FREE_COMMANDS.has(first)) return 'none'
|
|
29
34
|
if (first === 'server' && second === 'dev') return 'dev-supervisor'
|
|
30
35
|
return 'full'
|
|
31
36
|
}
|
|
37
|
+
|
|
38
|
+
export function requiresDatabaseRuntimeForMigration(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
39
|
+
const configured = env.OM_TENANT_RLS?.trim()
|
|
40
|
+
return Boolean(configured) && parseBooleanToken(configured) !== false
|
|
41
|
+
}
|
|
@@ -8,6 +8,17 @@ import type { ModuleEntry, PackageResolver } from '../../resolver'
|
|
|
8
8
|
const collectQueryIndexReindexEntityTypes = jest.fn<Promise<string[]>, [any, any]>()
|
|
9
9
|
const requestQueryIndexReindex = jest.fn<Promise<{ requested: string[]; queued: boolean }>, [any, any]>()
|
|
10
10
|
const isMigrationReindexEnabled = jest.fn<boolean, []>()
|
|
11
|
+
const beforeMigrate = jest.fn<Promise<void>, []>()
|
|
12
|
+
const afterMigrate = jest.fn<Promise<void>, []>()
|
|
13
|
+
const recoverHistory = jest.fn<boolean, []>()
|
|
14
|
+
|
|
15
|
+
jest.mock('@open-mercato/shared/lib/db/runtime', () => ({
|
|
16
|
+
beforeDatabaseMigrate: () => beforeMigrate(),
|
|
17
|
+
afterDatabaseMigrate: () => afterMigrate(),
|
|
18
|
+
shouldRecoverDatabaseMigrationReindex: () => recoverHistory(),
|
|
19
|
+
resolveDatabaseConnectionUrl: (_purpose: string, defaultUrl: string) => recoverHistory() ? 'postgres://maintenance@localhost:5432/test' : defaultUrl,
|
|
20
|
+
runWithDatabaseExecutionContext: (_context: unknown, callback: () => unknown) => callback(),
|
|
21
|
+
}))
|
|
11
22
|
|
|
12
23
|
jest.mock('../migration-reindex', () => ({
|
|
13
24
|
collectQueryIndexReindexEntityTypes: (...args: any[]) => collectQueryIndexReindexEntityTypes(...(args as [any, any])),
|
|
@@ -19,7 +30,7 @@ jest.mock('../migration-reindex', () => ({
|
|
|
19
30
|
// real `MikroORM` class at import time, so replacing the module export breaks the driver import.
|
|
20
31
|
const ormInit = jest.fn()
|
|
21
32
|
|
|
22
|
-
type PendingPlan = { pending: string[]; failOn?: string }
|
|
33
|
+
type PendingPlan = { pending: string[]; executed?: string[]; failOn?: string }
|
|
23
34
|
|
|
24
35
|
const tempDirs: string[] = []
|
|
25
36
|
const ormCloses: string[] = []
|
|
@@ -68,6 +79,7 @@ function stubOrmsFor(plans: Record<string, PendingPlan>): void {
|
|
|
68
79
|
const plan = moduleId ? plans[moduleId] : { pending: [] }
|
|
69
80
|
return {
|
|
70
81
|
migrator: {
|
|
82
|
+
getExecuted: async () => (plan.executed ?? []).map((name) => ({ name })),
|
|
71
83
|
getPending: async () => plan.pending.map((name) => ({ name, path: null })),
|
|
72
84
|
up: async (options: { migrations?: string[] } = {}) => {
|
|
73
85
|
const name = options.migrations?.[0]
|
|
@@ -89,6 +101,9 @@ describe('dbMigrate discharges query-index reindex declarations', () => {
|
|
|
89
101
|
|
|
90
102
|
beforeEach(() => {
|
|
91
103
|
process.env.DATABASE_URL = process.env.DATABASE_URL || 'postgres://noop@localhost:5432/test'
|
|
104
|
+
beforeMigrate.mockReset().mockResolvedValue(undefined)
|
|
105
|
+
afterMigrate.mockReset().mockResolvedValue(undefined)
|
|
106
|
+
recoverHistory.mockReset().mockReturnValue(false)
|
|
92
107
|
ormCloses.length = 0
|
|
93
108
|
ormInit.mockReset()
|
|
94
109
|
initSpy = jest.spyOn(MikroORM, 'init').mockImplementation((...args: any[]) => ormInit(...args))
|
|
@@ -186,4 +201,60 @@ describe('dbMigrate discharges query-index reindex declarations', () => {
|
|
|
186
201
|
expect(collectQueryIndexReindexEntityTypes).not.toHaveBeenCalled()
|
|
187
202
|
expect(requestQueryIndexReindex).not.toHaveBeenCalled()
|
|
188
203
|
})
|
|
204
|
+
it('preflights before opening module ORMs and reconciles even with no pending migrations', async () => {
|
|
205
|
+
recoverHistory.mockReturnValue(true)
|
|
206
|
+
const module = { id: 'alpha', dir: createTempModule('alpha') }
|
|
207
|
+
stubOrmsFor({ alpha: { pending: [], executed: ['MigrationCommittedBeforeRetry'] } })
|
|
208
|
+
beforeMigrate.mockImplementation(async () => { expect(ormInit).not.toHaveBeenCalled() })
|
|
209
|
+
afterMigrate.mockImplementation(async () => {
|
|
210
|
+
expect(ormCloses).toEqual(['alpha'])
|
|
211
|
+
expect(requestQueryIndexReindex).not.toHaveBeenCalled()
|
|
212
|
+
})
|
|
213
|
+
await dbMigrate(createMockResolver([module]))
|
|
214
|
+
expect(afterMigrate).toHaveBeenCalledTimes(1)
|
|
215
|
+
expect(ormInit.mock.calls[0][0].clientUrl).toBe('postgres://maintenance@localhost:5432/test')
|
|
216
|
+
expect(collectQueryIndexReindexEntityTypes.mock.calls[0][0]).toEqual([
|
|
217
|
+
expect.objectContaining({ moduleId: 'alpha', name: 'MigrationCommittedBeforeRetry' }),
|
|
218
|
+
])
|
|
219
|
+
expect(requestQueryIndexReindex).toHaveBeenCalledTimes(1)
|
|
220
|
+
})
|
|
221
|
+
|
|
222
|
+
it('recovers committed history together with newly applied declarations after reconciliation', async () => {
|
|
223
|
+
recoverHistory.mockReturnValue(true)
|
|
224
|
+
const module = { id: 'alpha', dir: createTempModule('alpha') }
|
|
225
|
+
stubOrmsFor({ alpha: { pending: ['MigrationNew'], executed: ['MigrationCommitted'] } })
|
|
226
|
+
await dbMigrate(createMockResolver([module]))
|
|
227
|
+
expect(collectQueryIndexReindexEntityTypes.mock.calls[0][0].map((migration: { name: string }) => migration.name))
|
|
228
|
+
.toEqual(['MigrationCommitted', 'MigrationNew'])
|
|
229
|
+
})
|
|
230
|
+
|
|
231
|
+
it('dispatches no protected reindex after a partial schema failure', async () => {
|
|
232
|
+
recoverHistory.mockReturnValue(true)
|
|
233
|
+
const module = { id: 'alpha', dir: createTempModule('alpha') }
|
|
234
|
+
stubOrmsFor({ alpha: { pending: ['MigrationCommitted', 'MigrationBroken'], failOn: 'MigrationBroken' } })
|
|
235
|
+
await expect(dbMigrate(createMockResolver([module]))).rejects.toThrow('MigrationBroken')
|
|
236
|
+
expect(afterMigrate).not.toHaveBeenCalled()
|
|
237
|
+
expect(collectQueryIndexReindexEntityTypes).not.toHaveBeenCalled()
|
|
238
|
+
expect(requestQueryIndexReindex).not.toHaveBeenCalled()
|
|
239
|
+
expect(ormCloses).toEqual(['alpha'])
|
|
240
|
+
})
|
|
241
|
+
|
|
242
|
+
it('propagates reconciliation failure without dispatching protected reindex', async () => {
|
|
243
|
+
recoverHistory.mockReturnValue(true)
|
|
244
|
+
const module = { id: 'alpha', dir: createTempModule('alpha') }
|
|
245
|
+
stubOrmsFor({ alpha: { pending: [] } })
|
|
246
|
+
afterMigrate.mockRejectedValue(new Error('[internal] policy reconciliation failed'))
|
|
247
|
+
await expect(dbMigrate(createMockResolver([module]))).rejects.toThrow('policy reconciliation failed')
|
|
248
|
+
expect(requestQueryIndexReindex).not.toHaveBeenCalled()
|
|
249
|
+
expect(ormCloses).toEqual(['alpha'])
|
|
250
|
+
})
|
|
251
|
+
|
|
252
|
+
it('opens no module ORM if privileged preflight fails', async () => {
|
|
253
|
+
beforeMigrate.mockRejectedValue(new Error('[internal] unsafe maintenance role'))
|
|
254
|
+
const module = { id: 'alpha', dir: createTempModule('alpha') }
|
|
255
|
+
await expect(dbMigrate(createMockResolver([module]))).rejects.toThrow('unsafe maintenance role')
|
|
256
|
+
expect(ormInit).not.toHaveBeenCalled()
|
|
257
|
+
expect(requestQueryIndexReindex).not.toHaveBeenCalled()
|
|
258
|
+
})
|
|
259
|
+
|
|
189
260
|
})
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import { createCliMaintenanceClient } from '../maintenance-client'
|
|
3
|
+
import { configureDatabasePool, isDatabaseRuntimeEnabled, runWithFreshDatabaseExecutionContext } from '@open-mercato/shared/lib/db/runtime'
|
|
4
|
+
|
|
5
|
+
const query = jest.fn(async () => ({ rows: [] }))
|
|
6
|
+
const end = jest.fn(async () => undefined)
|
|
7
|
+
const ready = jest.fn(async () => undefined)
|
|
8
|
+
const dispose = jest.fn()
|
|
9
|
+
const connectionScope = new AsyncLocalStorage<symbol>()
|
|
10
|
+
const sessionQuery = jest.fn(async (_sql: string) => ({ rows: [{ owner: connectionScope.getStore() }] }))
|
|
11
|
+
const release = jest.fn()
|
|
12
|
+
const connect = jest.fn(async () => ({ query: sessionQuery, release, on: jest.fn() }))
|
|
13
|
+
jest.mock('pg', () => ({
|
|
14
|
+
Pool: jest.fn(() => ({ connect, query, end })),
|
|
15
|
+
Client: jest.fn(() => ({ legacy: true })),
|
|
16
|
+
}))
|
|
17
|
+
jest.mock('@open-mercato/shared/lib/db/ssl', () => ({ getSslConfig: () => undefined }))
|
|
18
|
+
jest.mock('@open-mercato/shared/lib/db/runtime', () => ({
|
|
19
|
+
isDatabaseRuntimeEnabled: jest.fn(() => true),
|
|
20
|
+
resolveDatabaseConnectionUrl: jest.fn(() => 'private-maintenance-connection'),
|
|
21
|
+
configureDatabasePool: jest.fn(() => ({ ready, dispose })),
|
|
22
|
+
runWithFreshDatabaseExecutionContext: jest.fn((_context, callback) => callback()),
|
|
23
|
+
}))
|
|
24
|
+
beforeEach(() => { jest.clearAllMocks(); jest.mocked(isDatabaseRuntimeEnabled).mockReturnValue(true); ready.mockResolvedValue(undefined) })
|
|
25
|
+
it('routes readiness and SQL through explicit maintenance scopes and drains registration', async () => {
|
|
26
|
+
const client = await createCliMaintenanceClient('private-runtime-connection')
|
|
27
|
+
await client.connect()
|
|
28
|
+
await client.query('SELECT 1')
|
|
29
|
+
await client.end()
|
|
30
|
+
expect(configureDatabasePool).toHaveBeenCalledWith(expect.any(Object), { id: 'cli.maintenance', purpose: 'maintenance', tables: [] })
|
|
31
|
+
expect(runWithFreshDatabaseExecutionContext).toHaveBeenCalledTimes(2)
|
|
32
|
+
expect(runWithFreshDatabaseExecutionContext).toHaveBeenLastCalledWith({ kind: 'maintenance', tenantId: null, source: 'cli', operation: 'database-maintenance' }, expect.any(Function))
|
|
33
|
+
expect(query).toHaveBeenCalledWith('SELECT 1')
|
|
34
|
+
expect(end).toHaveBeenCalledTimes(1)
|
|
35
|
+
expect(dispose).toHaveBeenCalledTimes(1)
|
|
36
|
+
})
|
|
37
|
+
it('rejects SQL when physical role verification fails', async () => {
|
|
38
|
+
ready.mockRejectedValueOnce(new Error('wrong role'))
|
|
39
|
+
const client = await createCliMaintenanceClient('private-runtime-connection')
|
|
40
|
+
await expect(client.query('SELECT 1')).rejects.toThrow('wrong role')
|
|
41
|
+
expect(query).not.toHaveBeenCalled()
|
|
42
|
+
await client.end()
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it('retains the same maintenance invocation and physical client across initialization queries', async () => {
|
|
46
|
+
const owner = Symbol('maintenance invocation')
|
|
47
|
+
jest.mocked(runWithFreshDatabaseExecutionContext).mockImplementationOnce((_context, callback) => connectionScope.run(owner, callback))
|
|
48
|
+
const client = await createCliMaintenanceClient('private-runtime-connection', { pinned: true })
|
|
49
|
+
await client.connect()
|
|
50
|
+
try {
|
|
51
|
+
expect(await client.query('SELECT pg_try_advisory_lock(1)')).toEqual({ rows: [{ owner }] })
|
|
52
|
+
expect(await client.query('SELECT 1')).toEqual({ rows: [{ owner }] })
|
|
53
|
+
expect(connect).toHaveBeenCalledTimes(1)
|
|
54
|
+
expect(query).not.toHaveBeenCalled()
|
|
55
|
+
expect(release).not.toHaveBeenCalled()
|
|
56
|
+
} finally {
|
|
57
|
+
await client.end()
|
|
58
|
+
}
|
|
59
|
+
expect(release).toHaveBeenCalledWith(true)
|
|
60
|
+
expect(end).toHaveBeenCalledTimes(1)
|
|
61
|
+
expect(dispose).toHaveBeenCalledTimes(1)
|
|
62
|
+
})
|
|
63
|
+
it('preserves the legacy client and closes pools after registration rejection', async () => {
|
|
64
|
+
jest.mocked(isDatabaseRuntimeEnabled).mockReturnValue(false)
|
|
65
|
+
expect(await createCliMaintenanceClient(undefined)).toEqual({ legacy: true })
|
|
66
|
+
jest.mocked(isDatabaseRuntimeEnabled).mockReturnValue(true)
|
|
67
|
+
jest.mocked(configureDatabasePool).mockImplementationOnce(() => { throw new Error('registration rejected') })
|
|
68
|
+
await expect(createCliMaintenanceClient('private-runtime-connection')).rejects.toThrow('registration rejected')
|
|
69
|
+
expect(end).toHaveBeenCalledTimes(1)
|
|
70
|
+
})
|
package/src/lib/db/commands.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { ReflectMetadataProvider } from '@mikro-orm/decorators/legacy'
|
|
|
7
7
|
import { Migrator } from '@mikro-orm/migrations'
|
|
8
8
|
import { PostgreSqlDriver } from '@mikro-orm/postgresql'
|
|
9
9
|
import { getSslConfig } from '@open-mercato/shared/lib/db/ssl'
|
|
10
|
+
import { afterDatabaseMigrate, beforeDatabaseMigrate, resolveDatabaseConnectionUrl, runWithDatabaseExecutionContext, shouldRecoverDatabaseMigrationReindex } from '@open-mercato/shared/lib/db/runtime'
|
|
10
11
|
import type { PackageResolver, ModuleEntry } from '../resolver'
|
|
11
12
|
import { quotePostgresIdentifier } from './identifiers'
|
|
12
13
|
import { preserveUnconstrainedNumericSnapshots } from './numeric-snapshots'
|
|
@@ -446,11 +447,18 @@ export async function dbGenerate(resolver: PackageResolver, options: DbOptions =
|
|
|
446
447
|
}
|
|
447
448
|
|
|
448
449
|
export async function dbMigrate(resolver: PackageResolver, options: DbOptions = {}): Promise<void> {
|
|
450
|
+
return runWithDatabaseExecutionContext({ kind: 'maintenance', tenantId: null, source: 'cli', operation: 'db:migrate' }, () => migrateModules(resolver, options))
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
async function migrateModules(resolver: PackageResolver, _options: DbOptions): Promise<void> {
|
|
449
454
|
const modules = resolver.loadEnabledModules()
|
|
450
455
|
const ordered = sortModules(modules)
|
|
451
456
|
const results: string[] = []
|
|
452
457
|
const appliedMigrations: AppliedMigration[] = []
|
|
458
|
+
const recoverHistory = shouldRecoverDatabaseMigrationReindex()
|
|
459
|
+
let reconciled = false
|
|
453
460
|
|
|
461
|
+
await beforeDatabaseMigrate()
|
|
454
462
|
try {
|
|
455
463
|
for (const entry of ordered) {
|
|
456
464
|
const modId = entry.id
|
|
@@ -474,7 +482,7 @@ export async function dbMigrate(resolver: PackageResolver, options: DbOptions =
|
|
|
474
482
|
const sslConfig = getSslConfig()
|
|
475
483
|
const orm = await MikroORM.init<PostgreSqlDriver>({
|
|
476
484
|
driver: PostgreSqlDriver,
|
|
477
|
-
clientUrl: getClientUrl(),
|
|
485
|
+
clientUrl: resolveDatabaseConnectionUrl('maintenance', getClientUrl()),
|
|
478
486
|
loggerFactory: () => createMinimalLogger(),
|
|
479
487
|
dynamicImportProvider,
|
|
480
488
|
entities: [],
|
|
@@ -503,6 +511,12 @@ export async function dbMigrate(resolver: PackageResolver, options: DbOptions =
|
|
|
503
511
|
|
|
504
512
|
try {
|
|
505
513
|
const migrator = orm.migrator as Migrator
|
|
514
|
+
if (recoverHistory) {
|
|
515
|
+
const executed = await migrator.getExecuted()
|
|
516
|
+
for (const migration of executed) {
|
|
517
|
+
appliedMigrations.push({ moduleId: modId, migrationsPath, name: migration.name })
|
|
518
|
+
}
|
|
519
|
+
}
|
|
506
520
|
const pending = await migrator.getPending()
|
|
507
521
|
if (!pending.length) {
|
|
508
522
|
results.push(formatResult(modId, 'no pending migrations', ''))
|
|
@@ -514,16 +528,14 @@ export async function dbMigrate(resolver: PackageResolver, options: DbOptions =
|
|
|
514
528
|
}
|
|
515
529
|
for (const migration of pending) {
|
|
516
530
|
const migrationName =
|
|
517
|
-
typeof migration === 'string'
|
|
518
|
-
? migration
|
|
519
|
-
: (migration as any).name ?? (migration as any).fileName
|
|
531
|
+
typeof migration === 'string' ? migration : migration.name
|
|
520
532
|
await migrator.up(migrationName ? { migrations: [migrationName] } : undefined)
|
|
521
533
|
if (migrationName) {
|
|
522
534
|
appliedMigrations.push({
|
|
523
535
|
moduleId: modId,
|
|
524
536
|
migrationsPath,
|
|
525
537
|
name: String(migrationName),
|
|
526
|
-
filePath: typeof migration === 'string' ? null :
|
|
538
|
+
filePath: typeof migration === 'string' ? null : migration.path ?? null,
|
|
527
539
|
})
|
|
528
540
|
}
|
|
529
541
|
applied += 1
|
|
@@ -540,9 +552,11 @@ export async function dbMigrate(resolver: PackageResolver, options: DbOptions =
|
|
|
540
552
|
await orm.close(true)
|
|
541
553
|
}
|
|
542
554
|
}
|
|
555
|
+
await afterDatabaseMigrate()
|
|
556
|
+
reconciled = true
|
|
543
557
|
} finally {
|
|
544
558
|
console.log(results.join('\n'))
|
|
545
|
-
await dischargeQueryIndexReindexRequests(appliedMigrations)
|
|
559
|
+
if (!recoverHistory || reconciled) await dischargeQueryIndexReindexRequests(appliedMigrations)
|
|
546
560
|
}
|
|
547
561
|
}
|
|
548
562
|
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import { Client, Pool } from 'pg'
|
|
3
|
+
import { configureDatabasePool, isDatabaseRuntimeEnabled, resolveDatabaseConnectionUrl, runWithFreshDatabaseExecutionContext } from '@open-mercato/shared/lib/db/runtime'
|
|
4
|
+
import { getSslConfig } from '@open-mercato/shared/lib/db/ssl'
|
|
5
|
+
|
|
6
|
+
export async function createCliMaintenanceClient(connectionString: string | undefined, options?: { pinned?: boolean }) {
|
|
7
|
+
if (!isDatabaseRuntimeEnabled()) {
|
|
8
|
+
const client = new Client({ connectionString, ssl: getSslConfig(), ...(options?.pinned ? { keepAlive: true } : {}) })
|
|
9
|
+
if (options?.pinned) client.on('error', () => undefined)
|
|
10
|
+
return client
|
|
11
|
+
}
|
|
12
|
+
if (!connectionString) throw new Error('[internal] Database maintenance requires a configured connection')
|
|
13
|
+
const pool = new Pool({ connectionString: resolveDatabaseConnectionUrl('maintenance', connectionString), ssl: getSslConfig(), max: 1, connectionTimeoutMillis: 5_000, statement_timeout: 30_000, ...(options?.pinned ? { keepAlive: true } : {}) })
|
|
14
|
+
const lifecycle = await (async () => {
|
|
15
|
+
try { return configureDatabasePool(pool, { id: 'cli.maintenance', purpose: 'maintenance', tables: [] }) } catch (error) { await pool.end(); throw error }
|
|
16
|
+
})()
|
|
17
|
+
const invoke = <Result>(callback: () => Promise<Result>) => runWithFreshDatabaseExecutionContext({ kind: 'maintenance', tenantId: null, source: 'cli', operation: 'database-maintenance' }, callback)
|
|
18
|
+
const end = async () => { try { await pool.end() } finally { lifecycle.dispose() } }
|
|
19
|
+
if (options?.pinned) {
|
|
20
|
+
const connection = Promise.withResolvers<Pool['query']>()
|
|
21
|
+
const closed = Promise.withResolvers<void>()
|
|
22
|
+
let lease: Promise<void> | undefined
|
|
23
|
+
return {
|
|
24
|
+
connect: async () => {
|
|
25
|
+
lease ??= invoke(async () => {
|
|
26
|
+
await lifecycle.ready()
|
|
27
|
+
const client = await pool.connect()
|
|
28
|
+
const runInOwnerScope = AsyncLocalStorage.snapshot()
|
|
29
|
+
try {
|
|
30
|
+
client.on('error', () => undefined)
|
|
31
|
+
connection.resolve(((...args: unknown[]) => runInOwnerScope(() => Reflect.apply(client.query, client, args))) as Pool['query'])
|
|
32
|
+
await closed.promise
|
|
33
|
+
} finally {
|
|
34
|
+
client.release(true)
|
|
35
|
+
}
|
|
36
|
+
}).catch(connection.reject)
|
|
37
|
+
await connection.promise
|
|
38
|
+
},
|
|
39
|
+
query: (async (...args: unknown[]) => Reflect.apply(await connection.promise, undefined, args)) as Pool['query'],
|
|
40
|
+
end: async () => {
|
|
41
|
+
closed.resolve()
|
|
42
|
+
try { await lease } finally { await end() }
|
|
43
|
+
},
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return {
|
|
47
|
+
connect: () => invoke(() => lifecycle.ready()),
|
|
48
|
+
query: ((...arguments_: unknown[]) => invoke(async () => {
|
|
49
|
+
await lifecycle.ready()
|
|
50
|
+
return Reflect.apply(pool.query, pool, arguments_)
|
|
51
|
+
})) as Pool['query'],
|
|
52
|
+
end,
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -2,6 +2,7 @@ import crypto from 'node:crypto'
|
|
|
2
2
|
import fs from 'node:fs'
|
|
3
3
|
import path from 'node:path'
|
|
4
4
|
import ts from 'typescript-js'
|
|
5
|
+
import { databaseDeclarationsPlugin } from './generators/database-declarations'
|
|
5
6
|
import {
|
|
6
7
|
MODULE_CODE_EXTENSIONS,
|
|
7
8
|
SCAN_CONFIGS,
|
|
@@ -632,7 +633,7 @@ export function collectGenerateWatchStructureSnapshot(
|
|
|
632
633
|
const collector = new SnapshotCollector(cacheState)
|
|
633
634
|
for (const reason of options.webResearchAdapterFullReasons ?? []) collector.fullReasons.add(reason)
|
|
634
635
|
collector.file(`configuration:${options.modulesFile}`, options.modulesFile, { category: 'configuration' })
|
|
635
|
-
const plugins = new Set
|
|
636
|
+
const plugins = new Set([databaseDeclarationsPlugin.conventionFile])
|
|
636
637
|
options.moduleRoots.forEach((roots, index) => addModule(collector, roots, index, plugins))
|
|
637
638
|
options.moduleRoots.forEach((roots, index) => {
|
|
638
639
|
const identity = `module:${index}:${roots.moduleId ?? path.basename(roots.appBase)}:${roots.appBase}:${roots.pkgBase}`
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import os from 'node:os'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import type { ModuleEntry, PackageResolver } from '../../resolver'
|
|
5
|
+
import { generateModuleRegistry, generateModuleRegistryCli } from '../module-registry'
|
|
6
|
+
|
|
7
|
+
let fixtureRoot: string
|
|
8
|
+
|
|
9
|
+
function write(relative: string, content: string): void {
|
|
10
|
+
const target = path.join(fixtureRoot, relative)
|
|
11
|
+
fs.mkdirSync(path.dirname(target), { recursive: true })
|
|
12
|
+
fs.writeFileSync(target, content)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
beforeEach(() => { fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'database-declarations-generator-')) })
|
|
16
|
+
afterEach(() => fs.rmSync(fixtureRoot, { recursive: true, force: true }))
|
|
17
|
+
|
|
18
|
+
it.each([false, true])('discovers neutral database declarations without enterprise (standalone=%s)', async (standalone) => {
|
|
19
|
+
const packageRoot = standalone ? 'node_modules/fixture' : 'packages/core'
|
|
20
|
+
const moduleRoot = `${packageRoot}/${standalone ? 'dist' : 'src'}/modules`
|
|
21
|
+
const extension = standalone ? 'js' : 'ts'
|
|
22
|
+
write(`${moduleRoot}/owner/database.${extension}`, 'export const databaseDeclarations = { bindingValidators: [] }')
|
|
23
|
+
write(`${moduleRoot}/extension/database.${extension}`, 'export const databaseDeclarations = {}')
|
|
24
|
+
const outputDir = path.join(fixtureRoot, '.mercato/generated')
|
|
25
|
+
const entries: ModuleEntry[] = [
|
|
26
|
+
{ id: 'owner', from: '@fixture/owner' },
|
|
27
|
+
{ id: 'extension', from: '@fixture/extension' },
|
|
28
|
+
]
|
|
29
|
+
const resolver: PackageResolver = {
|
|
30
|
+
isMonorepo: () => !standalone,
|
|
31
|
+
getRootDir: () => fixtureRoot,
|
|
32
|
+
getAppDir: () => fixtureRoot,
|
|
33
|
+
getOutputDir: () => outputDir,
|
|
34
|
+
getModulesConfigPath: () => path.join(fixtureRoot, 'src/modules.ts'),
|
|
35
|
+
discoverPackages: () => [],
|
|
36
|
+
loadEnabledModules: () => entries,
|
|
37
|
+
getModulePaths: (entry) => ({
|
|
38
|
+
appBase: path.join(fixtureRoot, 'src/modules', entry.id),
|
|
39
|
+
pkgBase: path.join(fixtureRoot, moduleRoot, entry.id),
|
|
40
|
+
}),
|
|
41
|
+
getModuleImportBase: (entry) => ({
|
|
42
|
+
appBase: `@/modules/${entry.id}`,
|
|
43
|
+
pkgBase: `${entry.from}/modules/${entry.id}`,
|
|
44
|
+
}),
|
|
45
|
+
getPackageOutputDir: () => outputDir,
|
|
46
|
+
getPackageRoot: () => path.join(fixtureRoot, packageRoot),
|
|
47
|
+
}
|
|
48
|
+
expect((await generateModuleRegistry({ resolver, quiet: true })).errors).toEqual([])
|
|
49
|
+
expect((await generateModuleRegistryCli({ resolver, quiet: true })).errors).toEqual([])
|
|
50
|
+
const read = (name: string) => fs.readFileSync(path.join(outputDir, name), 'utf8')
|
|
51
|
+
expect(read('database-declarations.generated.ts')).toContain('@fixture/owner/modules/owner/database')
|
|
52
|
+
expect(read('database-declarations.generated.ts')).toContain('@fixture/extension/modules/extension/database')
|
|
53
|
+
expect(read('bootstrap-registrations.generated.ts')).toContain('registerDatabaseModuleDeclarations(databaseModuleDeclarations)')
|
|
54
|
+
expect(read('bootstrap-registrations.generated.ts')).not.toContain('@open-mercato/enterprise')
|
|
55
|
+
expect(JSON.parse(read('dev-supervisor.generated.json')).requiresFullBootstrap).toBe(true)
|
|
56
|
+
expect(fs.existsSync(path.join(outputDir, 'tenant-boundaries.generated.ts'))).toBe(false)
|
|
57
|
+
|
|
58
|
+
entries.splice(0, 1)
|
|
59
|
+
expect((await generateModuleRegistry({ resolver, quiet: true })).errors).toEqual([])
|
|
60
|
+
expect(read('database-declarations.generated.ts')).not.toContain('@fixture/owner/modules/owner/database')
|
|
61
|
+
expect(read('database-declarations.generated.ts')).toContain('@fixture/extension/modules/extension/database')
|
|
62
|
+
|
|
63
|
+
entries.splice(0)
|
|
64
|
+
expect((await generateModuleRegistry({ resolver, quiet: true })).errors).toEqual([])
|
|
65
|
+
expect((await generateModuleRegistryCli({ resolver, quiet: true })).errors).toEqual([])
|
|
66
|
+
expect(read('database-declarations.generated.ts')).toContain('databaseModuleDeclarations')
|
|
67
|
+
expect(read('database-declarations.generated.ts')).not.toContain('@fixture/')
|
|
68
|
+
expect(JSON.parse(read('dev-supervisor.generated.json')).requiresFullBootstrap).toBe(false)
|
|
69
|
+
})
|
|
@@ -229,7 +229,7 @@ it('preserves unselected plugin ownership and reconciles it on the next full gen
|
|
|
229
229
|
const full = capture()
|
|
230
230
|
expect(full['extra.generated.ts']).toBeUndefined()
|
|
231
231
|
expect(full['extra.generated.checksum']).toBeUndefined()
|
|
232
|
-
expect(full['.generator-plugin-outputs.json']).
|
|
232
|
+
expect(JSON.parse(full['.generator-plugin-outputs.json'].content)).toEqual(['database-declarations.generated.ts'])
|
|
233
233
|
})
|
|
234
234
|
|
|
235
235
|
it('emits the aggregate command loader once without unrelated registry families', async () => {
|
|
@@ -1253,6 +1253,22 @@ export default async function handle(): Promise<void> {}
|
|
|
1253
1253
|
expect(second.filesWritten).not.toContain(manifestPath)
|
|
1254
1254
|
})
|
|
1255
1255
|
|
|
1256
|
+
it('runs bootstrap registrations before dev supervisor probes for any enabled plugin owner', async () => {
|
|
1257
|
+
scaffoldModule(tmpDir, 'custom_runtime', 'pkg', ['generators.ts'])
|
|
1258
|
+
touchFile(
|
|
1259
|
+
path.join(tmpDir, 'packages', 'core', 'src', 'modules', 'custom_runtime', 'generators.ts'),
|
|
1260
|
+
`export const generatorPlugins = [{
|
|
1261
|
+
id: 'custom.runtime',
|
|
1262
|
+
bootstrapRegistration: { entriesExportName: 'entries', registrationImports: [], buildCall: () => '' },
|
|
1263
|
+
}]`,
|
|
1264
|
+
)
|
|
1265
|
+
const resolver = createMockResolver(tmpDir, [{ id: 'custom_runtime', from: '@open-mercato/core' }])
|
|
1266
|
+
const result = await generateModuleRegistryCli({ resolver, quiet: true })
|
|
1267
|
+
expect(result.errors).toEqual([])
|
|
1268
|
+
const manifestPath = path.join(tmpDir, 'output', 'generated', 'dev-supervisor.generated.json')
|
|
1269
|
+
expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8')).requiresFullBootstrap).toBe(true)
|
|
1270
|
+
})
|
|
1271
|
+
|
|
1256
1272
|
it('falls back to full bootstrap for worker overrides and computed scheduler commands', async () => {
|
|
1257
1273
|
scaffoldModule(tmpDir, 'events', 'pkg', ['workers/dispatch.ts'])
|
|
1258
1274
|
scaffoldModule(tmpDir, 'scheduler', 'pkg', ['cli.ts'])
|
|
@@ -2092,7 +2108,7 @@ describe('all generated files are valid with varying subsets', () => {
|
|
|
2092
2108
|
await generateModuleRegistry({ resolver: disabledResolver, quiet: true })
|
|
2093
2109
|
expect(fs.existsSync(outputPath)).toBe(false)
|
|
2094
2110
|
expect(fs.existsSync(checksumPath)).toBe(false)
|
|
2095
|
-
expect(fs.
|
|
2111
|
+
expect(JSON.parse(fs.readFileSync(manifestPath, 'utf8'))).toEqual(['database-declarations.generated.ts'])
|
|
2096
2112
|
})
|
|
2097
2113
|
|
|
2098
2114
|
it('notifications.generated.ts uses typed fallback for legacy "types" export', async () => {
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { GeneratorPlugin } from '@open-mercato/shared/modules/generators'
|
|
2
|
+
|
|
3
|
+
export const databaseDeclarationsPlugin: GeneratorPlugin = {
|
|
4
|
+
id: 'database.declarations',
|
|
5
|
+
conventionFile: 'database.ts',
|
|
6
|
+
importPrefix: 'DATABASE_DECLARATIONS',
|
|
7
|
+
configExpr: (name, moduleId) => `{ moduleId: '${moduleId}', declarations: ${name}.databaseDeclarations }`,
|
|
8
|
+
outputFileName: 'database-declarations.generated.ts',
|
|
9
|
+
buildOutput: ({ importSection, entriesLiteral }) => `// AUTO-GENERATED by mercato generate registry
|
|
10
|
+
import type { DatabaseModuleDeclarationEntry } from '@open-mercato/shared/lib/db/declarations'
|
|
11
|
+
${importSection}
|
|
12
|
+
export const databaseModuleDeclarations: DatabaseModuleDeclarationEntry[] = [${entriesLiteral}]
|
|
13
|
+
`,
|
|
14
|
+
bootstrapRegistration: {
|
|
15
|
+
entriesExportName: 'databaseModuleDeclarations',
|
|
16
|
+
registrationImports: ["import { registerDatabaseModuleDeclarations } from '@open-mercato/shared/lib/db/declarations'"],
|
|
17
|
+
buildCall: (name) => `registerDatabaseModuleDeclarations(${name})`,
|
|
18
|
+
},
|
|
19
|
+
}
|
|
@@ -80,6 +80,7 @@ import {
|
|
|
80
80
|
resolveStandaloneSourceMirrorBase,
|
|
81
81
|
} from './scanner'
|
|
82
82
|
import { loadGeneratorExtensions } from './extensions'
|
|
83
|
+
import { databaseDeclarationsPlugin } from './database-declarations'
|
|
83
84
|
import { resolveDashboardWidgetKey } from './extensions/dashboard-widgets'
|
|
84
85
|
import { prepareCrudFormSectionRegistries, writeCrudFormSectionRegistries, writeDerivedCrudFormSectionRoutes } from './form-sections'
|
|
85
86
|
import type { ModuleScanContext, StandaloneConfigOptions } from './extension'
|
|
@@ -3784,9 +3785,13 @@ async function generateModuleRegistryFromDiscovery(options: ModuleRegistryRender
|
|
|
3784
3785
|
const enabled = discovery.enabled
|
|
3785
3786
|
const extensions = loadGeneratorExtensions(resolver)
|
|
3786
3787
|
|
|
3787
|
-
// Pre-pass: collect
|
|
3788
|
-
const pluginRegistry = new Map<string, import('@open-mercato/shared/modules/generators').GeneratorPlugin>(
|
|
3789
|
-
|
|
3788
|
+
// Pre-pass: register the built-in plugin and collect plugins from enabled modules.
|
|
3789
|
+
const pluginRegistry = new Map<string, import('@open-mercato/shared/modules/generators').GeneratorPlugin>([
|
|
3790
|
+
[databaseDeclarationsPlugin.id, databaseDeclarationsPlugin],
|
|
3791
|
+
])
|
|
3792
|
+
const pluginState = new Map<string, { imports: string[]; configs: string[] }>([
|
|
3793
|
+
[databaseDeclarationsPlugin.id, { imports: [], configs: [] }],
|
|
3794
|
+
])
|
|
3790
3795
|
for (const discovered of discovery.modules) {
|
|
3791
3796
|
const resolved = discovered.resolve('generators.ts')
|
|
3792
3797
|
if (!resolved) continue
|
|
@@ -4968,7 +4973,8 @@ async function generateModuleRegistryCliFromDiscovery(options: ModuleRegistryRen
|
|
|
4968
4973
|
const devSupervisorWorkers: DevSupervisorWorkerDescriptor[] = []
|
|
4969
4974
|
let schedulerStartStatus: DevSupervisorSchedulerStartStatus = 'missing-module'
|
|
4970
4975
|
let requiresFullBootstrap = selectsRegistryOutput(options, 'supervisor') && (
|
|
4971
|
-
|
|
4976
|
+
discovery.modules.some((module) => Boolean(module.resolve(databaseDeclarationsPlugin.conventionFile)))
|
|
4977
|
+
|| enabled.some((entry) => entry.devSupervisorRequiresFullBootstrap === true)
|
|
4972
4978
|
|| appDeclaresProgrammaticDevSupervisorOverrides(resolver.getAppDir())
|
|
4973
4979
|
)
|
|
4974
4980
|
|
|
@@ -4976,6 +4982,19 @@ async function generateModuleRegistryCliFromDiscovery(options: ModuleRegistryRen
|
|
|
4976
4982
|
const { modId, imps, appImportBase } = discovered
|
|
4977
4983
|
commandLoaderEntries.push(...discovered.commandLoaderEntries)
|
|
4978
4984
|
|
|
4985
|
+
const generatorSource = discovered.resolve('generators.ts')
|
|
4986
|
+
if (generatorSource) {
|
|
4987
|
+
assertGeneratorPluginUsesTypeOnlyImports(generatorSource.absolutePath)
|
|
4988
|
+
try {
|
|
4989
|
+
const pluginModule = await import(buildCacheBustedSourceImportUrl(generatorSource.absolutePath))
|
|
4990
|
+
const plugins: import('@open-mercato/shared/modules/generators').GeneratorPlugin[] =
|
|
4991
|
+
pluginModule.generatorPlugins ?? pluginModule.default ?? []
|
|
4992
|
+
requiresFullBootstrap ||= plugins.some((plugin) => Boolean(plugin.bootstrapRegistration))
|
|
4993
|
+
} catch {
|
|
4994
|
+
requiresFullBootstrap = true
|
|
4995
|
+
}
|
|
4996
|
+
}
|
|
4997
|
+
|
|
4979
4998
|
let cliImportName: string | null = null
|
|
4980
4999
|
const translations: GeneratedObjectEntry[] = []
|
|
4981
5000
|
const subscribers: WriterFunction[] = []
|