@open-mercato/cli 0.10.1-develop.8227.1.33f80330f2 → 0.10.1-develop.8230.1.29770a5cd8

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 (101) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/agentic/guides/module-facts.json +162 -162
  3. package/dist/agentic/guides/module-facts.v2.json +162 -162
  4. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  5. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  6. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  7. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  8. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  9. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  10. package/dist/agentic/guides/modules/auth/index.md +1 -1
  11. package/dist/agentic/guides/modules/availability/index.md +1 -1
  12. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  13. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  14. package/dist/agentic/guides/modules/cart/index.md +1 -1
  15. package/dist/agentic/guides/modules/catalog/index.md +1 -1
  16. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  17. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  18. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  19. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  20. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  21. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  22. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  23. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  24. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  25. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  26. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  27. package/dist/agentic/guides/modules/configs/index.md +1 -1
  28. package/dist/agentic/guides/modules/content/index.md +1 -1
  29. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  30. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  31. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  32. package/dist/agentic/guides/modules/customers/index.md +1 -1
  33. package/dist/agentic/guides/modules/dashboards/index.md +1 -1
  34. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  35. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  36. package/dist/agentic/guides/modules/devices/index.md +1 -1
  37. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  38. package/dist/agentic/guides/modules/directory/index.md +1 -1
  39. package/dist/agentic/guides/modules/documents/index.md +1 -1
  40. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  41. package/dist/agentic/guides/modules/entities/index.md +1 -1
  42. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  43. package/dist/agentic/guides/modules/events/index.md +1 -1
  44. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  45. package/dist/agentic/guides/modules/forms/index.md +1 -1
  46. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  47. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  48. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  49. package/dist/agentic/guides/modules/generators/index.md +1 -1
  50. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  51. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  52. package/dist/agentic/guides/modules/messages/index.md +1 -1
  53. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  54. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  55. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  56. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  57. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  58. package/dist/agentic/guides/modules/planner/index.md +1 -1
  59. package/dist/agentic/guides/modules/portal/index.md +1 -1
  60. package/dist/agentic/guides/modules/progress/index.md +1 -1
  61. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  62. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  63. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  64. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  65. package/dist/agentic/guides/modules/resources/index.md +1 -1
  66. package/dist/agentic/guides/modules/sales/index.md +1 -1
  67. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  68. package/dist/agentic/guides/modules/search/index.md +1 -1
  69. package/dist/agentic/guides/modules/security/index.md +1 -1
  70. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  71. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  72. package/dist/agentic/guides/modules/sso/index.md +1 -1
  73. package/dist/agentic/guides/modules/staff/index.md +1 -1
  74. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  75. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  76. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  77. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  78. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  79. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  80. package/dist/agentic/guides/modules/translations/index.md +1 -1
  81. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  82. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  83. package/dist/agentic/guides/modules/wms/index.md +1 -1
  84. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  85. package/dist/agentic/guides/reference-module-facts.json +1 -1
  86. package/dist/agentic/guides/upstream/BACKWARD_COMPATIBILITY.md +4 -0
  87. package/dist/agentic/guides/upstream/manifest.json +2 -2
  88. package/dist/lib/generate-child-process.js +23 -0
  89. package/dist/lib/generate-child-process.js.map +7 -0
  90. package/dist/lib/in-process-generate-watcher.js +11 -5
  91. package/dist/lib/in-process-generate-watcher.js.map +2 -2
  92. package/dist/mercato.js +39 -22
  93. package/dist/mercato.js.map +3 -3
  94. package/package.json +7 -7
  95. package/src/__tests__/mercato.test.ts +12 -0
  96. package/src/lib/__tests__/generate-child-process.test.ts +185 -0
  97. package/src/lib/__tests__/generate-quiet-entrypoint.test.ts +47 -0
  98. package/src/lib/__tests__/in-process-generate-watcher.test.ts +91 -0
  99. package/src/lib/generate-child-process.ts +35 -0
  100. package/src/lib/in-process-generate-watcher.ts +14 -6
  101. package/src/mercato.ts +45 -31
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/cli",
3
- "version": "0.10.1-develop.8227.1.33f80330f2",
3
+ "version": "0.10.1-develop.8230.1.29770a5cd8",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -60,10 +60,10 @@
60
60
  "@mikro-orm/decorators": "^7.1.14",
61
61
  "@mikro-orm/migrations": "^7.1.14",
62
62
  "@mikro-orm/postgresql": "^7.1.14",
63
- "@open-mercato/events": "0.10.1-develop.8227.1.33f80330f2",
64
- "@open-mercato/queue": "0.10.1-develop.8227.1.33f80330f2",
65
- "@open-mercato/shared": "0.10.1-develop.8227.1.33f80330f2",
66
- "@open-mercato/telemetry": "0.10.1-develop.8227.1.33f80330f2",
63
+ "@open-mercato/events": "0.10.1-develop.8230.1.29770a5cd8",
64
+ "@open-mercato/queue": "0.10.1-develop.8230.1.29770a5cd8",
65
+ "@open-mercato/shared": "0.10.1-develop.8230.1.29770a5cd8",
66
+ "@open-mercato/telemetry": "0.10.1-develop.8230.1.29770a5cd8",
67
67
  "cross-spawn": "^7.0.6",
