@open-mercato/cli 0.10.1-develop.8098.1.f4decc8a57 → 0.10.1-develop.8111.1.6c779bc21b

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 (94) hide show
  1. package/dist/agentic/guides/module-facts.json +169 -169
  2. package/dist/agentic/guides/module-facts.v2.json +169 -169
  3. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  4. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  5. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  6. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  7. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  8. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  9. package/dist/agentic/guides/modules/auth/index.md +1 -1
  10. package/dist/agentic/guides/modules/availability/index.md +1 -1
  11. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  12. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  13. package/dist/agentic/guides/modules/cart/index.md +1 -1
  14. package/dist/agentic/guides/modules/catalog/index.md +1 -1
  15. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  16. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  17. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  18. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  19. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  20. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  21. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  22. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  23. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  24. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  25. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  26. package/dist/agentic/guides/modules/configs/index.md +1 -1
  27. package/dist/agentic/guides/modules/content/index.md +1 -1
  28. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  29. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  30. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  31. package/dist/agentic/guides/modules/customers/index.md +1 -1
  32. package/dist/agentic/guides/modules/dashboards/index.md +1 -1
  33. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  34. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  35. package/dist/agentic/guides/modules/devices/index.md +1 -1
  36. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  37. package/dist/agentic/guides/modules/directory/index.md +1 -1
  38. package/dist/agentic/guides/modules/documents/index.md +1 -1
  39. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  40. package/dist/agentic/guides/modules/entities/index.md +1 -1
  41. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  42. package/dist/agentic/guides/modules/events/index.md +1 -1
  43. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  44. package/dist/agentic/guides/modules/forms/index.md +1 -1
  45. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  46. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  47. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  48. package/dist/agentic/guides/modules/generators/index.md +1 -1
  49. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  50. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  51. package/dist/agentic/guides/modules/messages/index.md +1 -1
  52. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  53. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  54. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  55. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  56. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  57. package/dist/agentic/guides/modules/planner/index.md +1 -1
  58. package/dist/agentic/guides/modules/portal/index.md +1 -1
  59. package/dist/agentic/guides/modules/progress/index.md +1 -1
  60. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  61. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  62. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  63. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  64. package/dist/agentic/guides/modules/resources/index.md +1 -1
  65. package/dist/agentic/guides/modules/sales/index.md +1 -1
  66. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  67. package/dist/agentic/guides/modules/search/index.md +1 -1
  68. package/dist/agentic/guides/modules/security/index.md +1 -1
  69. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  70. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  71. package/dist/agentic/guides/modules/sso/index.md +1 -1
  72. package/dist/agentic/guides/modules/staff/index.md +1 -1
  73. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  74. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  75. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  76. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  77. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  78. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  79. package/dist/agentic/guides/modules/translations/index.md +1 -1
  80. package/dist/agentic/guides/modules/warranty_claims/exact-override-targets.md +5 -5
  81. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  82. package/dist/agentic/guides/modules/warranty_claims/setup.md +1 -1
  83. package/dist/agentic/guides/modules/warranty_claims/workers.md +1 -1
  84. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  85. package/dist/agentic/guides/modules/wms/index.md +1 -1
  86. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  87. package/dist/agentic/guides/reference-module-facts.json +1 -1
  88. package/dist/agentic/guides/upstream/manifest.json +1 -1
  89. package/dist/lib/generators/module-registry.js +133 -72
  90. package/dist/lib/generators/module-registry.js.map +2 -2
  91. package/package.json +7 -7
  92. package/src/lib/generators/__tests__/module-registry-requires-enforcement.test.ts +3 -3
  93. package/src/lib/generators/__tests__/module-requires.test.ts +242 -0
  94. package/src/lib/generators/module-registry.ts +192 -77
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/cli",
3
- "version": "0.10.1-develop.8098.1.f4decc8a57",
3
+ "version": "0.10.1-develop.8111.1.6c779bc21b",
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.8098.1.f4decc8a57",
64
- "@open-mercato/queue": "0.10.1-develop.8098.1.f4decc8a57",
65
- "@open-mercato/shared": "0.10.1-develop.8098.1.f4decc8a57",
66
- "@open-mercato/telemetry": "0.10.1-develop.8098.1.f4decc8a57",
63
+ "@open-mercato/events": "0.10.1-develop.8111.1.6c779bc21b",
64
+ "@open-mercato/queue": "0.10.1-develop.8111.1.6c779bc21b",
65
+ "@open-mercato/shared": "0.10.1-develop.8111.1.6c779bc21b",
66
+ "@open-mercato/telemetry": "0.10.1-develop.8111.1.6c779bc21b",
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.8098.1.f4decc8a57"
78
+ "@open-mercato/shared": "0.10.1-develop.8111.1.6c779bc21b"
79
79
  },
