@azure-net/cli 2.3.62 → 4.0.0-0

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 (91) hide show
  1. package/.prettierrc +7 -0
  2. package/bin/azure-net.js +247 -157
  3. package/bin/azure-net.ts +253 -0
  4. package/eslint.config.js +19 -0
  5. package/package.json +12 -5
  6. package/src/commands/generate/generateCrudBase.js +95 -114
  7. package/src/commands/generate/generateCrudPresenter.js +135 -142
  8. package/src/commands/generate/generateModule.js +21 -21
  9. package/src/commands/generate/generateModuleBase.js +92 -114
  10. package/src/commands/generate/generateModulePresenter.js +73 -80
  11. package/src/commands/generate/generatePresenter.js +38 -44
  12. package/src/commands/generate/generateRepository.js +41 -47
  13. package/src/commands/generate/generateSchema.js +74 -70
  14. package/src/commands/generate/generateService.js +32 -37
  15. package/src/commands/generate/index.js +0 -5
  16. package/src/generate/layers/generateRepository.js +124 -0
  17. package/src/generate/layers/generateRepositoryMethod.js +102 -0
  18. package/src/generate/layers/generateUseCases.js +50 -0
  19. package/src/generate/layers/repositoryShared.js +569 -0
  20. package/src/generate/module/generateDomain.js +146 -0
  21. package/src/generate/module/generateDomain.ts +147 -0
  22. package/src/generate/module/generateModule.js +84 -0
  23. package/src/generate/module/generateModule.ts +84 -0
  24. package/src/generate/module/generatePresenter.js +419 -0
  25. package/src/generate/module/generatePresenter.ts +442 -0
  26. package/src/generate/module/generateRepository.js +144 -0
  27. package/src/generate/module/generateRepository.ts +158 -0
  28. package/src/generate/module/generateSchemaFromType.js +320 -0
  29. package/src/generate/module/generateSchemaFromType.ts +325 -0
  30. package/src/generate/module/generateTypesJson.js +252 -0
  31. package/src/generate/module/generateTypesJson.ts +259 -0
  32. package/src/generate/module/generateUseCases.js +67 -0
  33. package/src/generate/module/generateUseCases.ts +67 -0
  34. package/src/generate/module/repositoryModuleShared.js +598 -0
  35. package/src/generate/ui/generateComponent.js +98 -0
  36. package/src/generate/ui/generateComponent.ts +100 -0
  37. package/src/generate/ui/generateDesignComponent.js +71 -0
  38. package/src/generate/ui/generateDesignComponent.ts +71 -0
  39. package/src/generate/ui/generateWidget.js +71 -0
  40. package/src/generate/ui/generateWidget.ts +71 -0
  41. package/src/init/initAliases.js +159 -0
  42. package/src/init/initAliases.ts +167 -0
  43. package/src/init/initEdges.js +74 -0
  44. package/src/init/initEdges.ts +74 -0
  45. package/src/init/initStructure.js +122 -0
  46. package/src/init/initStructure.ts +124 -0
  47. package/src/install/installFresh.js +101 -0
  48. package/src/install/installFresh.ts +101 -0
  49. package/src/plugins/addLint.js +257 -0
  50. package/src/plugins/addLint.ts +274 -0
  51. package/src/plugins/index.js +1 -0
  52. package/src/plugins/index.ts +1 -0
  53. package/src/scaffolds/createCoreMiddleware.js +27 -0
  54. package/src/scaffolds/createCoreMiddleware.ts +27 -0
  55. package/src/scaffolds/createCoreSchema.js +141 -0
  56. package/src/scaffolds/createCoreSchema.ts +142 -0
  57. package/src/scaffolds/createDatasource.js +173 -0
  58. package/src/scaffolds/createDatasource.ts +175 -0
  59. package/src/scaffolds/createDatasourceProvider.js +164 -0
  60. package/src/scaffolds/createDatasourceProvider.ts +175 -0
  61. package/src/scaffolds/createMiddleware.js +105 -0
  62. package/src/scaffolds/createMiddleware.ts +105 -0
  63. package/src/scaffolds/createPresenterFactory.js +112 -0
  64. package/src/scaffolds/createPresenterFactory.ts +114 -0
  65. package/src/scaffolds/createResponse.js +64 -0
  66. package/src/scaffolds/createResponse.ts +64 -0
  67. package/src/scaffolds/createSchemaRule.js +40 -0
  68. package/src/scaffolds/createSchemaRule.ts +42 -0
  69. package/src/scaffolds/createTranslationManager.js +78 -0
  70. package/src/scaffolds/createTranslationManager.ts +78 -0
  71. package/src/scaffolds/index.js +9 -0
  72. package/src/scaffolds/index.ts +9 -0
  73. package/src/utils/contextUtils.js +56 -49
  74. package/src/utils/fileUtils.js +72 -84
  75. package/src/utils/loadConfig.js +57 -13
  76. package/tsconfig.json +19 -0
  77. package/src/commands/generate/generateComponent.js +0 -53
  78. package/src/commands/generate/generateDatasource.js +0 -84
  79. package/src/commands/generate/generateDesignComponent.js +0 -53
  80. package/src/commands/generate/generateResponse.js +0 -41
  81. package/src/commands/generate/generateWidget.js +0 -53
  82. package/src/commands/init/index.js +0 -9
  83. package/src/commands/init/initAliases.js +0 -52
  84. package/src/commands/init/initEdges.js +0 -42
  85. package/src/commands/init/initLint.js +0 -138
  86. package/src/commands/init/initMiddleware.js +0 -21
  87. package/src/commands/init/initPresenter.js +0 -25
  88. package/src/commands/init/initSchema.js +0 -22
  89. package/src/commands/init/initStructure.js +0 -140
  90. package/src/commands/init/initTranslations.js +0 -59
  91. package/src/commands/init/migrateStructure.js +0 -144