68
68
  "minisearch": "7.2.0",
69
69
  "pg": "8.23.0",
@@ -75,10 +75,10 @@
75
75
  "typescript-js": "npm:typescript@6.0.3"
76
76
  },
77
77
  "peerDependencies": {
78
- "@open-mercato/shared": "0.10.1-develop.8227.1.33f80330f2"
78
+ "@open-mercato/shared": "0.10.1-develop.8230.1.29770a5cd8"
79
79
  },
80
80
  "devDependencies": {
81
- "@open-mercato/shared": "0.10.1-develop.8227.1.33f80330f2",
81
+ "@open-mercato/shared": "0.10.1-develop.8230.1.29770a5cd8",
82
82
  "@types/jest": "^30.0.0",
83
83
  "jest": "^30.4.2",
84
84
  "ts-jest": "^29.4.12"
@@ -311,6 +311,18 @@ describe('--help never triggers side effects (issue #5581)', () => {
311
311
  })
312
312
  })
313
313
 
314
+ it.each(['--quiet', '-q'])('silences generation environment loading for %s only', (flag) => {
315
+ expect(resolveEnvBootstrapOptions(['generate', 'all', flag])).toEqual({
316
+ createIfMissing: true,
317
+ quiet: true,
318
+ })
319
+ expect(resolveEnvBootstrapOptions(['db', 'generate', flag])).toEqual({
320
+ createIfMissing: true,
321
+ quiet: false,
322
+ })
323
+ expect(resolveEnvBootstrapOptions(['generate', 'all']).quiet).toBe(false)
324
+ })
325
+
314
326
  it('keeps module search and module info read-only and quiet, so --json output parses', () => {
315
327
  expect(resolveEnvBootstrapOptions(['module', 'search', 'ksef', '--json'])).toEqual({
316
328
  createIfMissing: false,
@@ -0,0 +1,185 @@
1
+ import fs from 'node:fs'
2
+ import os from 'node:os'
3
+ import path from 'node:path'
4
+ import { pathToFileURL } from 'node:url'
5
+ import { runGenerateChildProcess } from '../generate-child-process'
6
+
7
+ let directory: string
8
+
9
+ function write(relativePath: string, contents: string): string {
10
+ const file = path.join(directory, relativePath)
11
+ fs.mkdirSync(path.dirname(file), { recursive: true })
12
+ fs.writeFileSync(file, contents)
13
+ return file
14
+ }
15
+
16
+ function readResult() {
17
+ return JSON.parse(fs.readFileSync(path.join(directory, 'result.json'), 'utf8'))
18
+ }
19
+
20
+ beforeEach(() => {
21
+ directory = fs.mkdtempSync(path.join(os.tmpdir(), 'generate-child-'))
22
+ })
23
+
24
+ afterEach(() => {
25
+ fs.rmSync(directory, { recursive: true, force: true })
26
+ })
27
+
28
+ it('releases the evaluation realm after every changed and unchanged edit cycle', async () => {
29
+ const binary = write('generate.mjs', `
30
+ import fs from 'node:fs'
31
+ import { metadata } from './reexport.mjs'
32
+ fs.writeFileSync('result.json', JSON.stringify({
33
+ pid: process.pid, cwd: process.cwd(), args: process.argv.slice(2),
34
+ marker: process.env.GENERATION_MARKER, evaluations: globalThis.__generatorEvaluations,
35
+ metadata: { ...metadata, onJobAbandoned: await metadata.onJobAbandoned() },
36
+ }))
37
+ `)
38
+ write('reexport.mjs', `export { metadata } from './metadata.mjs'`)
39
+ write('metadata.mjs', `
40
+ import { revision } from './dependency.mjs'
41
+ globalThis.__generatorEvaluations = (globalThis.__generatorEvaluations ?? 0) + 1
42
+ export const metadata = {
43
+ GET: { requireAuth: true }, queue: 'jobs-' + revision,
44
+ onJobAbandoned: async () => revision,
45
+ }
46
+ metadata.GET.requireFeatures = ['feature-' + revision]
47
+ `)
48
+ for (let revision = 0; revision < 20; revision += 1) {
49
+ // Only the dependency changes: a root-only cache bust would miss this edit.
50
+ write('dependency.mjs', `export const revision = ${revision}`)
51
+ await runGenerateChildProcess({
52
+ mercatoBin: binary,
53
+ cwd: directory,
54
+ env: { ...process.env, GENERATION_MARKER: 'inherited' },
55
+ quiet: true,
56
+ })
57
+ expect(readResult()).toMatchObject({
58
+ cwd: fs.realpathSync(directory), args: ['generate', 'all', '--quiet'],
59
+ marker: 'inherited', evaluations: 1,
60
+ metadata: {
61
+ GET: { requireAuth: true, requireFeatures: [`feature-${revision}`] },
62
+ queue: `jobs-${revision}`, onJobAbandoned: revision,
63
+ },
64
+ })
65
+ expect(readResult().pid).not.toBe(process.pid)
66
+ }
67
+ const before = readResult()
68
+ await runGenerateChildProcess({
69
+ mercatoBin: binary, cwd: directory,
70
+ env: { ...process.env, GENERATION_MARKER: 'inherited' }, quiet: true,
71
+ })
72
+ expect(readResult().metadata).toEqual(before.metadata)
73
+ expect(readResult().evaluations).toBe(1)
74
+ expect((globalThis as Record<string, unknown>).__generatorEvaluations).toBeUndefined()
75
+ }, 30_000)
76
+
77
+ it('propagates nonzero exits and allows a subsequent corrected invocation', async () => {
78
+ const binary = write('generate.mjs', 'process.exit(7)')
79
+ await expect(runGenerateChildProcess({ mercatoBin: binary, cwd: directory }))
80
+ .rejects.toThrow('Generator process exited with code 7')
81
+ write('generate.mjs', 'process.exit(0)')
82
+ await expect(runGenerateChildProcess({ mercatoBin: binary, cwd: directory })).resolves.toBeUndefined()
83
+ })
84
+
85
+ it('propagates spawn failures', async () => {
86
+ const binary = write('generate.mjs', '')
87
+ await expect(runGenerateChildProcess({ mercatoBin: binary, cwd: path.join(directory, 'missing') }))
88
+ .rejects.toMatchObject({ code: 'ENOENT' })
89
+ })
90
+
91
+ it('propagates signal termination', async () => {
92
+ const binary = write('generate.mjs', `process.kill(process.pid, 'SIGTERM')`)
93
+ await expect(runGenerateChildProcess({ mercatoBin: binary, cwd: directory }))
94
+ .rejects.toThrow('Generator process terminated by SIGTERM')
95
+ })
96
+
97
+ it('preserves real generated metadata, callbacks and plugins across dependency edits', async () => {
98
+ // Use a native loader so this exercises real ESM evaluation rather than Jest's
99
+ // CommonJS transformation or the static-extraction fallback.
100
+ const cliRoot = path.resolve(__dirname, '../../..')
101
+ fs.symlinkSync(path.resolve(cliRoot, '../../node_modules'), path.join(directory, 'node_modules'), 'junction')
102
+ write('package.json', '{"type":"module"}')
103
+ write('src/modules/probe/index.js', `export const metadata = { name: 'Probe' }`)
104
+ write('src/modules/probe/api/items/route.js', `
105
+ import { metadata } from '../../lib/policy.js'
106
+ metadata.GET.requireRoles = ['manager']
107
+ export { metadata }
108
+ export async function GET() { return new Response('ok') }
109
+ `)
110
+ write('src/modules/probe/subscribers/event.js', `
111
+ import { revision } from '../lib/policy.js'
112
+ export const metadata = { event: 'probe.' + revision, persistent: true }
113
+ export default async function handler() { return revision }
114
+ `)
115
+ write('src/modules/probe/workers/job.js', `
116
+ export { workerMetadata as metadata } from '../lib/policy.js'
117
+ export default async function handler() {}
118
+ `)
119
+ write('src/modules/probe/probe.items.ts', 'export const items = []')
120
+ write('src/modules/probe/generators.ts', `
121
+ export const generatorPlugins = [{
122
+ id: 'probe.output', conventionFile: 'probe.items.ts', importPrefix: 'PROBE',
123
+ outputFileName: 'probe.generated.ts', configExpr: () => '{}',
124
+ buildOutput: () => 'export const value = ' + JSON.stringify(process.env.PROBE_VALUE) + '\\n',
125
+ }]
126
+ `)
127
+ const binary = write('generate.mjs', `
128
+ import fs from 'node:fs'
129
+ import path from 'node:path'
130
+ import { pathToFileURL } from 'node:url'
131
+ const { generateModuleRegistries } = await import(process.env.GENERATOR_SOURCE)
132
+ const root = process.cwd()
133
+ const output = path.join(root, '.mercato/generated')
134
+ const resolver = {
135
+ isMonorepo: () => false, getRootDir: () => root, getAppDir: () => root,
136
+ getOutputDir: () => output, getModulesConfigPath: () => path.join(root, 'src/modules.ts'),
137
+ discoverPackages: () => [], loadEnabledModules: () => [{ id: 'probe', from: '@app' }],
138
+ getModulePaths: () => ({ appBase: path.join(root, 'src/modules/probe'), pkgBase: '' }),
139
+ getModuleImportBase: () => ({ appBase: '@/modules/probe', pkgBase: '' }),
140
+ getPackageOutputDir: () => output, getPackageRoot: () => root,
141
+ }
142
+ await generateModuleRegistries({ resolver, quiet: true })
143
+ const { modules: runtimeModules } = await import(pathToFileURL(path.join(output, 'modules.runtime.generated.ts')).href)
144
+ const routes = runtimeModules[0].apis
145
+ const { modules } = await import(pathToFileURL(path.join(output, 'modules.cli.generated.ts')).href)
146
+ const { value: pluginValue } = await import(pathToFileURL(path.join(output, 'probe.generated.ts')).href)
147
+ const worker = modules[0].workers[0]
148
+ await worker.onJobAbandoned({ id: 'payload' }, { jobId: 'job', reason: 'expired' })
149
+ fs.writeFileSync('result.json', JSON.stringify({
150
+ routes, pluginValue, event: modules[0].subscribers[0].event,
151
+ worker: { queue: worker.queue, concurrency: worker.concurrency,
152
+ abandoned: globalThis.__abandoned },
153
+ }))
154
+ `)
155
+ const env = {
156
+ ...process.env,
157
+ NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=${pathToFileURL(require.resolve('tsx')).href}`,
158
+ GENERATOR_SOURCE: pathToFileURL(path.join(cliRoot, 'src/lib/generators/module-registry.ts')).href,
159
+ }
160
+ for (const revision of [1, 1, 2]) {
161
+ write('src/modules/probe/lib/policy.js', `
162
+ export const revision = ${revision}
163
+ export const metadata = { GET: { requireAuth: true, requireFeatures: ['probe.' + revision] } }
164
+ export const workerMetadata = {
165
+ queue: 'probe-' + revision, concurrency: revision,
166
+ onJobAbandoned: async (payload, info) => { globalThis.__abandoned = { revision, payload, info } },
167
+ }
168
+ `)
169
+ await runGenerateChildProcess({ mercatoBin: binary, cwd: directory, env: { ...env, PROBE_VALUE: String(revision) }, quiet: true })
170
+ const result = readResult()
171
+ expect(result.pluginValue).toBe(String(revision))
172
+ expect(result.event).toBe(`probe.${revision}`)
173
+ expect(result.worker).toEqual({
174
+ queue: `probe-${revision}`, concurrency: revision,
175
+ abandoned: { revision, payload: { id: 'payload' }, info: { jobId: 'job', reason: 'expired' } },
176
+ })
177
+ expect(result.routes).toEqual(expect.arrayContaining([
178
+ expect.objectContaining({
179
+ metadata: expect.objectContaining({
180
+ GET: { requireAuth: true, requireFeatures: [`probe.${revision}`], requireRoles: ['manager'] },
181
+ }),
182
+ }),
183
+ ]))
184
+ }
185
+ }, 120_000)
@@ -0,0 +1,47 @@
1
+ import { execFile } from 'node:child_process'
2
+ import fs from 'node:fs'
3
+ import os from 'node:os'
4
+ import path from 'node:path'
5
+ import { promisify } from 'node:util'
6
+
7
+ const execute = promisify(execFile)
8
+
9
+ it('keeps quiet generation stdout empty without hiding diagnostics at the CLI entrypoint', async () => {
10
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'generate-quiet-'))
11
+ const cliRoot = path.resolve(__dirname, '../../..')
12
+ const coreRoot = path.join(directory, 'node_modules/@open-mercato/core')
13
+ const moduleRoot = path.join(directory, 'src/modules/probe')
14
+ const env = { ...process.env }
15
+ delete env.OM_CLI_QUIET
16
+ delete env.DOTENV_CONFIG_QUIET
17
+ try {
18
+ // A real directory, not the workspace core symlink: the production resolver
19
+ // must identify this as a standalone app and never generate into the repo.
20
+ fs.mkdirSync(path.join(coreRoot, 'dist/modules'), { recursive: true })
21
+ fs.writeFileSync(path.join(coreRoot, 'package.json'), JSON.stringify({
22
+ name: '@open-mercato/core', version: '0.0.0', type: 'module',
23
+ }))
24
+ fs.writeFileSync(path.join(directory, 'package.json'), JSON.stringify({ name: 'quiet-generation-fixture', type: 'module' }))
25
+ fs.writeFileSync(path.join(directory, '.env'), 'GENERATOR_QUIET_FIXTURE=loaded\n')
26
+ fs.mkdirSync(path.join(moduleRoot, 'api/items'), { recursive: true })
27
+ fs.writeFileSync(path.join(directory, 'src/modules.ts'), `export const enabledModules = [{ id: 'probe', from: '@app' }]`)
28
+ fs.writeFileSync(path.join(moduleRoot, 'index.js'), `export const metadata = { name: 'Probe' }`)
29
+ // Missing route metadata is a real generator warning, not a logging mock.
30
+ fs.writeFileSync(path.join(moduleRoot, 'api/items/route.js'), `export async function GET() { return new Response('ok') }`)
31
+
32
+ const args = ['--import', require.resolve('tsx'), path.join(cliRoot, 'src/bin.ts'), 'generate', 'all']
33
+ const options = { cwd: directory, env, encoding: 'utf8' as const, maxBuffer: 4 * 1024 * 1024 }
34
+ const quiet = await execute(process.execPath, [...args, '--quiet'], options)
35
+ expect(quiet.stdout.trim()).toBe('')
36
+ expect(quiet.stderr).toContain(fs.realpathSync(path.join(moduleRoot, 'api/items/route.js')))
37
+
38
+ fs.writeFileSync(path.join(moduleRoot, 'index.js'), `export const metadata = { requires: ['missing_dependency'] }`)
39
+ await expect(execute(process.execPath, [...args, '-q'], options)).rejects.toMatchObject({
40
+ code: 1,
41
+ stdout: '',
42
+ stderr: expect.stringContaining('missing_dependency'),
43
+ })
44
+ } finally {
45
+ fs.rmSync(directory, { recursive: true, force: true })
46
+ }
47
+ }, 120_000)
@@ -411,6 +411,97 @@ describe('startInProcessGenerateWatcher', () => {
411
411
  await handle.done
412
412
  })
413
413
 
414
+ it.each([false, true])('drains an active generation on close (skipInitial=%s)', async (skipInitial) => {
415
+ let release!: () => void
416
+ let checksum = 'before'
417
+ const runGenerators = jest.fn(() => new Promise<void>((resolve) => { release = resolve }))
418
+ const { signal, markChanged } = createFakeChangeSignal()
419
+ const handle = startInProcessGenerateWatcher({
420
+ skipInitial,
421
+ quiet: true,
422
+ logger: silentLogger,
423
+ changeSignal: signal,
424
+ computeStructureChecksum: async () => checksum,
425
+ runGenerators,
426
+ })
427
+ await flushAsync(8)
428
+ if (skipInitial) {
429
+ checksum = 'after'
430
+ markChanged()
431
+ jest.advanceTimersByTime(1000)
432
+ await flushAsync(8)
433
+ }
434
+ expect(runGenerators).toHaveBeenCalledTimes(1)
435
+
436
+ const closed = jest.fn()
437
+ const closing = handle.close().then(closed)
438
+ const secondClose = handle.close()
439
+ void handle.done.then(closed)
440
+ await flushAsync(8)
441
+ expect(closed).not.toHaveBeenCalled()
442
+ expect(signal.close).not.toHaveBeenCalled()
443
+
444
+ markChanged()
445
+ release()
446
+ await closing
447
+ await secondClose
448
+ await handle.done
449
+ jest.advanceTimersByTime(5000)
450
+ await flushAsync(8)
451
+ expect(runGenerators).toHaveBeenCalledTimes(1)
452
+ expect(signal.close).toHaveBeenCalledTimes(1)
453
+ expect(closed).toHaveBeenCalledTimes(2)
454
+ })
455
+
456
+ it('does not launch generation when shutdown overtakes a checksum capture', async () => {
457
+ let release!: (checksum: string) => void
458
+ const computeStructureChecksum = jest.fn()
459
+ .mockResolvedValueOnce('before')
460
+ .mockImplementationOnce(() => new Promise<string>((resolve) => { release = resolve }))
461
+ const runGenerators = jest.fn(async () => undefined)
462
+ const handle = startInProcessGenerateWatcher({
463
+ skipInitial: true,
464
+ quiet: true,
465
+ computeStructureChecksum,
466
+ runGenerators,
467
+ })
468
+ await flushAsync(8)
469
+ jest.advanceTimersByTime(1000)
470
+ await flushAsync(8)
471
+ const closing = handle.close()
472
+ release('after')
473
+ await closing
474
+ expect(runGenerators).not.toHaveBeenCalled()
475
+ })
476
+
477
+ it('recovers on a later edit after the generator child fails', async () => {
478
+ let checksum = 'before'
479
+ const { signal, markChanged } = createFakeChangeSignal()
480
+ const runGenerators = jest.fn()
481
+ .mockRejectedValueOnce(new Error('Generator process exited with code 1'))
482
+ .mockResolvedValue(undefined)
483
+ const handle = startInProcessGenerateWatcher({
484
+ skipInitial: true,
485
+ quiet: true,
486
+ logger: silentLogger,
487
+ changeSignal: signal,
488
+ computeStructureChecksum: async () => checksum,
489
+ runGenerators,
490
+ })
491
+ await flushAsync(8)
492
+ for (const value of ['broken', 'fixed']) {
493
+ checksum = value
494
+ markChanged()
495
+ jest.advanceTimersByTime(1000)
496
+ await flushAsync(12)
497
+ }
498
+ expect(runGenerators).toHaveBeenCalledTimes(2)
499
+ expect(silentLogger.error).toHaveBeenCalledWith(
500
+ '[generate:watch] Generation failed: Generator process exited with code 1',
501
+ )
502
+ await handle.close()
503
+ })
504
+
414
505
  it('close() is idempotent and resolves done exactly once', async () => {
415
506
  const runGenerators = jest.fn(async () => undefined)
416
507
  const computeStructureChecksum = jest.fn(async () => 'k')
@@ -0,0 +1,35 @@
1
+ import { spawn } from 'node:child_process'
2
+
3
+ /**
4
+ * Evaluate application modules in a disposable process, never in the watcher.
5
+ * Native ESM keeps every cache-busted module revision until its process exits;
6
+ * a fresh process also observes edits to unchanged modules' imported dependencies.
7
+ */
8
+ export async function runGenerateChildProcess(options: {
9
+ mercatoBin: string
10
+ cwd: string
11
+ env?: NodeJS.ProcessEnv
12
+ quiet?: boolean
13
+ }): Promise<void> {
14
+ const args = [options.mercatoBin, 'generate', 'all']
15
+ if (options.quiet) args.push('--quiet')
16
+
17
+ await new Promise<void>((resolve, reject) => {
18
+ const child = spawn(process.execPath, args, {
19
+ cwd: options.cwd,
20
+ env: options.env ?? process.env,
21
+ stdio: ['ignore', 'inherit', 'inherit'],
22
+ })
23
+ child.once('error', reject)
24
+ // Wait for close, not just exit: generation and inherited stream cleanup
25
+ // must finish before another cycle or supervisor restart can proceed.
26
+ child.once('close', (code, signal) => {
27
+ if (code === 0) resolve()
28
+ else reject(new Error(
29
+ signal
30
+ ? `Generator process terminated by ${signal}`
31
+ : `Generator process exited with code ${code ?? 'unknown'}`,
32
+ ))
33
+ })
34
+ })
35
+ }
@@ -60,7 +60,7 @@ export type GenerateWatcherOptions = {
60
60
  export type GenerateWatcherHandle = {
61
61
  /** Resolves when the watcher loop has stopped (after `close()`). */
62
62
  readonly done: Promise<void>
63
- /** Stop the polling loop and resolve `done`. Idempotent. */
63
+ /** Stop polling, drain the active cycle, and resolve `done`. Idempotent. */
64
64
  close(): Promise<void>
65
65
  }
66
66
 
@@ -89,6 +89,7 @@ export function startInProcessGenerateWatcher(
89
89
 
90
90
  let stopping = false
91
91
  let pollTimer: ReturnType<typeof setTimeout> | null = null
92
+ let activeCycle: Promise<void> | null = null
92
93
  let running = false
93
94
  let pendingReason: string | null = null
94
95
  let previousChecksum = ''
@@ -99,6 +100,7 @@ export function startInProcessGenerateWatcher(
99
100
  })
100
101
 
101
102
  async function runOnce(reason: string): Promise<void> {
103
+ if (stopping) return
102
104
  if (running) {
103
105
  pendingReason = reason
104
106
  return
@@ -128,7 +130,7 @@ export function startInProcessGenerateWatcher(
128
130
  function scheduleNext(): void {
129
131
  if (stopping) return
130
132
  pollTimer = setTimeout(() => {
131
- void (async () => {
133
+ activeCycle = (async () => {
132
134
  if (stopping) return
133
135
  try {
134
136
  const changeVersion = changeSignal?.currentVersion() ?? 0
@@ -164,13 +166,15 @@ export function startInProcessGenerateWatcher(
164
166
  pollTimer.unref?.()
165
167
  }
166
168
 
167
- void (async () => {
169
+ activeCycle = (async () => {
168
170
  try {
169
171
  await changeSignal?.refresh()
172
+ if (stopping) return
170
173
  const initialChangeVersion = changeSignal?.currentVersion() ?? 0
171
174
  if (!skipInitial) {
172
175
  await runOnce('initial')
173
176
  }
177
+ if (stopping) return
174
178
  previousChecksum = await computeStructureChecksum()
175
179
  observedChangeVersion = initialChangeVersion
176
180
  if (!quiet) {
@@ -199,9 +203,13 @@ export function startInProcessGenerateWatcher(
199
203
  clearTimeout(pollTimer)
200
204
  pollTimer = null
201
205
  }
202
- await changeSignal?.close()
203
- if (doneResolve) {
204
- doneResolve()
206
+ // Drain before closing subscriptions: an in-flight capture can refresh
207
+ // them, and a generator child must exit before dev restarts its group.
208
+ try {
209
+ await activeCycle
210
+ await changeSignal?.close()
211
+ } finally {
212
+ doneResolve?.()
205
213
  doneResolve = null
206
214
  }
207
215
  }
package/src/mercato.ts CHANGED
@@ -36,6 +36,7 @@ import {
36
36
  startInProcessGenerateWatcher,
37
37
  type GenerateWatcherHandle,
38
38
  } from './lib/in-process-generate-watcher'
39
+ import { runGenerateChildProcess } from './lib/generate-child-process'
39
40
  import {
40
41
  resolveGenerateWatcherMode,
41
42
  type GenerateWatcherMode,
@@ -381,10 +382,19 @@ async function ensureEnvLoaded(options: { createIfMissing?: boolean; quiet?: boo
381
382
  // Resolver might fail during early init, fall back to default behavior
382
383
  }
383
384
 
384
- // Fall back to default dotenv behavior (loads from cwd)
385
+ // Preserve dotenv/config's environment/argv options in the cwd fallback.
386
+ const previousDotenvQuiet = process.env.DOTENV_CONFIG_QUIET
385
387
  try {
388
+ if (quietDotenv) process.env.DOTENV_CONFIG_QUIET = 'true'
386
389
  await import('dotenv/config')
387
- } catch {}
390
+ } catch {
391
+ // Environment loading remains best effort.
392
+ } finally {
393
+ if (quietDotenv) {
394
+ if (previousDotenvQuiet === undefined) delete process.env.DOTENV_CONFIG_QUIET
395
+ else process.env.DOTENV_CONFIG_QUIET = previousDotenvQuiet
396
+ }
397
+ }
388
398
  }
389
399
 
390
400
  function resolveInstalledBinary(baseDirs: string[], relativeBinPath: string): string {
@@ -833,12 +843,7 @@ async function runPostGenerateStructuralInvalidation(quiet: boolean): Promise<vo
833
843
  }
834
844
  }
835
845
 
836
- /**
837
- * Generator suite invoked by both `mercato generate all` and the in-process
838
- * generate watcher embedded in `mercato server dev`. Hoisted to module scope
839
- * so the watcher embedded in the server lifecycle can reuse the same closure
840
- * without re-importing the closure-scoped version inside `buildBaseModules`.
841
- */
846
+ /** Full one-shot suite; long-lived watchers invoke this in a disposable CLI process. */
842
847
  async function runGeneratorSuite(quiet: boolean): Promise<boolean> {
843
848
  const { createResolver } = await import('./lib/resolver')
844
849
  const {
@@ -874,6 +879,17 @@ async function runGeneratorSuiteWithStructuralInvalidation(quiet: boolean): Prom
874
879
  await runPostGenerateStructuralInvalidation(quiet)
875
880
  }
876
881
 
882
+ async function runWatchGeneratorSuite(): Promise<void> {
883
+ // Keep resolver setup behind command dispatch; other CLI modes do not need it.
884
+ const { resolveEnvironment } = await import('./lib/resolver')
885
+ const { rootDir, appDir } = resolveEnvironment()
886
+ await runGenerateChildProcess({
887
+ mercatoBin: resolveInstalledBinary([rootDir, appDir], '@open-mercato/cli/bin/mercato'),
888
+ cwd: process.cwd(),
889
+ quiet: true,
890
+ })
891
+ }
892
+
877
893
  /**
878
894
  * Builds the event-gated structural fingerprint runtime used by generate
879
895
  * watchers. Filesystem events mark the tree dirty; the existing full content
@@ -995,16 +1011,18 @@ export function resolveEnvBootstrapOptions(parts: string[]): { createIfMissing:
995
1011
  const opaqueEnvCommand = first === 'deploy' || first === 'telemetry'
996
1012
  const readOnlyModuleCommand = first === 'module' && (parts[1] === 'search' || parts[1] === 'info')
997
1013
  const jsonOutput = parts.includes('--json')
1014
+ const quietGeneration = first === 'generate' && (parts.includes('--quiet') || parts.includes('-q'))
998
1015
  const helpRequested = isHelpRequest(parts)
999
1016
  return {
1000
1017
  createIfMissing: !helpRequested && !opaqueEnvCommand && !readOnlyModuleCommand,
1001
- quiet: helpRequested || opaqueEnvCommand || readOnlyModuleCommand || jsonOutput,
1018
+ quiet: helpRequested || opaqueEnvCommand || readOnlyModuleCommand || jsonOutput || quietGeneration,
1002
1019
  }
1003
1020
  }
1004
1021
 
1005
1022
  export async function run(argv = process.argv) {
1006
1023
  const [, , ...parts] = argv
1007
1024
  const [first, second, ...remaining] = parts
1025
+ const quietGeneration = first === 'generate' && (parts.includes('--quiet') || parts.includes('-q'))
1008
1026
  // Help must never have side effects: it must not create .env, and must not fall through
1009
1027
  // to the command it is asking about.
1010
1028
  const helpRequested = isHelpRequest(parts)
@@ -2038,9 +2056,9 @@ export async function run(argv = process.argv) {
2038
2056
  run: async (args: string[]) => {
2039
2057
  const quiet = args.includes('--quiet') || args.includes('-q')
2040
2058
 
2041
- console.log('Running all generators...')
2059
+ if (!quiet) console.log('Running all generators...')
2042
2060
  await runGeneratorSuiteWithStructuralInvalidation(quiet)
2043
- console.log('All generators completed.')
2061
+ if (!quiet) console.log('All generators completed.')
2044
2062
  },
2045
2063
  },
2046
2064
  {
@@ -2058,9 +2076,7 @@ export async function run(argv = process.argv) {
2058
2076
  skipInitial,
2059
2077
  quiet,
2060
2078
  ...generateWatchRuntime,
2061
- runGenerators: async () => {
2062
- await runGeneratorSuiteWithStructuralInvalidation(true)
2063
- },
2079
+ runGenerators: runWatchGeneratorSuite,
2064
2080
  })
2065
2081
 
2066
2082
  const shutdownSignals: NodeJS.Signals[] = ['SIGINT', 'SIGTERM']
@@ -2529,12 +2545,10 @@ export async function run(argv = process.argv) {
2529
2545
  })
2530
2546
 
2531
2547
  if (generateWatcherMode === 'in-process') {
2532
- // Run the structural regeneration watcher inside this process
2533
- // instead of spawning a dedicated `mercato generate watch --skip-initial`
2534
- // sidecar. Saves ~190 MB of resident RSS on a typical dev box
2535
- // (measured against the legacy sidecar). Opt back into the
2536
- // sidecar with `OM_DEV_GENERATE_WATCH_MODE=legacy` if needed.
2537
- console.log('[server] In-process generate watcher enabled — structural changes will regenerate without a sidecar process.')
2548
+ // Keep the event watcher here, but evaluate each generation in
2549
+ // a fresh one-shot child so imported module revisions do not
2550
+ // accumulate in this long-lived supervisor.
2551
+ console.log('[server] In-process generate watcher enabled — structural changes regenerate in a one-shot child.')
2538
2552
  const generateWatchRuntime = await createGenerateWatchRuntime()
2539
2553
  activeGenerateWatcher = startInProcessGenerateWatcher({
2540
2554
  // `--skip-initial` equivalent: `yarn dev` always runs an
@@ -2545,9 +2559,7 @@ export async function run(argv = process.argv) {
2545
2559
  skipInitial: true,
2546
2560
  quiet: false,
2547
2561
  ...generateWatchRuntime,
2548
- runGenerators: async () => {
2549
- await runGeneratorSuiteWithStructuralInvalidation(true)
2550
- },
2562
+ runGenerators: runWatchGeneratorSuite,
2551
2563
  })
2552
2564
  } else {
2553
2565
  console.log('[server] Legacy out-of-process generate watcher selected via OM_DEV_GENERATE_WATCH_MODE=legacy — expect the dev orchestrator to spawn `mercato generate watch --skip-initial`.')
@@ -2787,7 +2799,7 @@ export async function run(argv = process.argv) {
2787
2799
 
2788
2800
  if (appCli.length) all.push({ id: 'app', cli: appCli } as any)
2789
2801
 
2790
- const quietBanner = process.env.OM_CLI_QUIET === '1'
2802
+ const quietBanner = process.env.OM_CLI_QUIET === '1' || quietGeneration
2791
2803
  const banner = '🧩 Open Mercato CLI'
2792
2804
  if (!quietBanner) {
2793
2805
  const header = [
@@ -2851,18 +2863,20 @@ export async function run(argv = process.argv) {
2851
2863
  return 0
2852
2864
  }
2853
2865
 
2854
- console.log('')
2866
+ if (!quietGeneration) console.log('')
2855
2867
  const started = Date.now()
2856
- const commandArgs = modName === 'deploy' && cmdName === 'railway'
2857
- ? (await import('./lib/deploy/railway/options')).redactRailwayCliArgs(rest)
2858
- : rest
2859
- const loggedArgs = redactSensitiveModuleCliArgs(commandArgs, `${modName}:${cmdName}`)
2860
- console.log(`🚀 Running ${modName}:${cmdName} ${loggedArgs.join(' ')}`)
2868
+ if (!quietGeneration) {
2869
+ const commandArgs = modName === 'deploy' && cmdName === 'railway'
2870
+ ? (await import('./lib/deploy/railway/options')).redactRailwayCliArgs(rest)
2871
+ : rest
2872
+ const loggedArgs = redactSensitiveModuleCliArgs(commandArgs, `${modName}:${cmdName}`)
2873
+ console.log(`🚀 Running ${modName}:${cmdName} ${loggedArgs.join(' ')}`)
2874
+ }
2861
2875
  try {
2862
2876
  const commandExitCode = await runWithCapturedExitCode(async () => {
2863
2877
  await cmd.run(rest)
2864
2878
  })
2865
- if (modName !== 'deploy' || cmdName !== 'railway') {
2879
+ if (!quietGeneration && (modName !== 'deploy' || cmdName !== 'railway')) {
2866
2880
  const ms = Date.now() - started
2867
2881
  console.log(`⏱️ Done in ${ms}ms`)
2868
2882
  }