@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,569 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import prompts from 'prompts';
4
+ import { loadUserConfig } from '../../utils/loadConfig.js';
5
+ import { normalizeContexts } from '../../init/initAliases.js';
6
+ import { toCamelCase, toKebabCase, toPascalCase } from '../../utils/contextUtils.js';
7
+ import { updateIndexTs, writeIfNotExists } from '../../utils/fileUtils.js';
8
+
9
+ const HTTP_METHODS = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'];
10
+
11
+ const normalizeAlias = (value, fallback) => {
12
+ const raw = String(value ?? '').trim();
13
+ if (!raw.length) return fallback;
14
+ return raw.startsWith('$') ? raw : `$${raw}`;
15
+ };
16
+
17
+ export const ensureRepositoryName = (rawName) => {
18
+ const normalized = toPascalCase(String(rawName ?? '').trim() || 'Repository');
19
+ return normalized.endsWith('Repository') ? normalized : `${normalized}Repository`;
20
+ };
21
+
22
+ const RESERVED_IDENTIFIERS = new Set([
23
+ 'break',
24
+ 'case',
25
+ 'catch',
26
+ 'class',
27
+ 'const',
28
+ 'continue',
29
+ 'debugger',
30
+ 'default',
31
+ 'delete',
32
+ 'do',
33
+ 'else',
34
+ 'enum',
35
+ 'export',
36
+ 'extends',
37
+ 'false',
38
+ 'finally',
39
+ 'for',
40
+ 'function',
41
+ 'if',
42
+ 'import',
43
+ 'in',
44
+ 'instanceof',
45
+ 'new',
46
+ 'null',
47
+ 'return',
48
+ 'super',
49
+ 'switch',
50
+ 'this',
51
+ 'throw',
52
+ 'true',
53
+ 'try',
54
+ 'typeof',
55
+ 'var',
56
+ 'void',
57
+ 'while',
58
+ 'with',
59
+ 'as',
60
+ 'implements',
61
+ 'interface',
62
+ 'let',
63
+ 'package',
64
+ 'private',
65
+ 'protected',
66
+ 'public',
67
+ 'static',
68
+ 'yield'
69
+ ]);
70
+
71
+ const toSafeIdentifier = (value) => {
72
+ const normalized = toCamelCase(value || 'repository');
73
+ if (!normalized.length) return 'repository';
74
+ if (RESERVED_IDENTIFIERS.has(normalized)) return `${normalized}Repository`;
75
+ return normalized;
76
+ };
77
+
78
+ export const getRepositoryMeta = (repositoryClassName) => {
79
+ const className = ensureRepositoryName(repositoryClassName);
80
+ const baseName = className.replace(/Repository$/, '') || 'Repository';
81
+ const domainName = toKebabCase(baseName);
82
+ const repositoryInterfaceName = `I${baseName}Repository`;
83
+ const useCasesClassName = `${baseName}UseCases`;
84
+ const repositoryDependencyName = toSafeIdentifier(baseName || 'repository');
85
+
86
+ return {
87
+ className,
88
+ baseName,
89
+ domainName,
90
+ repositoryInterfaceName,
91
+ useCasesClassName,
92
+ repositoryDependencyName
93
+ };
94
+ };
95
+
96
+ export const getConfigState = async () => {
97
+ const config = await loadUserConfig();
98
+ const contexts = normalizeContexts(config.contexts);
99
+ const coreAlias = normalizeAlias(config.coreAlias, '$core');
100
+
101
+ return {
102
+ contexts,
103
+ coreAlias
104
+ };
105
+ };
106
+
107
+ export const selectContext = async (message = 'Select context:') => {
108
+ const { contexts } = await getConfigState();
109
+ if (!contexts.length) {
110
+ console.error('❌ Cannot continue: `contexts` is missing or empty in azure-net.config.ts/js');
111
+ return null;
112
+ }
113
+
114
+ const { context } = await prompts({
115
+ type: 'select',
116
+ name: 'context',
117
+ message,
118
+ choices: contexts.map((item) => ({ title: item.name, value: item.name })),
119
+ initial: 0
120
+ });
121
+
122
+ return context ? String(context) : null;
123
+ };
124
+
125
+ export const resolveContextAlias = (contexts, contextName) => {
126
+ const found = contexts.find((item) => item.name === contextName);
127
+ if (!found) return `$${contextName}`;
128
+ return normalizeAlias(found.alias, `$${contextName}`);
129
+ };
130
+
131
+ export const resolveRepositoriesPath = (contextName) =>
132
+ path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'infrastructure', 'http', 'repositories');
133
+
134
+ export const resolveDatasourcesPath = (contextName) =>
135
+ path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'infrastructure', 'http', 'datasources');
136
+
137
+ export const resolveCoreDatasourcesPath = () => path.join(process.cwd(), 'src', 'core', 'datasource');
138
+
139
+ export const resolveDomainRootPath = (contextName, domainName) =>
140
+ path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'domain', domainName);
141
+
142
+ export const resolveUseCasesPath = (contextName) =>
143
+ path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'application', 'use-cases');
144
+
145
+ export const getAvailableTsNames = async (targetPath) => {
146
+ try {
147
+ const files = await fs.readdir(targetPath);
148
+ return files.filter((item) => item.endsWith('.ts') && item !== 'index.ts').map((item) => item.replace(/\.ts$/, ''));
149
+ } catch {
150
+ return [];
151
+ }
152
+ };
153
+
154
+ export const selectDatasource = async (contextName) => {
155
+ const { contexts, coreAlias } = await getConfigState();
156
+ const contextAlias = resolveContextAlias(contexts, contextName);
157
+ const coreDatasources = await getAvailableTsNames(resolveCoreDatasourcesPath());
158
+ const contextDatasources = await getAvailableTsNames(resolveDatasourcesPath(contextName));
159
+
160
+ const choices = [];
161
+ for (const datasource of coreDatasources) {
162
+ choices.push({
163
+ title: `${datasource} (core)`,
164
+ value: {
165
+ name: datasource,
166
+ source: 'core',
167
+ importPath: `${coreAlias}/datasource`
168
+ }
169
+ });
170
+ }
171
+
172
+ for (const datasource of contextDatasources) {
173
+ choices.push({
174
+ title: `${datasource} (${contextName})`,
175
+ value: {
176
+ name: datasource,
177
+ source: 'context',
178
+ importPath: `${contextAlias}/layers/infrastructure/http/datasources`
179
+ }
180
+ });
181
+ }
182
+
183
+ if (!choices.length) {
184
+ console.error(`❌ No datasources found in core or context "${contextName}".`);
185
+ return null;
186
+ }
187
+
188
+ const { datasource } = await prompts({
189
+ type: 'select',
190
+ name: 'datasource',
191
+ message: 'Select datasource:',
192
+ choices,
193
+ initial: 0
194
+ });
195
+
196
+ return datasource ?? null;
197
+ };
198
+
199
+ const updateDomainIndex = async (domainRootPath) => {
200
+ const exports = [];
201
+
202
+ try {
203
+ await fs.access(path.join(domainRootPath, 'ports'));
204
+ exports.push(`export * from './ports';`);
205
+ } catch {
206
+ // ignore
207
+ }
208
+
209
+ try {
210
+ await fs.access(path.join(domainRootPath, 'model'));
211
+ exports.push(`export * from './model';`);
212
+ } catch {
213
+ // ignore
214
+ }
215
+
216
+ const content = exports.length ? `${exports.join('\n')}\n` : '';
217
+ await fs.mkdir(domainRootPath, { recursive: true });
218
+ await fs.writeFile(path.join(domainRootPath, 'index.ts'), content, 'utf-8');
219
+ };
220
+
221
+ const normalizeTypeName = (rawTypeName) => {
222
+ const normalized = toPascalCase(String(rawTypeName ?? '').trim());
223
+ return normalized || 'IType';
224
+ };
225
+
226
+ export const ensureDomainType = async ({ contextName, domainName, typeName, layer }) => {
227
+ const interfaceName = normalizeTypeName(typeName);
228
+ const domainRootPath = resolveDomainRootPath(contextName, domainName);
229
+ const preferredLayer = layer === 'model' ? 'model' : 'ports';
230
+ const portsTypePath = path.join(domainRootPath, 'ports', `${interfaceName}.ts`);
231
+ const modelTypePath = path.join(domainRootPath, 'model', `${interfaceName}.ts`);
232
+
233
+ try {
234
+ await fs.access(portsTypePath);
235
+ return { interfaceName, layer: 'ports' };
236
+ } catch {
237
+ // ignore
238
+ }
239
+
240
+ try {
241
+ await fs.access(modelTypePath);
242
+ return { interfaceName, layer: 'model' };
243
+ } catch {
244
+ // ignore
245
+ }
246
+
247
+ const layerPath = path.join(domainRootPath, preferredLayer);
248
+ const filePath = path.join(layerPath, `${interfaceName}.ts`);
249
+
250
+ await fs.mkdir(layerPath, { recursive: true });
251
+ await writeIfNotExists(filePath, `export interface ${interfaceName} {\n\t[key: string]: unknown;\n}\n`);
252
+ await updateIndexTs(layerPath);
253
+ await updateDomainIndex(domainRootPath);
254
+
255
+ return { interfaceName, layer: preferredLayer };
256
+ };
257
+
258
+ export const ensureRepositoryInterfaceFile = async ({ contextName, meta, methods }) => {
259
+ const domainRootPath = resolveDomainRootPath(contextName, meta.domainName);
260
+ const portsPath = path.join(domainRootPath, 'ports');
261
+ await fs.mkdir(portsPath, { recursive: true });
262
+
263
+ const resolveTypeLayer = async (typeName) => {
264
+ const portsTypePath = path.join(domainRootPath, 'ports', `${typeName}.ts`);
265
+ const modelTypePath = path.join(domainRootPath, 'model', `${typeName}.ts`);
266
+
267
+ try {
268
+ await fs.access(portsTypePath);
269
+ return 'ports';
270
+ } catch {
271
+ // ignore
272
+ }
273
+
274
+ try {
275
+ await fs.access(modelTypePath);
276
+ return 'model';
277
+ } catch {
278
+ // ignore
279
+ }
280
+
281
+ return null;
282
+ };
283
+
284
+ const importsByLayer = { ports: new Set(), model: new Set() };
285
+ for (const method of methods) {
286
+ const relatedTypes = [method.responseType, method.requestType].filter(Boolean);
287
+ for (const typeName of relatedTypes) {
288
+ // eslint-disable-next-line no-await-in-loop
289
+ const typeLayer = await resolveTypeLayer(typeName);
290
+ if (typeLayer === 'ports') importsByLayer.ports.add(typeName);
291
+ if (typeLayer === 'model') importsByLayer.model.add(typeName);
292
+ }
293
+ }
294
+
295
+ const importLines = [];
296
+ for (const typeName of Array.from(importsByLayer.ports)) {
297
+ importLines.push(`import type { ${typeName} } from './${typeName}.js';`);
298
+ }
299
+ for (const typeName of Array.from(importsByLayer.model)) {
300
+ importLines.push(`import type { ${typeName} } from '../model/${typeName}.js';`);
301
+ }
302
+
303
+ const signatures = methods
304
+ .map((method) => {
305
+ const arg = method.requestType ? `data: ${method.requestType}` : '';
306
+ return `\t${method.name}(${arg}): Promise<${method.responseType}>;`;
307
+ })
308
+ .join('\n');
309
+
310
+ const content = `${importLines.join('\n')}${importLines.length ? '\n\n' : ''}export interface ${meta.repositoryInterfaceName} {\n${signatures ? `${signatures}\n` : ''}}\n`;
311
+ await fs.writeFile(path.join(portsPath, `${meta.repositoryInterfaceName}.ts`), content, 'utf-8');
312
+ await updateIndexTs(portsPath);
313
+ await updateDomainIndex(domainRootPath);
314
+ };
315
+
316
+ const buildHttpCall = (method) => {
317
+ const httpMethod = method.httpMethod.toLowerCase();
318
+ const route = method.route || '/public-route';
319
+ if (!method.requestType) {
320
+ return `http.${httpMethod}('${route}')`;
321
+ }
322
+
323
+ if (httpMethod === 'get' || httpMethod === 'head' || httpMethod === 'options') {
324
+ return `http.${httpMethod}('${route}', { searchParams: query.toSearchParams(data) })`;
325
+ }
326
+
327
+ return `http.${httpMethod}('${route}', { json: data })`;
328
+ };
329
+
330
+ export const buildRepositoryMethodCode = (method) => {
331
+ const arg = method.requestType ? `data: ${method.requestType}` : '';
332
+ const call = buildHttpCall(method);
333
+
334
+ let getInCallback = `http`;
335
+ const httpMethod = String(method.httpMethod ?? '').toLowerCase();
336
+ if (httpMethod === 'get' || httpMethod === 'head' || httpMethod === 'options') {
337
+ getInCallback = `http, query`;
338
+ }
339
+
340
+ return `\tpublic async ${method.name}(${arg}) {\n\t\treturn this.datasource\n\t\t\t.createRequest<${method.responseType}>(({ ${getInCallback} }) => ${call})\n\t\t\t.then((res) => res.get());\n\t}`;
341
+ };
342
+
343
+ export const buildRepositoryContent = ({ meta, contextAlias, datasourceImportPath, datasourceName, methods }) => {
344
+ const importedTypes = new Set([meta.repositoryInterfaceName]);
345
+ for (const method of methods) {
346
+ importedTypes.add(method.responseType);
347
+ if (method.requestType) importedTypes.add(method.requestType);
348
+ }
349
+
350
+ const methodsCode = methods.map((method) => buildRepositoryMethodCode(method)).join('\n\n');
351
+
352
+ return `import { ${datasourceName} } from '${datasourceImportPath}';
353
+ import type { ${Array.from(importedTypes).join(', ')} } from '${contextAlias}/layers/domain/${meta.domainName}';
354
+
355
+ export class ${meta.className} implements ${meta.repositoryInterfaceName} {
356
+ \tconstructor(private readonly datasource: ${datasourceName}) {}
357
+
358
+ ${methodsCode ? `${methodsCode}\n` : ''}
359
+ }
360
+ `;
361
+ };
362
+
363
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
364
+
365
+ const upsertImport = (content, source, names) => {
366
+ const uniqueNames = Array.from(new Set(names)).filter(Boolean);
367
+ if (!uniqueNames.length) return content;
368
+
369
+ const importRegex = new RegExp(`import\\s+(type\\s+)?\\{([^}]+)\\}\\s*from\\s*['"]${escapeRegExp(source)}['"];?`);
370
+ const match = content.match(importRegex);
371
+
372
+ if (match) {
373
+ const existing = match[2]
374
+ .split(',')
375
+ .map((part) => part.trim())
376
+ .filter(Boolean);
377
+ const merged = Array.from(new Set([...existing, ...uniqueNames]));
378
+ return content.replace(importRegex, `import type { ${merged.join(', ')} } from '${source}';`);
379
+ }
380
+
381
+ const lines = content.split('\n');
382
+ let insertIndex = 0;
383
+ while (insertIndex < lines.length && lines[insertIndex].startsWith('import ')) {
384
+ insertIndex += 1;
385
+ }
386
+
387
+ lines.splice(insertIndex, 0, `import type { ${uniqueNames.join(', ')} } from '${source}';`);
388
+ return lines.join('\n');
389
+ };
390
+
391
+ export const appendRepositoryMethod = async ({ repositoryPath, method, contextAlias, domainName }) => {
392
+ let content = await fs.readFile(repositoryPath, 'utf-8');
393
+ const methodExistsRegex = new RegExp(`\\bpublic\\s+async\\s+${escapeRegExp(method.name)}\\s*\\(`);
394
+ if (methodExistsRegex.test(content)) {
395
+ console.warn(`⚠️ Method "${method.name}" already exists in repository, skipped.`);
396
+ return false;
397
+ }
398
+
399
+ content = upsertImport(content, `${contextAlias}/layers/domain/${domainName}`, [method.responseType, method.requestType]);
400
+
401
+ const methodCode = buildRepositoryMethodCode(method);
402
+ const classEnd = content.lastIndexOf('\n}');
403
+ if (classEnd === -1) {
404
+ throw new Error(`Repository class end was not found in ${repositoryPath}`);
405
+ }
406
+
407
+ content = `${content.slice(0, classEnd)}\n\n${methodCode}\n${content.slice(classEnd)}`;
408
+ await fs.writeFile(repositoryPath, content, 'utf-8');
409
+ return true;
410
+ };
411
+
412
+ export const parseRepositoryMethods = (content) => {
413
+ const methods = [];
414
+ const regex =
415
+ /public\s+async\s+(\w+)\(([^)]*)\)\s*\{[\s\S]*?\.createRequest<([^>]+)>\(\(\{ http \}\) =>\s*http\.(get|post|put|delete|head|options|patch)\(/g;
416
+
417
+ let match;
418
+ while ((match = regex.exec(content)) !== null) {
419
+ const name = match[1];
420
+ const params = match[2] ?? '';
421
+ const responseType = (match[3] ?? '').trim();
422
+ const httpMethod = (match[4] ?? 'get').toLowerCase();
423
+ const requestTypeMatch = params.match(/:\s*([A-Za-z0-9_]+)/);
424
+ const requestType = requestTypeMatch?.[1] ?? null;
425
+
426
+ methods.push({
427
+ name,
428
+ httpMethod,
429
+ responseType,
430
+ requestType,
431
+ route: '/public-route'
432
+ });
433
+ }
434
+
435
+ return methods;
436
+ };
437
+
438
+ export const ensureUseCasesFile = async ({ contextName, contextAlias, meta }) => {
439
+ const repositoryInterfacePath = path.join(
440
+ resolveDomainRootPath(contextName, meta.domainName),
441
+ 'ports',
442
+ `${meta.repositoryInterfaceName}.ts`
443
+ );
444
+
445
+ let interfaceContent = '';
446
+ try {
447
+ interfaceContent = await fs.readFile(repositoryInterfacePath, 'utf-8');
448
+ } catch {
449
+ console.error(`❌ Repository interface not found: ${repositoryInterfacePath}`);
450
+ return false;
451
+ }
452
+
453
+ const methods = [];
454
+ const methodRegex = /(\w+)\(([^)]*)\)\s*:\s*Promise<[^>]+>;/g;
455
+ let methodMatch;
456
+ while ((methodMatch = methodRegex.exec(interfaceContent)) !== null) {
457
+ methods.push(methodMatch[1]);
458
+ }
459
+
460
+ const declares = methods.map((methodName) => `\tdeclare ${methodName}: ${meta.repositoryInterfaceName}['${methodName}'];`).join('\n');
461
+ const useCasesPath = resolveUseCasesPath(contextName);
462
+ await fs.mkdir(useCasesPath, { recursive: true });
463
+
464
+ const content = `import { ClassMirror } from '@azure-net/kit';
465
+ import type { ${meta.repositoryInterfaceName} } from '${contextAlias}/layers/domain/${meta.domainName}';
466
+
467
+ export class ${meta.useCasesClassName} extends ClassMirror {
468
+ \tconstructor(private ${meta.repositoryDependencyName}: ${meta.repositoryInterfaceName}) {
469
+ \t\tsuper(${meta.repositoryDependencyName});
470
+ \t}
471
+
472
+ ${declares ? `${declares}\n` : ''}
473
+ }
474
+ `;
475
+
476
+ await fs.writeFile(path.join(useCasesPath, `${meta.useCasesClassName}.ts`), content, 'utf-8');
477
+ await updateIndexTs(useCasesPath);
478
+ return true;
479
+ };
480
+
481
+ export const promptMethodDefinition = async () => {
482
+ const { methodNameRaw } = await prompts({
483
+ type: 'text',
484
+ name: 'methodNameRaw',
485
+ message: 'Method name:',
486
+ validate: (value) => (String(value ?? '').trim().length > 0 ? true : 'Method name is required')
487
+ });
488
+
489
+ const { httpMethod } = await prompts({
490
+ type: 'select',
491
+ name: 'httpMethod',
492
+ message: 'HTTP method:',
493
+ choices: HTTP_METHODS.map((value) => ({ title: value, value })),
494
+ initial: 0
495
+ });
496
+
497
+ const { responseTypeRaw } = await prompts({
498
+ type: 'text',
499
+ name: 'responseTypeRaw',
500
+ message: 'Response type name:',
501
+ validate: (value) => (String(value ?? '').trim().length > 0 ? true : 'Response type is required')
502
+ });
503
+
504
+ const { responseLayer } = await prompts({
505
+ type: 'select',
506
+ name: 'responseLayer',
507
+ message: 'Where to place response type?',
508
+ choices: [
509
+ { title: 'ports', value: 'ports' },
510
+ { title: 'model', value: 'model' }
511
+ ],
512
+ initial: 0
513
+ });
514
+
515
+ const { routeRaw } = await prompts({
516
+ type: 'text',
517
+ name: 'routeRaw',
518
+ message: 'Request path (e.g. /public-route):',
519
+ initial: '/public-route',
520
+ validate: (value) => {
521
+ const raw = String(value ?? '').trim();
522
+ if (!raw.length) return 'Path is required';
523
+ return raw.startsWith('/') ? true : 'Path must start with "/"';
524
+ }
525
+ });
526
+
527
+ const { hasRequest } = await prompts({
528
+ type: 'confirm',
529
+ name: 'hasRequest',
530
+ message: 'Has request payload type?',
531
+ initial: false
532
+ });
533
+
534
+ let requestType = null;
535
+ let requestLayer = null;
536
+
537
+ if (hasRequest) {
538
+ const { requestTypeRaw } = await prompts({
539
+ type: 'text',
540
+ name: 'requestTypeRaw',
541
+ message: 'Request type name:',
542
+ validate: (value) => (String(value ?? '').trim().length > 0 ? true : 'Request type is required')
543
+ });
544
+
545
+ const layerResult = await prompts({
546
+ type: 'select',
547
+ name: 'requestLayer',
548
+ message: 'Where to place request type?',
549
+ choices: [
550
+ { title: 'ports', value: 'ports' },
551
+ { title: 'model', value: 'model' }
552
+ ],
553
+ initial: 0
554
+ });
555
+
556
+ requestType = normalizeTypeName(requestTypeRaw);
557
+ requestLayer = layerResult.requestLayer ?? 'ports';
558
+ }
559
+
560
+ return {
561
+ name: toCamelCase(String(methodNameRaw ?? '').trim() || 'method'),
562
+ httpMethod: String(httpMethod ?? 'get').toLowerCase(),
563
+ responseType: normalizeTypeName(responseTypeRaw),
564
+ responseLayer: responseLayer ?? 'ports',
565
+ route: String(routeRaw ?? '/public-route').trim() || '/public-route',
566
+ requestType,
567
+ requestLayer
568
+ };
569
+ };
@@ -0,0 +1,146 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import prompts from 'prompts';
4
+ import { normalizeContexts } from '../../init/initAliases.js';
5
+ import { loadUserConfig } from '../../utils/loadConfig.js';
6
+ import { toKebabCase, toPascalCase } from '../../utils/contextUtils.js';
7
+ import { updateIndexTs, writeIfNotExists } from '../../utils/fileUtils.js';
8
+
9
+ const parseInterfaceNames = (rawValue) =>
10
+ String(rawValue ?? '')
11
+ .split(',')
12
+ .map((item) => item.trim())
13
+ .filter(Boolean)
14
+ .map((item) => toPascalCase(item))
15
+ .filter(Boolean);
16
+
17
+ const toFileNameFromInterface = (interfaceName) => interfaceName.replace(/^I/, '') || 'Type';
18
+
19
+ const validateInterfaceNames = (rawValue) => {
20
+ const names = parseInterfaceNames(rawValue);
21
+ if (!names.length) return 'Provide at least one interface name';
22
+
23
+ for (const name of names) {
24
+ if (!name.startsWith('I')) {
25
+ return `Interface "${name}" must start with "I"`;
26
+ }
27
+ }
28
+
29
+ return true;
30
+ };
31
+
32
+ const createInterfaceContent = (name) => `export interface ${name} {
33
+ \t[key: string]: unknown;
34
+ }
35
+ `;
36
+
37
+ const writeRootIndex = async (domainPath) => {
38
+ const content = `export * from './model';
39
+ export * from './ports';
40
+ `;
41
+
42
+ await fs.writeFile(path.join(domainPath, 'index.ts'), content, 'utf-8');
43
+ };
44
+
45
+ const selectContext = async () => {
46
+ const config = await loadUserConfig();
47
+ const contexts = normalizeContexts(config.contexts);
48
+ if (!contexts.length) {
49
+ console.error('❌ Cannot generate domain: `contexts` is missing or empty in azure-net.config.ts/js');
50
+ return null;
51
+ }
52
+
53
+ const { context } = await prompts({
54
+ type: 'select',
55
+ name: 'context',
56
+ message: 'Select context:',
57
+ choices: contexts.map((item) => ({ title: item.name, value: item.name })),
58
+ initial: 0
59
+ });
60
+
61
+ return context ? String(context) : null;
62
+ };
63
+
64
+ const createInterfacesInLayer = async (layerPath, names) => {
65
+ for (const interfaceName of names) {
66
+ const fileName = toFileNameFromInterface(interfaceName);
67
+ const filePath = path.join(layerPath, `${fileName}.ts`);
68
+ // eslint-disable-next-line no-await-in-loop
69
+ await writeIfNotExists(filePath, createInterfaceContent(interfaceName));
70
+ }
71
+
72
+ await updateIndexTs(layerPath);
73
+ };
74
+
75
+ export default async function generateDomain(options = {}) {
76
+ const { entityRaw } = await prompts({
77
+ type: 'text',
78
+ name: 'entityRaw',
79
+ message: 'Entity name:',
80
+ initial: options.entityName ?? '',
81
+ validate: (value) => (String(value ?? '').trim().length > 0 ? true : 'Entity name is required')
82
+ });
83
+
84
+ let context = options.contextName ? String(options.contextName) : null;
85
+ if (!context) {
86
+ context = await selectContext();
87
+ }
88
+ if (!context) {
89
+ process.exitCode = 1;
90
+ return null;
91
+ }
92
+
93
+ const entityName = toKebabCase(String(entityRaw ?? '').trim()) || 'entity';
94
+ const domainPath = path.join(process.cwd(), 'src', 'app', context, 'layers', 'domain', entityName);
95
+ const modelPath = path.join(domainPath, 'model');
96
+ const portsPath = path.join(domainPath, 'ports');
97
+
98
+ await fs.mkdir(modelPath, { recursive: true });
99
+ await fs.mkdir(portsPath, { recursive: true });
100
+
101
+ const { shouldCreateModels } = await prompts({
102
+ type: 'confirm',
103
+ name: 'shouldCreateModels',
104
+ message: 'Create model interfaces?',
105
+ initial: true
106
+ });
107
+
108
+ if (shouldCreateModels) {
109
+ const { modelNamesRaw } = await prompts({
110
+ type: 'text',
111
+ name: 'modelNamesRaw',
112
+ message: 'Model interface names (comma separated, start with I):',
113
+ validate: validateInterfaceNames
114
+ });
115
+
116
+ const modelNames = parseInterfaceNames(modelNamesRaw);
117
+ await createInterfacesInLayer(modelPath, modelNames);
118
+ } else {
119
+ await updateIndexTs(modelPath);
120
+ }
121
+
122
+ const { shouldCreatePorts } = await prompts({
123
+ type: 'confirm',
124
+ name: 'shouldCreatePorts',
125
+ message: 'Create port interfaces?',
126
+ initial: true
127
+ });
128
+
129
+ if (shouldCreatePorts) {
130
+ const { portNamesRaw } = await prompts({
131
+ type: 'text',
132
+ name: 'portNamesRaw',
133
+ message: 'Port interface names (comma separated, start with I):',
134
+ validate: validateInterfaceNames
135
+ });
136
+
137
+ const portNames = parseInterfaceNames(portNamesRaw);
138
+ await createInterfacesInLayer(portsPath, portNames);
139
+ } else {
140
+ await updateIndexTs(portsPath);
141
+ }
142
+
143
+ await writeRootIndex(domainPath);
144
+ console.log(`✅ Domain generated: ${domainPath}`);
145
+ return { contextName: context, domainName: entityName, domainPath };
146
+ }