80
80
  "devDependencies": {
81
- "@open-mercato/shared": "0.10.1-develop.8098.1.f4decc8a57",
81
+ "@open-mercato/shared": "0.10.1-develop.8111.1.6c779bc21b",
82
82
  "@types/jest": "^30.0.0",
83
83
  "jest": "^30.4.2",
84
84
  "ts-jest": "^29.4.12"
@@ -11,9 +11,9 @@
11
11
  * runs the generator under CommonJS, where `require()` is defined and the bug cannot
12
12
  * reproduce.
13
13
  *
14
- * The fix reads `metadata.requires` through `loadModuleExportsFromSource` (a real
15
- * `import()`) with an AST-based static fallback — the same mechanism this file already
16
- * uses for route metadata — so there is no `require()` left to break under ESM. This test
14
+ * The generator now reads `metadata.requires` syntactically through
15
+ * `extractModuleRequiresFromSource` — the index file is parsed, never executed — so there is
16
+ * no `require()` left to break under ESM. This test
17
17
  * drives the real generator against real fixture files on disk rather than asserting on
18
18
  * the implementation, so it fails again if a future change reintroduces `require()`.
19
19
  */
@@ -0,0 +1,242 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import os from 'node:os'
4
+ import type { PackageResolver, ModuleEntry } from '../../resolver'
5
+ import {
6
+ extractModuleRequiresFromSource,
7
+ findMissingModuleRequires,
8
+ generateModuleRegistry,
9
+ generateModuleRegistryApp,
10
+ generateModuleRegistryCli,
11
+ } from '../module-registry'
12
+
13
+ let tmpDir: string
14
+
15
+ function writeSource(relativePath: string, source: string): string {
16
+ const fullPath = path.join(tmpDir, relativePath)
17
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true })
18
+ fs.writeFileSync(fullPath, source)
19
+ return fullPath
20
+ }
21
+
22
+ function createStandaloneSrcMirrorResolver(enabled: ModuleEntry[]): PackageResolver {
23
+ const outputDir = path.join(tmpDir, '.mercato', 'generated')
24
+ fs.mkdirSync(outputDir, { recursive: true })
25
+ return {
26
+ isMonorepo: () => false,
27
+ getRootDir: () => tmpDir,
28
+ getAppDir: () => tmpDir,
29
+ getOutputDir: () => outputDir,
30
+ getModulesConfigPath: () => path.join(tmpDir, 'src', 'modules.ts'),
31
+ discoverPackages: () => [],
32
+ loadEnabledModules: () => enabled,
33
+ getModulePaths: (entry: ModuleEntry) => ({
34
+ appBase: path.join(tmpDir, 'src', 'modules', entry.id),
35
+ pkgBase: path.join(tmpDir, 'node_modules', 'pkg', 'dist', 'modules', entry.id),
36
+ }),
37
+ getModuleImportBase: (entry: ModuleEntry) => ({
38
+ appBase: `@/modules/${entry.id}`,
39
+ pkgBase: `@open-mercato/core/modules/${entry.id}`,
40
+ }),
41
+ getPackageOutputDir: () => outputDir,
42
+ getPackageRoot: () => path.join(tmpDir, 'node_modules', 'pkg'),
43
+ }
44
+ }
45
+
46
+ beforeEach(() => {
47
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'module-requires-'))
48
+ })
49
+
50
+ afterEach(() => {
51
+ fs.rmSync(tmpDir, { recursive: true, force: true })
52
+ })
53
+
54
+ describe('extractModuleRequiresFromSource', () => {
55
+ it('reads requires from a packaged TypeScript source without executing it', () => {
56
+ const file = writeSource('node_modules/pkg/src/modules/workflows/index.ts', `
57
+ import type { ModuleInfo } from '@open-mercato/shared/modules/registry'
58
+ import './commands'
59
+ throw new Error('module side effects must not run')
60
+ export const metadata: ModuleInfo = {
61
+ name: 'workflows',
62
+ requires: ['business_rules'],
63
+ }
64
+ `)
65
+ expect(extractModuleRequiresFromSource(file)).toEqual({ status: 'declared', requires: ['business_rules'] })
66
+ })
67
+
68
+ it('ignores the word requires inside comments', () => {
69
+ const file = writeSource('index.ts', `
70
+ // requires: ['commented_out']
71
+ /* metadata.requires: ['also_commented'] */
72
+ export const metadata = {
73
+ name: 'example',
74
+ /** requires: ['jsdoc_mention'] */
75
+ }
76
+ `)
77
+ expect(extractModuleRequiresFromSource(file)).toEqual({ status: 'absent' })
78
+ })
79
+
80
+ it('ignores unrelated objects that carry a requires field', () => {
81
+ const file = writeSource('index.ts', `
82
+ const settings = { requires: ['not_a_module'] }
83
+ export const config = { requires: ['also_not_a_module'] }
84
+ export const metadata = { name: 'example', requires: ['auth'] }
85
+ export function build() { return { requires: ['runtime_value'] } }
86
+ `)
87
+ expect(extractModuleRequiresFromSource(file)).toEqual({ status: 'declared', requires: ['auth'] })
88
+ })
89
+
90
+ it('ignores a local metadata object that is not exported', () => {
91
+ const file = writeSource('index.ts', `
92
+ const metadata = { requires: ['auth'] }
93
+ export const info = metadata
94
+ `)
95
+ expect(extractModuleRequiresFromSource(file)).toEqual({ status: 'absent' })
96
+ })
97
+
98
+ it.each([
99
+ ['a type annotation', `export const metadata: ModuleInfo = { requires: ['auth', 'attachments'] }`],
100
+ ['an as-assertion', `export const metadata = { requires: ['auth', 'attachments'] } as ModuleInfo`],
101
+ ['a satisfies clause', `export const metadata = { requires: ['auth', 'attachments'] as const } satisfies ModuleInfo`],
102
+ ['a quoted key and template literal', `export const metadata = { 'requires': [\`auth\`, "attachments"] }`],
103
+ ])('reads typed object literals with %s', (_label, declaration) => {
104
+ const file = writeSource('index.ts', `import type { ModuleInfo } from '@open-mercato/shared/modules/registry'\n${declaration}\n`)
105
+ expect(extractModuleRequiresFromSource(file)).toEqual({ status: 'declared', requires: ['auth', 'attachments'] })
106
+ })
107
+
108
+ it('reads compiled ESM output', () => {
109
+ const file = writeSource('node_modules/pkg/dist/modules/workflows/index.js', `
110
+ import "./commands";
111
+ const metadata = { name: "workflows", requires: ["business_rules"] };
112
+ export { metadata };
113
+ `)
114
+ expect(extractModuleRequiresFromSource(file)).toEqual({ status: 'declared', requires: ['business_rules'] })
115
+ })
116
+
117
+ it('reads an aliased named export', () => {
118
+ const file = writeSource('index.js', `
119
+ const moduleInfo = { requires: ["auth"] };
120
+ export { moduleInfo as metadata };
121
+ `)
122
+ expect(extractModuleRequiresFromSource(file)).toEqual({ status: 'declared', requires: ['auth'] })
123
+ })
124
+
125
+ it.each([
126
+ ['exports.metadata', `exports.metadata = { requires: ['auth'] }`],
127
+ ['module.exports.metadata', `module.exports.metadata = { requires: ['auth'] }`],
128
+ ])('reads compiled CommonJS output assigning %s', (_label, assignment) => {
129
+ const file = writeSource('index.js', `"use strict";\n${assignment};\n`)
130
+ expect(extractModuleRequiresFromSource(file)).toEqual({ status: 'declared', requires: ['auth'] })
131
+ })
132
+
133
+ it.each([
134
+ ['a single export', `Object.defineProperty(exports, "__esModule", { value: true });\nexports.metadata = void 0;\nexports.metadata = { requires: ['auth'] };`],
135
+ ['multiple exports', `Object.defineProperty(exports, "__esModule", { value: true });\nexports.features = exports.metadata = void 0;\nexports.metadata = { requires: ['auth'] };\nexports.features = [];`],
136
+ ])('reads tsc CommonJS output with %s', (_label, compiled) => {
137
+ const file = writeSource('index.js', `"use strict";\n${compiled}\n`)
138
+ expect(extractModuleRequiresFromSource(file)).toEqual({ status: 'declared', requires: ['auth'] })
139
+ })
140
+
141
+ it.each([
142
+ ['a re-export', `export { metadata } from './meta'`, 're-exported'],
143
+ ['an imported binding re-exported locally', `import { metadata } from './meta'\nexport { metadata }`, 're-exported'],
144
+ ['an exported declaration without an initializer', `export let metadata\nmetadata = { requires: ['auth'] }`, 'no initializer'],
145
+ ['a computed key', `export const metadata = { ['requires']: ['auth'] }`, 'computed key'],
146
+ ['an identifier entry', `const DEP = 'auth'\nexport const metadata = { requires: [DEP] }`, 'non-literal entry'],
147
+ ['a spread entry', `const base = ['auth']\nexport const metadata = { requires: [...base, 'attachments'] }`, 'non-literal entry'],
148
+ ['an interpolated template', `const id = 'auth'\nexport const metadata = { requires: [\`\${id}\`] }`, 'non-literal entry'],
149
+ ['an identifier array', `const deps = ['auth']\nexport const metadata = { requires: deps }`, 'not an array literal'],
150
+ ['a metadata spread', `const base = { requires: ['auth'] }\nexport const metadata = { ...base }`, 'uses a spread'],
151
+ ['a shorthand property', `const requires = ['auth']\nexport const metadata = { requires }`, 'not a property assignment'],
152
+ ['a non-literal metadata', `export const metadata = buildMetadata()`, 'not an object literal'],
153
+ ])('reports %s as unresolvable instead of guessing', (_label, source, reason) => {
154
+ const file = writeSource('index.ts', `${source}\n`)
155
+ const extraction = extractModuleRequiresFromSource(file)
156
+ expect(extraction.status).toBe('unresolvable')
157
+ expect(extraction.status === 'unresolvable' && extraction.reason).toContain(reason)
158
+ })
159
+
160
+ it('ignores a type-only metadata export specifier', () => {
161
+ const file = writeSource('index.ts', `
162
+ import type { metadata } from './meta'
163
+ export { type metadata }
164
+ export const info = { requires: ['auth'] }
165
+ `)
166
+ expect(extractModuleRequiresFromSource(file)).toEqual({ status: 'absent' })
167
+ })
168
+
169
+ it('returns absent when there is no requires or no file', () => {
170
+ expect(extractModuleRequiresFromSource(writeSource('index.ts', `export const metadata = { name: 'x' }\n`)))
171
+ .toEqual({ status: 'absent' })
172
+ expect(extractModuleRequiresFromSource(path.join(tmpDir, 'missing.ts'))).toEqual({ status: 'absent' })
173
+ })
174
+ })
175
+
176
+ describe('findMissingModuleRequires', () => {
177
+ it('lists only the dependencies that are not enabled', () => {
178
+ const requiresByModule = new Map([
179
+ ['workflows', ['business_rules']],
180
+ ['agent_orchestrator', ['workflows', 'api_keys', 'auth', 'attachments']],
181
+ ])
182
+ expect(findMissingModuleRequires([{ id: 'workflows' }, { id: 'agent_orchestrator' }, { id: 'auth' }], requiresByModule))
183
+ .toEqual([
184
+ { moduleId: 'workflows', missing: ['business_rules'] },
185
+ { moduleId: 'agent_orchestrator', missing: ['api_keys', 'attachments'] },
186
+ ])
187
+ })
188
+ })
189
+
190
+ describe('module dependency validation during generate', () => {
191
+ let exitSpy: jest.SpyInstance
192
+ let errorSpy: jest.SpyInstance
193
+
194
+ beforeEach(() => {
195
+ exitSpy = jest.spyOn(process, 'exit').mockImplementation(((code?: number) => {
196
+ throw new Error(`process.exit(${code})`)
197
+ }) as never)
198
+ errorSpy = jest.spyOn(console, 'error').mockImplementation(() => undefined)
199
+ writeSource(
200
+ 'node_modules/pkg/src/modules/workflows/index.ts',
201
+ `import type { ModuleInfo } from '@open-mercato/shared/modules/registry'\n`
202
+ + `throw new Error('module side effects must not run')\n`
203
+ + `export const metadata: ModuleInfo = { name: 'workflows', requires: ['business_rules'] }\n`,
204
+ )
205
+ writeSource(
206
+ 'node_modules/pkg/dist/modules/workflows/index.js',
207
+ `throw new Error('module side effects must not run');\n`
208
+ + `export const metadata = { name: 'workflows', requires: ['business_rules'] };\n`,
209
+ )
210
+ })
211
+
212
+ afterEach(() => {
213
+ exitSpy.mockRestore()
214
+ errorSpy.mockRestore()
215
+ })
216
+
217
+ it.each([
218
+ ['generateModuleRegistry', generateModuleRegistry],
219
+ ['generateModuleRegistryApp', generateModuleRegistryApp],
220
+ ['generateModuleRegistryCli', generateModuleRegistryCli],
221
+ ])('%s fails when a packaged TypeScript module misses a required module', async (_label, generate) => {
222
+ const resolver = createStandaloneSrcMirrorResolver([{ id: 'workflows', from: '@open-mercato/core' }])
223
+ await expect(generate({ resolver, quiet: true })).rejects.toThrow('process.exit(1)')
224
+ const printed = errorSpy.mock.calls.map((call) => String(call[0])).join('\n')
225
+ expect(printed).toContain('Module "workflows" requires: business_rules')
226
+ expect(printed).toContain("Fix: Enable module 'business_rules' in src/modules.ts.")
227
+ })
228
+
229
+ it.each([
230
+ ['generateModuleRegistry', generateModuleRegistry],
231
+ ['generateModuleRegistryApp', generateModuleRegistryApp],
232
+ ['generateModuleRegistryCli', generateModuleRegistryCli],
233
+ ])('%s passes when every required module is enabled', async (_label, generate) => {
234
+ const resolver = createStandaloneSrcMirrorResolver([
235
+ { id: 'workflows', from: '@open-mercato/core' },
236
+ { id: 'business_rules', from: '@open-mercato/core' },
237
+ ])
238
+ const result = await generate({ resolver, quiet: true })
239
+ expect(result.errors).toEqual([])
240
+ expect(exitSpy).not.toHaveBeenCalled()
241
+ })
242
+ })
@@ -6,7 +6,7 @@ import { VariableDeclarationKind, type WriterFunction } from 'ts-morph'
6
6
  import ts from 'typescript-js'