@@ -0,0 +1,325 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import prompts from 'prompts';
4
+ import { getConfigState, resolveContextAlias, selectContext } from './repositoryModuleShared.js';
5
+
6
+ const listDirectories = async (targetPath: string): Promise<string[]> => {
7
+ try {
8
+ const items = await fs.readdir(targetPath, { withFileTypes: true });
9
+ return items.filter((item) => item.isDirectory()).map((item) => item.name);
10
+ } catch {
11
+ return [];
12
+ }
13
+ };
14
+
15
+ const listSchemaFiles = async (targetPath: string): Promise<string[]> => {
16
+ try {
17
+ const files = await fs.readdir(targetPath);
18
+ return files.filter((item) => item.endsWith('.ts') && item !== 'index.ts');
19
+ } catch {
20
+ return [];
21
+ }
22
+ };
23
+
24
+ const resolveAliasMap = async (): Promise<Map<string, string>> => {
25
+ const { contexts, coreAlias } = await getConfigState();
26
+ const map = new Map<string, string>();
27
+ map.set(coreAlias, path.join(process.cwd(), 'src', 'core'));
28
+
29
+ for (const context of contexts) {
30
+ const alias = resolveContextAlias(contexts, context.name);
31
+ map.set(alias, path.join(process.cwd(), 'src', 'app', context.name));
32
+ }
33
+
34
+ return map;
35
+ };
36
+
37
+ const resolveImportToFile = async (fromFile: string, importPath: string, aliasMap: Map<string, string>): Promise<string | null> => {
38
+ const rawImport = String(importPath ?? '').trim();
39
+ if (!rawImport.length) return null;
40
+
41
+ let absolute = '';
42
+ if (rawImport.startsWith('.')) {
43
+ absolute = path.resolve(path.dirname(fromFile), rawImport);
44
+ } else {
45
+ const alias = Array.from(aliasMap.keys()).find((key) => rawImport === key || rawImport.startsWith(`${key}/`));
46
+ if (!alias) return null;
47
+ const suffix = rawImport === alias ? '' : rawImport.slice(alias.length + 1);
48
+ absolute = path.join(aliasMap.get(alias) as string, suffix);
49
+ }
50
+
51
+ const tsCandidate = absolute.endsWith('.ts') ? absolute : `${absolute}.ts`;
52
+ try {
53
+ await fs.access(tsCandidate);
54
+ return tsCandidate;
55
+ } catch {
56
+ const indexCandidate = path.join(absolute, 'index.ts');
57
+ try {
58
+ await fs.access(indexCandidate);
59
+ return indexCandidate;
60
+ } catch {
61
+ return null;
62
+ }
63
+ }
64
+ };
65
+
66
+ const extractSchemaTypeName = (content: string): string | null => {
67
+ const typeMatch = content.match(/=\s*[A-Za-z0-9_]+<\s*([^>]+?)\s*>\s*\(\)/m);
68
+ if (!typeMatch) return null;
69
+ return String(typeMatch[1]).trim();
70
+ };
71
+
72
+ const findTypeImportPath = (content: string, typeName: string): string | null => {
73
+ const importRegex = /import\s+type\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/g;
74
+ let match: RegExpExecArray | null;
75
+ while ((match = importRegex.exec(content)) !== null) {
76
+ const importedList = match[1];
77
+ const sourcePath = match[2];
78
+ if (!importedList || !sourcePath) continue;
79
+ const imported = importedList
80
+ .split(',')
81
+ .map((item) => item.trim())
82
+ .filter(Boolean);
83
+ if (imported.includes(typeName)) {
84
+ return sourcePath;
85
+ }
86
+ }
87
+ return null;
88
+ };
89
+
90
+ const extractInterfaceBody = (content: string, interfaceName: string): string | null => {
91
+ const declarationRegex = new RegExp(`export\\s+interface\\s+${interfaceName}\\s*\\{`);
92
+ const declarationMatch = content.match(declarationRegex);
93
+ if (!declarationMatch || declarationMatch.index === undefined) return null;
94
+
95
+ const openBraceIndex = content.indexOf('{', declarationMatch.index);
96
+ if (openBraceIndex === -1) return null;
97
+
98
+ let depth = 0;
99
+ let closeBraceIndex = -1;
100
+ for (let index = openBraceIndex; index < content.length; index += 1) {
101
+ const char = content[index];
102
+ if (char === '{') depth += 1;
103
+ if (char === '}') {
104
+ depth -= 1;
105
+ if (depth === 0) {
106
+ closeBraceIndex = index;
107
+ break;
108
+ }
109
+ }
110
+ }
111
+
112
+ if (closeBraceIndex === -1) return null;
113
+ return content.slice(openBraceIndex + 1, closeBraceIndex);
114
+ };
115
+
116
+ const resolveRelativeExportPath = async (fromFile: string, exportPath: string): Promise<string | null> => {
117
+ const absolute = path.resolve(path.dirname(fromFile), exportPath);
118
+ const tsCandidate = absolute.endsWith('.ts') ? absolute : `${absolute}.ts`;
119
+ try {
120
+ await fs.access(tsCandidate);
121
+ return tsCandidate;
122
+ } catch {
123
+ const indexCandidate = path.join(absolute, 'index.ts');
124
+ try {
125
+ await fs.access(indexCandidate);
126
+ return indexCandidate;
127
+ } catch {
128
+ return null;
129
+ }
130
+ }
131
+ };
132
+
133
+ const findInterfaceBodyByExportGraph = async (
134
+ entryFilePath: string,
135
+ interfaceName: string,
136
+ visited: Set<string> = new Set()
137
+ ): Promise<string | null> => {
138
+ const resolvedPath = path.resolve(entryFilePath);
139
+ if (visited.has(resolvedPath)) return null;
140
+ visited.add(resolvedPath);
141
+
142
+ let content = '';
143
+ try {
144
+ content = await fs.readFile(resolvedPath, 'utf-8');
145
+ } catch {
146
+ return null;
147
+ }
148
+
149
+ const direct = extractInterfaceBody(content, interfaceName);
150
+ if (direct) return direct;
151
+
152
+ const exportRegex = /export\s+(?:\*|\{[^}]+\})\s+from\s+['"]([^'"]+)['"]/g;
153
+ let match: RegExpExecArray | null;
154
+ while ((match = exportRegex.exec(content)) !== null) {
155
+ const exportPath = match[1];
156
+ if (!exportPath || !exportPath.startsWith('.')) continue;
157
+ const nextPath = await resolveRelativeExportPath(resolvedPath, exportPath);
158
+ if (!nextPath) continue;
159
+ const nested = await findInterfaceBodyByExportGraph(nextPath, interfaceName, visited);
160
+ if (nested) return nested;
161
+ }
162
+
163
+ return null;
164
+ };
165
+
166
+ const findInterfaceBodyByScan = async (rootDir: string, interfaceName: string): Promise<string | null> => {
167
+ const queue: string[] = [rootDir];
168
+ while (queue.length) {
169
+ const current = queue.shift();
170
+ if (!current) continue;
171
+ let entries: import('node:fs').Dirent[] = [];
172
+ try {
173
+ entries = await fs.readdir(current, { withFileTypes: true });
174
+ } catch {
175
+ continue;
176
+ }
177
+
178
+ for (const entry of entries) {
179
+ const absolute = path.join(current, entry.name);
180
+ if (entry.isDirectory()) {
181
+ queue.push(absolute);
182
+ continue;
183
+ }
184
+ if (!entry.isFile() || !entry.name.endsWith('.ts')) continue;
185
+ const content = await fs.readFile(absolute, 'utf-8');
186
+ const body = extractInterfaceBody(content, interfaceName);
187
+ if (body) return body;
188
+ }
189
+ }
190
+ return null;
191
+ };
192
+
193
+ const extractKeys = (body: string): string[] => {
194
+ const keys: string[] = [];
195
+ const keyRegex = /^\s*([A-Za-z_$][A-Za-z0-9_$]*)\??\s*:/gm;
196
+ let match: RegExpExecArray | null;
197
+ while ((match = keyRegex.exec(body)) !== null) {
198
+ const key = match[1];
199
+ if (key) keys.push(key);
200
+ }
201
+ return Array.from(new Set(keys));
202
+ };
203
+
204
+ const updateRulesObject = (schemaContent: string, keys: string[]): string | null => {
205
+ const rulesRegex = /\.rules\(\(rules\)\s*=>\s*\(\{([\s\S]*?)\}\)\)/m;
206
+ const match = schemaContent.match(rulesRegex);
207
+ if (!match) return null;
208
+
209
+ const currentBody = match[1] ?? '';
210
+ const existingKeys = new Set(extractKeys(currentBody));
211
+ const newLines = keys.filter((key) => !existingKeys.has(key)).map((key) => `\t\t${key}: [],`);
212
+
213
+ if (!newLines.length) return schemaContent;
214
+
215
+ const trimmedBody = currentBody.trimEnd();
216
+ const nextBody = trimmedBody.length ? `${trimmedBody}\n${newLines.join('\n')}\n\t` : `\n${newLines.join('\n')}\n\t`;
217
+
218
+ return schemaContent.replace(rulesRegex, `.rules((rules) => ({${nextBody}}))`);
219
+ };
220
+
221
+ export default async function generateSchemaFromType(): Promise<void> {
222
+ const contextName = await selectContext('Select context for schema update:');
223
+ if (!contextName) {
224
+ process.exitCode = 1;
225
+ return;
226
+ }
227
+
228
+ const presentationPath = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'presentation');
229
+ const presenterFolders = await listDirectories(presentationPath);
230
+ if (!presenterFolders.length) {
231
+ console.error(`❌ No presenter folders found in ${presentationPath}`);
232
+ process.exitCode = 1;
233
+ return;
234
+ }
235
+
236
+ const { presenterFolder } = await prompts({
237
+ type: 'select',
238
+ name: 'presenterFolder',
239
+ message: 'Select presenter folder:',
240
+ choices: presenterFolders.map((item) => ({ title: item, value: item })),
241
+ initial: 0
242
+ });
243
+
244
+ if (!presenterFolder) {
245
+ process.exitCode = 1;
246
+ return;
247
+ }
248
+
249
+ const schemaFolderPath = path.join(presentationPath, String(presenterFolder), 'schema');
250
+ const schemas = await listSchemaFiles(schemaFolderPath);
251
+ if (!schemas.length) {
252
+ console.error(`❌ No schemas found in ${schemaFolderPath}`);
253
+ process.exitCode = 1;
254
+ return;
255
+ }
256
+
257
+ const { schemaFile } = await prompts({
258
+ type: 'select',
259
+ name: 'schemaFile',
260
+ message: 'Select schema file:',
261
+ choices: schemas.map((item) => ({ title: item, value: item })),
262
+ initial: 0
263
+ });
264
+
265
+ if (!schemaFile) {
266
+ process.exitCode = 1;
267
+ return;
268
+ }
269
+
270
+ const schemaPath = path.join(schemaFolderPath, String(schemaFile));
271
+ const schemaContent = await fs.readFile(schemaPath, 'utf-8');
272
+
273
+ const typeName = extractSchemaTypeName(schemaContent);
274
+ if (!typeName) {
275
+ console.error('❌ Unable to resolve schema generic type.');
276
+ process.exitCode = 1;
277
+ return;
278
+ }
279
+
280
+ const importPath = findTypeImportPath(schemaContent, typeName);
281
+ if (!importPath) {
282
+ console.error(`❌ Unable to find import for type "${typeName}".`);
283
+ process.exitCode = 1;
284
+ return;
285
+ }
286
+
287
+ const aliasMap = await resolveAliasMap();
288
+ const typeFilePath = await resolveImportToFile(schemaPath, importPath, aliasMap);
289
+ if (!typeFilePath) {
290
+ console.error(`❌ Unable to resolve type file path from import "${importPath}".`);
291
+ process.exitCode = 1;
292
+ return;
293
+ }
294
+
295
+ let interfaceBody = await findInterfaceBodyByExportGraph(typeFilePath, typeName);
296
+ if (!interfaceBody) {
297
+ interfaceBody = await findInterfaceBodyByScan(path.dirname(typeFilePath), typeName);
298
+ }
299
+ if (!interfaceBody) {
300
+ console.error(`❌ Interface "${typeName}" not found in ${typeFilePath}`);
301
+ process.exitCode = 1;
302
+ return;
303
+ }
304
+
305
+ const interfaceKeys = extractKeys(interfaceBody);
306
+ if (!interfaceKeys.length) {
307
+ console.log('ℹ️ Interface has no explicit keys to transfer into rules.');
308
+ return;
309
+ }
310
+
311
+ const updatedSchemaContent = updateRulesObject(schemaContent, interfaceKeys);
312
+ if (!updatedSchemaContent) {
313
+ console.error('❌ Could not locate `.rules((rules) => ({}))` block in schema file.');
314
+ process.exitCode = 1;
315
+ return;
316
+ }
317
+
318
+ if (updatedSchemaContent === schemaContent) {
319
+ console.log('ℹ️ Rules already include all keys from type.');
320
+ return;
321
+ }
322
+
323
+ await fs.writeFile(schemaPath, updatedSchemaContent, 'utf-8');
324
+ console.log(`✅ Schema updated from type: ${schemaPath}`);
325
+ }
@@ -0,0 +1,252 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import prompts from 'prompts';
4
+ import { selectContext } from './repositoryModuleShared.js';
5
+
6
+ const isValidIdentifier = (value) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(value);
7
+
8
+ const toPropertyName = (key) => (isValidIdentifier(key) ? key : `'${String(key).replace(/'/g, "\\'")}'`);
9
+
10
+ const getIndent = (level) => '\t'.repeat(level);
11
+
12
+ const normalizeObjectInput = (rawValue) => {
13
+ let input = String(rawValue ?? '').trim();
14
+ if (input.endsWith(';')) {
15
+ input = input.slice(0, -1).trim();
16
+ }
17
+
18
+ const openCurly = (input.match(/\{/g) ?? []).length;
19
+ const closeCurly = (input.match(/\}/g) ?? []).length;
20
+ if (openCurly > closeCurly) {
21
+ input += '}'.repeat(openCurly - closeCurly);
22
+ }
23
+
24
+ return input;
25
+ };
26
+
27
+ const parseObjectInput = (rawValue) => {
28
+ const input = normalizeObjectInput(rawValue);
29
+ if (!input.length) {
30
+ throw new Error('Input is empty');
31
+ }
32
+
33
+ try {
34
+ const parsed = JSON.parse(input);
35
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
36
+ throw new Error('Input root must be an object');
37
+ }
38
+ return parsed;
39
+ } catch {
40
+ // fallback to JS object literal
41
+ }
42
+
43
+ // eslint-disable-next-line no-new-func
44
+ const parsed = new Function(`"use strict"; return (${input});`)();
45
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
46
+ throw new Error('Input root must be an object');
47
+ }
48
+ return parsed;
49
+ };
50
+
51
+ const stringifyType = (value, level = 1) => {
52
+ if (value === null) return 'null';
53
+
54
+ const valueType = typeof value;
55
+ if (valueType === 'string') return 'string';
56
+ if (valueType === 'number') return Number.isFinite(value) ? 'number' : 'unknown';
57
+ if (valueType === 'boolean') return 'boolean';
58
+ if (valueType === 'bigint') return 'bigint';
59
+ if (valueType === 'undefined') return 'undefined';
60
+
61
+ if (Array.isArray(value)) {
62
+ if (!value.length) return 'unknown[]';
63
+
64
+ const itemTypes = Array.from(new Set(value.map((item) => stringifyType(item, level + 1))));
65
+ if (itemTypes.length === 1) {
66
+ const single = itemTypes[0];
67
+ if (single.includes('\n')) return `Array<${single}>`;
68
+ return `${single}[]`;
69
+ }
70
+
71
+ const union = itemTypes.join(' | ');
72
+ if (union.includes('\n')) return `Array<${union}>`;
73
+ return `(${union})[]`;
74
+ }
75
+
76
+ if (valueType === 'object') {
77
+ const entries = Object.entries(value);
78
+ if (!entries.length) return 'Record<string, unknown>';
79
+
80
+ const lines = entries.map(([entryKey, entryValue]) => {
81
+ const propertyType = stringifyType(entryValue, level + 1);
82
+ return `${getIndent(level + 1)}${toPropertyName(entryKey)}: ${propertyType};`;
83
+ });
84
+
85
+ return `{\n${lines.join('\n')}\n${getIndent(level)}}`;
86
+ }
87
+
88
+ return 'unknown';
89
+ };
90
+
91
+ const findInterfaceDeclaration = (content) => {
92
+ const declarationMatch = content.match(/export\s+interface\s+([A-Za-z0-9_]+)\s*\{/);
93
+ if (!declarationMatch || declarationMatch.index === undefined) return null;
94
+
95
+ const name = declarationMatch[1];
96
+ const openBraceIndex = content.indexOf('{', declarationMatch.index);
97
+ if (openBraceIndex === -1) return null;
98
+
99
+ let depth = 0;
100
+ let closeBraceIndex = -1;
101
+ for (let index = openBraceIndex; index < content.length; index += 1) {
102
+ const char = content[index];
103
+ if (char === '{') depth += 1;
104
+ if (char === '}') {
105
+ depth -= 1;
106
+ if (depth === 0) {
107
+ closeBraceIndex = index;
108
+ break;
109
+ }
110
+ }
111
+ }
112
+
113
+ if (closeBraceIndex === -1) return null;
114
+
115
+ const body = content.slice(openBraceIndex + 1, closeBraceIndex);
116
+ return {
117
+ name,
118
+ openBraceIndex,
119
+ closeBraceIndex,
120
+ body
121
+ };
122
+ };
123
+
124
+ const extractExistingRootKeys = (body) => {
125
+ const keys = new Set();
126
+ const keyRegex = /^\s*([A-Za-z_$][A-Za-z0-9_$]*)\??\s*:/gm;
127
+ let match;
128
+ while ((match = keyRegex.exec(body)) !== null) {
129
+ keys.add(match[1]);
130
+ }
131
+ return keys;
132
+ };
133
+
134
+ const listDomains = async (contextName) => {
135
+ const domainRoot = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'domain');
136
+ try {
137
+ const items = await fs.readdir(domainRoot, { withFileTypes: true });
138
+ return items.filter((item) => item.isDirectory()).map((item) => item.name);
139
+ } catch {
140
+ return [];
141
+ }
142
+ };
143
+
144
+ const listModelFiles = async (contextName, domainName) => {
145
+ const modelRoot = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'domain', domainName, 'model');
146
+ try {
147
+ const files = await fs.readdir(modelRoot);
148
+ return files
149
+ .filter((fileName) => fileName.endsWith('.ts') && fileName !== 'index.ts')
150
+ .map((fileName) => ({
151
+ name: fileName.replace(/\.ts$/, ''),
152
+ path: path.join(modelRoot, fileName)
153
+ }));
154
+ } catch {
155
+ return [];
156
+ }
157
+ };
158
+
159
+ export default async function generateTypesJson() {
160
+ const contextName = await selectContext('Select context for model update:');
161
+ if (!contextName) {
162
+ process.exitCode = 1;
163
+ return;
164
+ }
165
+
166
+ const domains = await listDomains(contextName);
167
+ if (!domains.length) {
168
+ console.error(`❌ No domains found in context "${contextName}".`);
169
+ process.exitCode = 1;
170
+ return;
171
+ }
172
+
173
+ const { domainName } = await prompts({
174
+ type: 'select',
175
+ name: 'domainName',
176
+ message: 'Select domain:',
177
+ choices: domains.map((item) => ({ title: item, value: item })),
178
+ initial: 0
179
+ });
180
+
181
+ if (!domainName) {
182
+ process.exitCode = 1;
183
+ return;
184
+ }
185
+
186
+ const models = await listModelFiles(contextName, String(domainName));
187
+ if (!models.length) {
188
+ console.error(`❌ No model files found in domain "${domainName}".`);
189
+ process.exitCode = 1;
190
+ return;
191
+ }
192
+
193
+ const { modelPath } = await prompts({
194
+ type: 'select',
195
+ name: 'modelPath',
196
+ message: 'Select model:',
197
+ choices: models.map((item) => ({ title: item.name, value: item.path })),
198
+ initial: 0
199
+ });
200
+
201
+ if (!modelPath) {
202
+ process.exitCode = 1;
203
+ return;
204
+ }
205
+
206
+ const { rawJson } = await prompts({
207
+ type: 'text',
208
+ name: 'rawJson',
209
+ message: 'Paste JSON or JS object (single line):',
210
+ validate: (value) => {
211
+ try {
212
+ parseObjectInput(value);
213
+ return true;
214
+ } catch {
215
+ return 'Invalid JSON/JS object';
216
+ }
217
+ }
218
+ });
219
+
220
+ if (!rawJson) {
221
+ process.exitCode = 1;
222
+ return;
223
+ }
224
+
225
+ const parsedJson = parseObjectInput(rawJson);
226
+ const content = await fs.readFile(String(modelPath), 'utf-8');
227
+ const interfaceDeclaration = findInterfaceDeclaration(content);
228
+ if (!interfaceDeclaration) {
229
+ console.error(`❌ Unable to parse interface in ${modelPath}`);
230
+ process.exitCode = 1;
231
+ return;
232
+ }
233
+
234
+ const existingKeys = extractExistingRootKeys(interfaceDeclaration.body);
235
+ const generatedLines = Object.entries(parsedJson)
236
+ .filter(([key]) => !existingKeys.has(key))
237
+ .map(([key, value]) => `${getIndent(1)}${toPropertyName(key)}: ${stringifyType(value, 1)};`);
238
+
239
+ if (!generatedLines.length) {
240
+ console.log('ℹ️ No new keys to add. Model already contains all JSON keys.');
241
+ return;
242
+ }
243
+
244
+ const trimmedBody = interfaceDeclaration.body.trimEnd();
245
+ const bodyPrefix = trimmedBody.length ? `${trimmedBody}\n` : '';
246
+ const newBody = `${bodyPrefix}${generatedLines.join('\n')}\n`;
247
+
248
+ const updatedContent = `${content.slice(0, interfaceDeclaration.openBraceIndex + 1)}${newBody}${content.slice(interfaceDeclaration.closeBraceIndex)}`;
249
+ await fs.writeFile(String(modelPath), updatedContent, 'utf-8');
250
+
251
+ console.log(`✅ Model updated: ${modelPath}`);
252
+ }