7
7
  import type { ModuleEntry, PackageResolver } from '../resolver'
8
8
  import { getEnabledModuleIdentities } from '../module-identity'
9
- import { getModuleRequirementHint, resolveModuleRequirement } from '@open-mercato/shared/modules/module-locators'
9
+ import { getModuleRequirementHint, resolveModuleRequirement, type ModuleIdentity } from '@open-mercato/shared/modules/module-locators'
10
10
  import {
11
11
  DEV_SUPERVISOR_MANIFEST_FILE,
12
12
  DEV_SUPERVISOR_MANIFEST_VERSION,
@@ -525,6 +525,145 @@ function extractNamedObjectLiteralSource(sourceFile: string, exportName: string)
525
525
  return null
526
526
  }
527
527
 
528
+ export type ModuleRequiresExtraction =
529
+ | { status: 'declared'; requires: string[] }
530
+ | { status: 'absent' }
531
+ | { status: 'unresolvable'; reason: string }
532
+
533
+ function isCommonJsMetadataTarget(expression: ts.Expression): boolean {
534
+ if (!ts.isPropertyAccessExpression(expression) || expression.name.text !== 'metadata') return false
535
+ const target = expression.expression
536
+ if (ts.isIdentifier(target)) return target.text === 'exports'
537
+ return ts.isPropertyAccessExpression(target)
538
+ && target.name.text === 'exports'
539
+ && ts.isIdentifier(target.expression)
540
+ && target.expression.text === 'module'
541
+ }
542
+
543
+ type ExportedMetadataSource =
544
+ | { kind: 'initializer'; expression: ts.Expression }
545
+ | { kind: 're-export' }
546
+ | { kind: 'no-initializer' }
547
+
548
+ function findExportedMetadataSource(parsed: ts.SourceFile): ExportedMetadataSource | undefined {
549
+ const localNamesExportedAsMetadata = new Set<string>()
550
+ for (const statement of parsed.statements) {
551
+ if (
552
+ ts.isExportDeclaration(statement)
553
+ && !statement.isTypeOnly
554
+ && statement.exportClause
555
+ && ts.isNamedExports(statement.exportClause)
556
+ ) {
557
+ for (const element of statement.exportClause.elements) {
558
+ if (element.name.text !== 'metadata' || element.isTypeOnly) continue
559
+ if (statement.moduleSpecifier) return { kind: 're-export' }
560
+ localNamesExportedAsMetadata.add(element.propertyName?.text ?? element.name.text)
561
+ }
562
+ }
563
+ }
564
+
565
+ let commonJsInitializer: ts.Expression | undefined
566
+ for (const statement of parsed.statements) {
567
+ if (ts.isVariableStatement(statement)) {
568
+ const exportsDirectly = (ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined)
569
+ ?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) ?? false
570
+ for (const declaration of statement.declarationList.declarations) {
571
+ if (!ts.isIdentifier(declaration.name)) continue
572
+ const localName = declaration.name.text
573
+ const exported = (exportsDirectly && localName === 'metadata') || localNamesExportedAsMetadata.has(localName)
574
+ if (!exported) continue
575
+ return declaration.initializer
576
+ ? { kind: 'initializer', expression: declaration.initializer }
577
+ : { kind: 'no-initializer' }
578
+ }
579
+ continue
580
+ }
581
+ if (
582
+ ts.isExpressionStatement(statement)
583
+ && ts.isBinaryExpression(statement.expression)
584
+ && statement.expression.operatorToken.kind === ts.SyntaxKind.EqualsToken
585
+ && isCommonJsMetadataTarget(statement.expression.left)
586
+ && !ts.isVoidExpression(statement.expression.right)
587
+ ) {
588
+ commonJsInitializer = statement.expression.right
589
+ }
590
+ }
591
+ if (commonJsInitializer) return { kind: 'initializer', expression: commonJsInitializer }
592
+ if (localNamesExportedAsMetadata.size > 0) return { kind: 're-export' }
593
+ return undefined
594
+ }
595
+
596
+ /**
597
+ * Reads `metadata.requires` from a module `index` source purely syntactically — the file is parsed,
598
+ * never executed, so packaged TypeScript sources and module side effects are both safe. Only the
599
+ * exported `metadata` object is consulted, and only string-literal entries are accepted: anything
600
+ * computed is reported as unresolvable instead of being guessed.
601
+ */
602
+ export function extractModuleRequiresFromSource(sourceFile: string): ModuleRequiresExtraction {
603
+ let source = ''
604
+ try {
605
+ source = fs.readFileSync(sourceFile, 'utf8')
606
+ } catch {
607
+ return { status: 'absent' }
608
+ }
609
+
610
+ const parsed = ts.createSourceFile(
611
+ sourceFile,
612
+ source,
613
+ ts.ScriptTarget.Latest,
614
+ true,
615
+ inferScriptKind(sourceFile),
616
+ )
617
+
618
+ const metadataSource = findExportedMetadataSource(parsed)
619
+ if (!metadataSource) return { status: 'absent' }
620
+ if (metadataSource.kind === 're-export') {
621
+ return { status: 'unresolvable', reason: 'exported metadata is re-exported from another file' }
622
+ }
623
+ if (metadataSource.kind === 'no-initializer') {
624
+ return { status: 'unresolvable', reason: 'exported metadata has no initializer' }
625
+ }
626
+
627
+ const metadata = unwrapExpression(metadataSource.expression)
628
+ if (!ts.isObjectLiteralExpression(metadata)) {
629
+ return { status: 'unresolvable', reason: 'exported metadata is not an object literal' }
630
+ }
631
+
632
+ let requiresInitializer: ts.Expression | undefined
633
+ for (const property of metadata.properties) {
634
+ if (ts.isSpreadAssignment(property)) {
635
+ return { status: 'unresolvable', reason: 'exported metadata uses a spread' }
636
+ }
637
+ const name = property.name
638
+ if (!name) continue
639
+ if (ts.isComputedPropertyName(name)) {
640
+ return { status: 'unresolvable', reason: 'exported metadata uses a computed key' }
641
+ }
642
+ const key = ts.isIdentifier(name) || ts.isStringLiteral(name) ? name.text : null
643
+ if (key !== 'requires') continue
644
+ if (!ts.isPropertyAssignment(property)) {
645
+ return { status: 'unresolvable', reason: 'metadata.requires is not a property assignment' }
646
+ }
647
+ requiresInitializer = property.initializer
648
+ }
649
+ if (!requiresInitializer) return { status: 'absent' }
650
+
651
+ const requiresArray = unwrapExpression(requiresInitializer)
652
+ if (!ts.isArrayLiteralExpression(requiresArray)) {
653
+ return { status: 'unresolvable', reason: 'metadata.requires is not an array literal' }
654
+ }
655
+
656
+ const requires: string[] = []
657
+ for (const element of requiresArray.elements) {
658
+ const value = unwrapExpression(element)
659
+ if (!ts.isStringLiteral(value) && !ts.isNoSubstitutionTemplateLiteral(value)) {
660
+ return { status: 'unresolvable', reason: 'metadata.requires contains a non-literal entry' }
661
+ }
662
+ requires.push(value.text)
663
+ }
664
+ return { status: 'declared', requires }
665
+ }
666
+
528
667
  function resolveLocalStringConstants(parsed: ts.SourceFile): Map<string, string> {
529
668
  const constants = new Map<string, string>()
530
669
  for (const statement of parsed.statements) {
@@ -1585,6 +1724,52 @@ function alreadyWarned(sourcePath: string): boolean {
1585
1724
  return false
1586
1725
  }
1587
1726
 
1727
+ export type MissingModuleRequires = { moduleId: string; missing: string[] }
1728
+
1729
+ export function findMissingModuleRequires(
1730
+ modules: readonly ModuleIdentity[],
1731
+ requiresByModule: ReadonlyMap<string, string[]>,
1732
+ ): MissingModuleRequires[] {
1733
+ const problems: MissingModuleRequires[] = []
1734
+ for (const [moduleId, requires] of requiresByModule.entries()) {
1735
+ const missing = requires.filter((requirement) => !resolveModuleRequirement(requirement, modules))
1736
+ if (missing.length) problems.push({ moduleId, missing })
1737
+ }
1738
+ return problems
1739
+ }
1740
+
1741
+ function exitOnMissingModuleRequires(
1742
+ modules: readonly ModuleIdentity[],
1743
+ requiresByModule: ReadonlyMap<string, string[]>,
1744
+ ): void {
1745
+ const problems = findMissingModuleRequires(modules, requiresByModule)
1746
+ if (!problems.length) return
1747
+ console.error('\nModule dependency check failed:')
1748
+ for (const problem of problems) console.error(`- Module "${problem.moduleId}" requires: ${problem.missing.join(', ')}`)
1749
+ const missingRequirements = new Set(problems.flatMap((problem) => problem.missing))
1750
+ for (const requirement of missingRequirements) console.error(`Fix: ${getModuleRequirementHint(requirement)}`)
1751
+ process.exit(1)
1752
+ }
1753
+
1754
+ function collectDeclaredModuleRequires(
1755
+ moduleId: string,
1756
+ indexPath: string,
1757
+ requiresByModule: Map<string, string[]>,
1758
+ quiet: boolean,
1759
+ ): void {
1760
+ const extraction = extractModuleRequiresFromSource(indexPath)
1761
+ if (extraction.status === 'declared') {
1762
+ if (extraction.requires.length) requiresByModule.set(moduleId, extraction.requires)
1763
+ return
1764
+ }
1765
+ if (extraction.status === 'unresolvable' && !quiet && !alreadyWarned(`requires:${indexPath}`)) {
1766
+ console.warn(
1767
+ `[generate] ⚠ Module "${moduleId}" declares metadata.requires that cannot be read statically `
1768
+ + `(${extraction.reason}); its dependency check is skipped. Use an array of string literals: ${indexPath}`,
1769
+ )
1770
+ }
1771
+ }
1772
+
1588
1773
  /**
1589
1774
  * Warns when a discovered page metadata file exports no `metadata` binding.
1590
1775
  *
@@ -1693,20 +1878,6 @@ function resolveApiPathFromMetadata(metadata: unknown, fallbackPath: string): st
1693
1878
  return typeof candidate === 'string' && candidate.length > 0 ? candidate : fallbackPath
1694
1879
  }
1695
1880
 
1696
- function resolveModuleRequiresFromMetadata(metadata: unknown): string[] | undefined {
1697
- if (!metadata || typeof metadata !== 'object') return undefined
1698
- const requires = (metadata as Record<string, unknown>).requires
1699
- if (!Array.isArray(requires)) return undefined
1700
- const resolved = requires.filter((value): value is string => typeof value === 'string')
1701
- return resolved.length > 0 ? resolved : undefined
1702
- }
1703
-
1704
- async function resolveModuleRequiresFromIndexFile(indexFileAbsolutePath: string): Promise<string[] | undefined> {
1705
- const loadedModule = await loadModuleExportsFromSource<Record<string, unknown>>(indexFileAbsolutePath)
1706
- const metadata = loadedModule?.metadata ?? extractNamedObjectLiteralExport(indexFileAbsolutePath, 'metadata')
1707
- return resolveModuleRequiresFromMetadata(metadata)
1708
- }
1709
-
1710
1881
  function detectExportedHttpMethods(sourceFile: string): HttpMethod[] {
1711
1882
  try {
1712
1883
  return sourceExportedHttpMethods(fs.readFileSync(sourceFile, 'utf8'))
@@ -3632,8 +3803,7 @@ async function generateModuleRegistryFromDiscovery(options: ModuleRegistryRender
3632
3803
  const importPath = sanitizeGeneratedModuleSpecifier(indexResolved.importPath)
3633
3804
  imports.push(buildImportStatement(`* as ${infoImportName}`, importPath))
3634
3805
  runtimeImports.push(buildImportStatement(`* as ${infoImportName}`, importPath))
3635
- const reqs = await resolveModuleRequiresFromIndexFile(indexResolved.absolutePath)
3636
- if (reqs && reqs.length) requiresByModule.set(modId, reqs)
3806
+ collectDeclaredModuleRequires(modId, indexResolved.absolutePath, requiresByModule, quiet)
3637
3807
  }
3638
3808
 
3639
3809
  // 2. Pages: frontend
@@ -4165,25 +4335,7 @@ async function generateModuleRegistryFromDiscovery(options: ModuleRegistryRender
4165
4335
  }),
4166
4336
  ]),
4167
4337
  })
4168
- // Validate module dependencies declared via ModuleInfo.requires
4169
- {
4170
- const identities = discovery.identities
4171
- const problems: string[] = []
4172
- const missingRequirements = new Set<string>()
4173
- for (const [modId, reqs] of requiresByModule.entries()) {
4174
- const missing = reqs.filter((requirement) => !resolveModuleRequirement(requirement, identities))
4175
- for (const requirement of missing) missingRequirements.add(requirement)
4176
- if (missing.length) {
4177
- problems.push(`- Module "${modId}" requires: ${missing.join(', ')}`)
4178
- }
4179
- }
4180
- if (problems.length) {
4181
- console.error('\nModule dependency check failed:')
4182
- for (const p of problems) console.error(p)
4183
- for (const requirement of missingRequirements) console.error(`Fix: ${getModuleRequirementHint(requirement)}`)
4184
- process.exit(1)
4185
- }
4186
- }
4338
+ exitOnMissingModuleRequires(discovery.identities, requiresByModule)
4187
4339
 
4188
4340
  const structureChecksum = discovery.getStructureChecksum()
4189
4341
 
@@ -4347,8 +4499,7 @@ async function generateModuleRegistryAppFromDiscovery(options: ModuleRegistryRen
4347
4499
  const importPath = sanitizeGeneratedModuleSpecifier(indexResolved.importPath)
4348
4500
  imports.push(buildImportStatement(`* as ${infoImportName}`, importPath))
4349
4501
  bootstrapImports.push(buildImportStatement(`* as ${infoImportName}`, importPath))
4350
- const reqs = await resolveModuleRequiresFromIndexFile(indexResolved.absolutePath)
4351
- if (reqs && reqs.length) requiresByModule.set(modId, reqs)
4502
+ collectDeclaredModuleRequires(modId, indexResolved.absolutePath, requiresByModule, quiet)
4352
4503
  }
4353
4504
 
4354
4505
  {
@@ -4643,24 +4794,7 @@ async function generateModuleRegistryAppFromDiscovery(options: ModuleRegistryRen
4643
4794
  initializer: identifier('modules'),
4644
4795
  })
4645
4796
 
4646
- {
4647
- const identities = discovery.identities
4648
- const problems: string[] = []
4649
- const missingRequirements = new Set<string>()
4650
- for (const [modId, reqs] of requiresByModule.entries()) {
4651
- const missing = reqs.filter((requirement) => !resolveModuleRequirement(requirement, identities))
4652
- for (const requirement of missing) missingRequirements.add(requirement)
4653
- if (missing.length) {
4654
- problems.push(`- Module "${modId}" requires: ${missing.join(', ')}`)
4655
- }
4656
- }
4657
- if (problems.length) {
4658
- console.error('\nModule dependency check failed:')
4659
- for (const p of problems) console.error(p)
4660
- for (const requirement of missingRequirements) console.error(`Fix: ${getModuleRequirementHint(requirement)}`)
4661
- process.exit(1)
4662
- }
4663
- }
4797
+ exitOnMissingModuleRequires(discovery.identities, requiresByModule)
4664
4798
 
4665
4799
  const structureChecksum = discovery.getStructureChecksum()
4666
4800
  writeGeneratedFile({ outFile, checksumFile, content: output, structureChecksum, result, quiet })
@@ -4774,8 +4908,7 @@ async function generateModuleRegistryCliFromDiscovery(options: ModuleRegistryRen
4774
4908
  infoImportName = `I${importIdRef.value++}_${toVar(modId)}`
4775
4909
  const importPath = sanitizeGeneratedModuleSpecifier(indexResolved.importPath)
4776
4910
  imports.push(buildImportStatement(`* as ${infoImportName}`, importPath))
4777
- const reqs = await resolveModuleRequiresFromIndexFile(indexResolved.absolutePath)
4778
- if (reqs && reqs.length) requiresByModule.set(modId, reqs)
4911
+ collectDeclaredModuleRequires(modId, indexResolved.absolutePath, requiresByModule, quiet)
4779
4912
  }
4780
4913
 
4781
4914
  // Module setup configuration: setup.ts
@@ -5028,25 +5161,7 @@ async function generateModuleRegistryCliFromDiscovery(options: ModuleRegistryRen
5028
5161
  ]),
5029
5162
  })
5030
5163
 
5031
- // Validate module dependencies declared via ModuleInfo.requires
5032
- {
5033
- const identities = discovery.identities
5034
- const problems: string[] = []
5035
- const missingRequirements = new Set<string>()
5036
- for (const [modId, reqs] of requiresByModule.entries()) {
5037
- const missing = reqs.filter((requirement) => !resolveModuleRequirement(requirement, identities))
5038
- for (const requirement of missing) missingRequirements.add(requirement)
5039
- if (missing.length) {
5040
- problems.push(`- Module "${modId}" requires: ${missing.join(', ')}`)
5041
- }
5042
- }
5043
- if (problems.length) {
5044
- console.error('\nModule dependency check failed:')
5045
- for (const p of problems) console.error(p)
5046
- for (const requirement of missingRequirements) console.error(`Fix: ${getModuleRequirementHint(requirement)}`)
5047
- process.exit(1)
5048
- }
5049
- }
5164
+ exitOnMissingModuleRequires(discovery.identities, requiresByModule)
5050
5165
 
5051
5166
  const structureChecksum = discovery.getStructureChecksum()
5052
5167
  writeGeneratedFile({ outFile, checksumFile, content: output, structureChecksum, result, quiet })