@azure-net/cli 5.0.0 → 5.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@azure-net/cli",
3
- "version": "5.0.0",
3
+ "version": "5.0.1",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "azure-net": "bin/azure-net.js"
@@ -8,353 +8,395 @@ import { loadUserConfig } from '../../utils/loadConfig.js';
8
8
  import { getFoundationConstructImportPath, getFoundationConstructPath, getSharedState } from '../../utils/sharedFoundation.js';
9
9
  const PRIMITIVE_TYPES = new Set(['string', 'number', 'boolean', 'unknown', 'void', 'null', 'undefined', 'bigint', 'symbol', 'never']);
10
10
  const parseProviderInfo = (content) => {
11
- const providerNameMatch = content.match(/export\s+const\s+(\w+)\s*=\s*createBoundaryProvider/);
12
- const providerName = providerNameMatch?.[1] ?? 'ApplicationProvider';
13
- const registerMatch = content.match(/register\s*:\s*\([^)]*\)\s*=>\s*\(\{([\s\S]*?)\}\)/m);
14
- const registerBody = registerMatch?.[1] ?? '';
15
- const keys = [];
16
- const keyRegex = /([A-Za-z_]\w*)\s*:/g;
17
- let keyMatch;
18
- while ((keyMatch = keyRegex.exec(registerBody)) !== null) {
19
- const key = keyMatch[1];
20
- if (key) keys.push(key);
21
- }
22
- return { providerName, registeredKeys: keys };
11
+ const providerNameMatch = content.match(/export\s+const\s+(\w+)\s*=\s*createBoundaryProvider/);
12
+ const providerName = providerNameMatch?.[1] ?? 'ApplicationProvider';
13
+ const registerMatch = content.match(/register\s*:\s*\([^)]*\)\s*=>\s*\(\{([\s\S]*?)\}\)/m);
14
+ const registerBody = registerMatch?.[1] ?? '';
15
+ const keys = [];
16
+ const keyRegex = /([A-Za-z_]\w*)\s*:/g;
17
+ let keyMatch;
18
+ while ((keyMatch = keyRegex.exec(registerBody)) !== null) {
19
+ const key = keyMatch[1];
20
+ if (key)
21
+ keys.push(key);
22
+ }
23
+ return { providerName, registeredKeys: keys };
23
24
  };
24
25
  const parseUseCasesInfo = (content) => {
25
- const interfaceImport = content.match(/import\s+type\s+\{\s*(\w+)\s*\}\s+from\s+['"]([^'"]+)['"]/);
26
- const repositoryInterfaceName = interfaceImport?.[1] ?? null;
27
- const domainImportPath = interfaceImport?.[2] ?? null;
28
- const domainNameMatch = domainImportPath?.match(/\/layers\/domain\/([^'"]+)$/);
29
- const domainName = domainNameMatch?.[1] ?? null;
30
- const methods = [];
31
- const declareRegex = /declare\s+(\w+)\s*:\s*\w+\['\w+'\];/g;
32
- let declareMatch;
33
- while ((declareMatch = declareRegex.exec(content)) !== null) {
34
- const methodName = declareMatch[1];
35
- if (methodName) methods.push(methodName);
36
- }
37
- return { repositoryInterfaceName, domainName, methods };
26
+ const interfaceImport = content.match(/import\s+type\s+\{\s*(\w+)\s*\}\s+from\s+['"]([^'"]+)['"]/);
27
+ const repositoryInterfaceName = interfaceImport?.[1] ?? null;
28
+ const domainImportPath = interfaceImport?.[2] ?? null;
29
+ const domainNameMatch = domainImportPath?.match(/\/layers\/domain\/([^'"]+)$/);
30
+ const domainName = domainNameMatch?.[1] ?? null;
31
+ const methods = [];
32
+ const declareRegex = /declare\s+(\w+)\s*:\s*\w+\['\w+'\];/g;
33
+ let declareMatch;
34
+ while ((declareMatch = declareRegex.exec(content)) !== null) {
35
+ const methodName = declareMatch[1];
36
+ if (methodName)
37
+ methods.push(methodName);
38
+ }
39
+ return { repositoryInterfaceName, domainName, methods };
38
40
  };
39
41
  const parseRepositoryInterfaceMethods = (content) => {
40
- const methods = [];
41
- const regex = /(\w+)\(([^)]*)\)\s*:\s*Promise<([^>]+)>;/g;
42
- let match;
43
- while ((match = regex.exec(content)) !== null) {
44
- const methodName = match[1];
45
- const paramsChunk = match[2];
46
- const responseTypeChunk = match[3];
47
- if (!methodName || paramsChunk === undefined || !responseTypeChunk) continue;
48
- const paramsRaw = paramsChunk.trim();
49
- const params = paramsRaw
50
- ? paramsRaw.split(',').map((part) => {
51
- const [name, ...typeParts] = part.trim().split(':');
52
- return { name: String(name ?? '').trim(), type: typeParts.join(':').trim() };
53
- })
54
- : [];
55
- methods.push({
56
- name: methodName,
57
- params,
58
- responseType: responseTypeChunk.trim()
59
- });
60
- }
61
- return methods;
42
+ const methods = [];
43
+ const regex = /(\w+)\(([^)]*)\)\s*:\s*Promise<([^>]+)>;/g;
44
+ let match;
45
+ while ((match = regex.exec(content)) !== null) {
46
+ const methodName = match[1];
47
+ const paramsChunk = match[2];
48
+ const responseTypeChunk = match[3];
49
+ if (!methodName || paramsChunk === undefined || !responseTypeChunk)
50
+ continue;
51
+ const paramsRaw = paramsChunk.trim();
52
+ const params = paramsRaw
53
+ ? paramsRaw.split(',').map((part) => {
54
+ const [name, ...typeParts] = part.trim().split(':');
55
+ return { name: String(name ?? '').trim(), type: typeParts.join(':').trim() };
56
+ })
57
+ : [];
58
+ methods.push({
59
+ name: methodName,
60
+ params,
61
+ responseType: responseTypeChunk.trim()
62
+ });
63
+ }
64
+ return methods;
62
65
  };
63
66
  const findRepositoryByInterface = async (contextName, repositoryInterfaceName) => {
64
- const repositoriesPath = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'infrastructure', 'http', 'repositories');
65
- try {
66
- const files = await fs.readdir(repositoriesPath);
67
- for (const fileName of files) {
68
- if (!fileName.endsWith('.ts') || fileName === 'index.ts') continue;
69
- const absolute = path.join(repositoriesPath, fileName);
70
- const content = await fs.readFile(absolute, 'utf-8');
71
- if (content.includes(`implements ${repositoryInterfaceName}`)) {
72
- return { filePath: absolute, content };
73
- }
74
- }
75
- return null;
76
- } catch {
77
- return null;
78
- }
67
+ const repositoriesPath = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'infrastructure', 'http', 'repositories');
68
+ try {
69
+ const files = await fs.readdir(repositoriesPath);
70
+ for (const fileName of files) {
71
+ if (!fileName.endsWith('.ts') || fileName === 'index.ts')
72
+ continue;
73
+ const absolute = path.join(repositoriesPath, fileName);
74
+ const content = await fs.readFile(absolute, 'utf-8');
75
+ if (content.includes(`implements ${repositoryInterfaceName}`)) {
76
+ return { filePath: absolute, content };
77
+ }
78
+ }
79
+ return null;
80
+ }
81
+ catch {
82
+ return null;
83
+ }
79
84
  };
80
85
  const parseRepositoryHttpMethods = (content) => {
81
- const methods = new Map();
82
- const regex = /public\s+async\s+(\w+)\([^)]*\)\s*\{([\s\S]*?)\n\t\}/g;
83
- let match;
84
- while ((match = regex.exec(content)) !== null) {
85
- const methodName = match[1];
86
- if (!methodName) continue;
87
- const body = match[2] ?? '';
88
- const httpMatch = body.match(/http\.(get|post|put|delete|head|options|patch)\(/);
89
- if (httpMatch?.[1]) methods.set(methodName, httpMatch[1]);
90
- }
91
- return methods;
86
+ const methods = new Map();
87
+ const regex = /public\s+async\s+(\w+)\([^)]*\)\s*\{([\s\S]*?)\n\t\}/g;
88
+ let match;
89
+ while ((match = regex.exec(content)) !== null) {
90
+ const methodName = match[1];
91
+ if (!methodName)
92
+ continue;
93
+ const body = match[2] ?? '';
94
+ const httpMatch = body.match(/http\.(get|post|put|delete|head|options|patch)\(/);
95
+ if (httpMatch?.[1])
96
+ methods.set(methodName, httpMatch[1]);
97
+ }
98
+ return methods;
92
99
  };
93
100
  const getSharedPresenterFactories = async () => {
94
- const { sharedContext } = await getSharedState();
95
- const presenterPath = getFoundationConstructPath(sharedContext.name, 'presenter');
96
- try {
97
- const files = await fs.readdir(presenterPath);
98
- return files.filter((item) => item.endsWith('.ts') && item !== 'index.ts').map((item) => item.replace(/\.ts$/, ''));
99
- } catch {
100
- return [];
101
- }
101
+ const { sharedContext } = await getSharedState();
102
+ const presenterPath = getFoundationConstructPath(sharedContext.name, 'presenter');
103
+ try {
104
+ const files = await fs.readdir(presenterPath);
105
+ return files.filter((item) => item.endsWith('.ts') && item !== 'index.ts').map((item) => item.replace(/\.ts$/, ''));
106
+ }
107
+ catch {
108
+ return [];
109
+ }
102
110
  };
103
111
  const getSharedSchemaFactories = async () => {
104
- const { sharedContext } = await getSharedState();
105
- const schemaPath = getFoundationConstructPath(sharedContext.name, 'schema');
106
- try {
107
- const files = await fs.readdir(schemaPath);
108
- return files.filter((item) => item.endsWith('.ts') && item !== 'index.ts').map((item) => item.replace(/\.ts$/, ''));
109
- } catch {
110
- return [];
111
- }
112
+ const { sharedContext } = await getSharedState();
113
+ const schemaPath = getFoundationConstructPath(sharedContext.name, 'schema');
114
+ try {
115
+ const files = await fs.readdir(schemaPath);
116
+ return files.filter((item) => item.endsWith('.ts') && item !== 'index.ts').map((item) => item.replace(/\.ts$/, ''));
117
+ }
118
+ catch {
119
+ return [];
120
+ }
112
121
  };
113
122
  const normalizePresenterName = (rawName, fallbackUseCasesName) => {
114
- const fallback = fallbackUseCasesName.replace(/UseCases$/, '') || 'Module';
115
- const source = String(rawName ?? '').trim() || fallback;
116
- const normalized = toPascalCase(source);
117
- return normalized.endsWith('Presenter') ? normalized : `${normalized}Presenter`;
123
+ const fallback = fallbackUseCasesName.replace(/UseCases$/, '') || 'Module';
124
+ const source = String(rawName ?? '').trim() || fallback;
125
+ const normalized = toPascalCase(source);
126
+ return normalized.endsWith('Presenter') ? normalized : `${normalized}Presenter`;
118
127
  };
119
128
  const isPrimitive = (typeName) => PRIMITIVE_TYPES.has(String(typeName ?? '').trim());
120
129
  const normalizeTypeImports = (types) => Array.from(new Set(types.filter((typeName) => !isPrimitive(typeName))));
121
130
  const isPathParamName = (name) => name === 'pathParam' || name === 'path';
131
+ const toTypeFileName = (typeName) => String(typeName ?? '').replace(/^I/, '') || 'Type';
122
132
  const buildMethodInvocation = (method, useCasesName, schemaByMethod) => {
123
- const paramsSignature = method.params.map((item) => `${item.name}: ${item.type}`).join(', ');
124
- const argNames = method.params.map((item) => item.name);
125
- const requestParam = method.params.find((item) => !isPathParamName(item.name));
126
- const schemaInfo = schemaByMethod.get(method.name) ?? null;
127
- const args = argNames.map((argName) => {
128
- if (schemaInfo && requestParam && argName === requestParam.name) {
129
- return `${schemaInfo.constName}.from(${argName}).json()`;
130
- }
131
- return argName;
132
- });
133
- const httpMethod = method.httpMethod;
134
- if (httpMethod === 'get' || httpMethod === 'head' || httpMethod === 'options') {
135
- return `\tconst ${method.name} = (${paramsSignature}) => createAsyncResource(() => ${useCasesName}.${method.name}(${args.join(', ')}));`;
136
- }
137
- const responseType = method.responseType;
138
- const requestType = requestParam?.type ?? null;
139
- let generic = `<${responseType}`;
140
- if (requestType) generic += `, ${requestType}`;
141
- generic += '>';
142
- return `\tconst ${method.name} = async (${paramsSignature}) =>\n\t\tawait createAsyncAction${generic}(() => ${useCasesName}.${method.name}(${args.join(', ')}));`;
133
+ const paramsSignature = method.params.map((item) => `${item.name}: ${item.type}`).join(', ');
134
+ const argNames = method.params.map((item) => item.name);
135
+ const requestParam = method.params.find((item) => !isPathParamName(item.name));
136
+ const schemaInfo = schemaByMethod.get(method.name) ?? null;
137
+ const args = argNames.map((argName) => {
138
+ if (schemaInfo && requestParam && argName === requestParam.name) {
139
+ return `${schemaInfo.constName}.from(${argName}).json()`;
140
+ }
141
+ return argName;
142
+ });
143
+ const httpMethod = method.httpMethod;
144
+ if (httpMethod === 'get' || httpMethod === 'head' || httpMethod === 'options') {
145
+ return `\tconst ${method.name} = (${paramsSignature}) => createAsyncResource(() => ${useCasesName}.${method.name}(${args.join(', ')}));`;
146
+ }
147
+ const responseType = method.responseType;
148
+ const requestType = requestParam?.type ?? null;
149
+ let generic = `<${responseType}`;
150
+ if (requestType)
151
+ generic += `, ${requestType}`;
152
+ generic += '>';
153
+ return `\tconst ${method.name} = async (${paramsSignature}) =>\n\t\tawait createAsyncAction${generic}(() => ${useCasesName}.${method.name}(${args.join(', ')}));`;
143
154
  };
144
155
  const getApplicationProviderFile = async (contextName) => {
145
- const providersPath = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'application', 'providers');
146
- const targetPath = path.join(providersPath, 'ApplicationProvider.ts');
147
- try {
148
- await fs.access(targetPath);
149
- return targetPath;
150
- } catch {
151
- const files = await fs.readdir(providersPath);
152
- const candidate = files.find((item) => item.endsWith('.ts') && item !== 'index.ts');
153
- return candidate ? path.join(providersPath, candidate) : null;
154
- }
156
+ const providersPath = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'application', 'providers');
157
+ const targetPath = path.join(providersPath, 'ApplicationProvider.ts');
158
+ try {
159
+ await fs.access(targetPath);
160
+ return targetPath;
161
+ }
162
+ catch {
163
+ const files = await fs.readdir(providersPath);
164
+ const candidate = files.find((item) => item.endsWith('.ts') && item !== 'index.ts');
165
+ return candidate ? path.join(providersPath, candidate) : null;
166
+ }
167
+ };
168
+ const resolveDomainInterfaceFile = async ({ contextName, domainName, interfaceName }) => {
169
+ const portsPath = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'domain', domainName, 'ports');
170
+ const preferredPath = path.join(portsPath, `${toTypeFileName(interfaceName)}.ts`);
171
+ const legacyPath = path.join(portsPath, `${interfaceName}.ts`);
172
+ for (const candidate of [preferredPath, legacyPath]) {
173
+ try {
174
+ await fs.access(candidate);
175
+ return candidate;
176
+ }
177
+ catch {
178
+ // Try the next candidate.
179
+ }
180
+ }
181
+ try {
182
+ const files = await fs.readdir(portsPath);
183
+ for (const fileName of files) {
184
+ if (!fileName.endsWith('.ts') || fileName === 'index.ts')
185
+ continue;
186
+ const candidate = path.join(portsPath, fileName);
187
+ const content = await fs.readFile(candidate, 'utf-8');
188
+ const escapedName = interfaceName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
189
+ if (new RegExp(`export\\s+interface\\s+${escapedName}\\b`).test(content)) {
190
+ return candidate;
191
+ }
192
+ }
193
+ }
194
+ catch {
195
+ return null;
196
+ }
197
+ return null;
155
198
  };
156
199
  export default async function generatePresenter(options = {}) {
157
- let contextName = options.contextName ? String(options.contextName) : null;
158
- if (!contextName) {
159
- contextName = await selectContext('Select context for presenter:');
160
- }
161
- if (!contextName) {
162
- process.exitCode = 1;
163
- return;
164
- }
165
- const appProviderFile = await getApplicationProviderFile(contextName);
166
- if (!appProviderFile) {
167
- console.error('❌ ApplicationProvider file was not found.');
168
- process.exitCode = 1;
169
- return;
170
- }
171
- const appProviderContent = await fs.readFile(appProviderFile, 'utf-8');
172
- const providerInfo = parseProviderInfo(appProviderContent);
173
- const useCasesPath = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'application', 'use-cases');
174
- let useCasesFiles = [];
175
- try {
176
- useCasesFiles = (await fs.readdir(useCasesPath))
177
- .filter((item) => item.endsWith('.ts') && item !== 'index.ts')
178
- .map((item) => item.replace(/\.ts$/, ''));
179
- } catch {
180
- // ignore
181
- }
182
- const registeredUseCases = useCasesFiles.filter((item) => providerInfo.registeredKeys.includes(item));
183
- if (!registeredUseCases.length) {
184
- console.error('❌ No registered UseCases were found in ApplicationProvider register().');
185
- process.exitCode = 1;
186
- return;
187
- }
188
- let useCasesName = options.useCasesName ? String(options.useCasesName) : '';
189
- if (!useCasesName) {
190
- const { selectedUseCases } = await prompts({
191
- type: 'select',
192
- name: 'selectedUseCases',
193
- message: 'Select UseCases:',
194
- choices: registeredUseCases.map((item) => ({ title: item, value: item })),
195
- initial: 0
196
- });
197
- useCasesName = String(selectedUseCases ?? '');
198
- }
199
- if (!registeredUseCases.includes(useCasesName)) {
200
- console.error(`❌ UseCases "${useCasesName}" is not registered in ApplicationProvider.`);
201
- process.exitCode = 1;
202
- return;
203
- }
204
- const useCasesFile = path.join(useCasesPath, `${useCasesName}.ts`);
205
- const useCasesContent = await fs.readFile(useCasesFile, 'utf-8');
206
- const useCasesInfo = parseUseCasesInfo(useCasesContent);
207
- if (!useCasesInfo.repositoryInterfaceName || !useCasesInfo.domainName) {
208
- console.error('❌ Unable to parse repository interface import from UseCases.');
209
- process.exitCode = 1;
210
- return;
211
- }
212
- const repositoryInfo = await findRepositoryByInterface(contextName, useCasesInfo.repositoryInterfaceName);
213
- if (!repositoryInfo) {
214
- console.error(`❌ Repository implementing ${useCasesInfo.repositoryInterfaceName} was not found.`);
215
- process.exitCode = 1;
216
- return;
217
- }
218
- const repositoryHttpMethods = parseRepositoryHttpMethods(repositoryInfo.content);
219
- const domainPortsInterfacePath = path.join(
220
- process.cwd(),
221
- 'src',
222
- 'app',
223
- contextName,
224
- 'layers',
225
- 'domain',
226
- useCasesInfo.domainName,
227
- 'ports',
228
- `${useCasesInfo.repositoryInterfaceName}.ts`
229
- );
230
- const repositoryInterfaceContent = await fs.readFile(domainPortsInterfacePath, 'utf-8');
231
- const repositoryMethods = parseRepositoryInterfaceMethods(repositoryInterfaceContent).filter((method) =>
232
- useCasesInfo.methods.includes(method.name)
233
- );
234
- const { presenterNameRaw } = await prompts({
235
- type: 'text',
236
- name: 'presenterNameRaw',
237
- message: 'Presenter name (optional):'
238
- });
239
- const presenterName = normalizePresenterName(presenterNameRaw, useCasesName);
240
- const presenterFolder = toKebabCase(presenterName.replace(/Presenter$/, ''));
241
- const presentationPath = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'presentation', presenterFolder);
242
- await fs.mkdir(presentationPath, { recursive: true });
243
- const { contexts, sharedAlias } = await getConfigState();
244
- const contextAlias = resolveContextAlias(contexts, contextName);
245
- const presenterImportPath = getFoundationConstructImportPath(sharedAlias, 'presenter');
246
- const schemaFactoryImportPath = getFoundationConstructImportPath(sharedAlias, 'schema');
247
- let presenterFactory = String((await loadUserConfig()).defaultPresenterFactory ?? '').trim();
248
- let useNativePresenter = false;
249
- if (!presenterFactory) {
250
- const availableFactories = await getSharedPresenterFactories();
251
- const { selectedFactory } = await prompts({
252
- type: 'select',
253
- name: 'selectedFactory',
254
- message: 'Select presenter factory:',
255
- choices: [
256
- ...availableFactories.map((item) => ({ title: item, value: item })),
257
- { title: 'Native createPresenter', value: '__native__' }
258
- ],
259
- initial: 0
260
- });
261
- if (selectedFactory === '__native__') {
262
- useNativePresenter = true;
263
- presenterFactory = 'createPresenter';
264
- } else {
265
- presenterFactory = String(selectedFactory ?? '');
266
- }
267
- }
268
- if (!presenterFactory) {
269
- useNativePresenter = true;
270
- presenterFactory = 'createPresenter';
271
- }
272
- const mutationMethods = repositoryMethods.filter((method) => {
273
- const httpMethod = repositoryHttpMethods.get(method.name) ?? 'get';
274
- return httpMethod !== 'get' && httpMethod !== 'head' && httpMethod !== 'options';
275
- });
276
- let schemaFactory = String((await loadUserConfig()).defaultSchemaFactory ?? '').trim();
277
- let schemaFactoryResolved = false;
278
- const schemaByMethod = new Map();
279
- const schemaImports = [];
280
- let schemaIndexNeeded = false;
281
- if (mutationMethods.length) {
282
- for (const method of mutationMethods) {
283
- const requestParam = method.params.find((item) => !isPathParamName(item.name));
284
- if (!requestParam) continue;
285
- const { shouldCreateSchema } = await prompts({
286
- type: 'confirm',
287
- name: 'shouldCreateSchema',
288
- message: `Create schema for "${method.name}"?`,
289
- initial: false
290
- });
291
- if (!shouldCreateSchema) continue;
292
- if (!schemaFactoryResolved) {
293
- if (!schemaFactory) {
294
- const availableSchemas = await getSharedSchemaFactories();
295
- if (!availableSchemas.length) {
296
- console.error('❌ No schema factories found in shared foundation constructs/schema.');
297
- process.exitCode = 1;
298
- return;
299
- }
300
- const { selectedSchemaFactory } = await prompts({
301
- type: 'select',
302
- name: 'selectedSchemaFactory',
303
- message: 'Select schema factory:',
304
- choices: availableSchemas.map((item) => ({ title: item, value: item })),
305
- initial: 0
306
- });
307
- schemaFactory = String(selectedSchemaFactory ?? '');
308
- }
309
- schemaFactoryResolved = true;
310
- }
311
- const schemaConstName = `${toPascalCase(method.name)}${presenterName}Schema`;
312
- const schemaFileName = `${schemaConstName}.ts`;
313
- const schemaPath = path.join(presentationPath, 'schema');
314
- await fs.mkdir(schemaPath, { recursive: true });
315
- schemaIndexNeeded = true;
316
- const schemaContent = `import { ${schemaFactory} } from '${schemaFactoryImportPath}';
200
+ let contextName = options.contextName ? String(options.contextName) : null;
201
+ if (!contextName) {
202
+ contextName = await selectContext('Select context for presenter:');
203
+ }
204
+ if (!contextName) {
205
+ process.exitCode = 1;
206
+ return;
207
+ }
208
+ const appProviderFile = await getApplicationProviderFile(contextName);
209
+ if (!appProviderFile) {
210
+ console.error('❌ ApplicationProvider file was not found.');
211
+ process.exitCode = 1;
212
+ return;
213
+ }
214
+ const appProviderContent = await fs.readFile(appProviderFile, 'utf-8');
215
+ const providerInfo = parseProviderInfo(appProviderContent);
216
+ const useCasesPath = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'application', 'use-cases');
217
+ let useCasesFiles = [];
218
+ try {
219
+ useCasesFiles = (await fs.readdir(useCasesPath))
220
+ .filter((item) => item.endsWith('.ts') && item !== 'index.ts')
221
+ .map((item) => item.replace(/\.ts$/, ''));
222
+ }
223
+ catch {
224
+ // ignore
225
+ }
226
+ const registeredUseCases = useCasesFiles.filter((item) => providerInfo.registeredKeys.includes(item));
227
+ if (!registeredUseCases.length) {
228
+ console.error('❌ No registered UseCases were found in ApplicationProvider register().');
229
+ process.exitCode = 1;
230
+ return;
231
+ }
232
+ let useCasesName = options.useCasesName ? String(options.useCasesName) : '';
233
+ if (!useCasesName) {
234
+ const { selectedUseCases } = await prompts({
235
+ type: 'select',
236
+ name: 'selectedUseCases',
237
+ message: 'Select UseCases:',
238
+ choices: registeredUseCases.map((item) => ({ title: item, value: item })),
239
+ initial: 0
240
+ });
241
+ useCasesName = String(selectedUseCases ?? '');
242
+ }
243
+ if (!registeredUseCases.includes(useCasesName)) {
244
+ console.error(`❌ UseCases "${useCasesName}" is not registered in ApplicationProvider.`);
245
+ process.exitCode = 1;
246
+ return;
247
+ }
248
+ const useCasesFile = path.join(useCasesPath, `${useCasesName}.ts`);
249
+ const useCasesContent = await fs.readFile(useCasesFile, 'utf-8');
250
+ const useCasesInfo = parseUseCasesInfo(useCasesContent);
251
+ if (!useCasesInfo.repositoryInterfaceName || !useCasesInfo.domainName) {
252
+ console.error('❌ Unable to parse repository interface import from UseCases.');
253
+ process.exitCode = 1;
254
+ return;
255
+ }
256
+ const repositoryInfo = await findRepositoryByInterface(contextName, useCasesInfo.repositoryInterfaceName);
257
+ if (!repositoryInfo) {
258
+ console.error(`❌ Repository implementing ${useCasesInfo.repositoryInterfaceName} was not found.`);
259
+ process.exitCode = 1;
260
+ return;
261
+ }
262
+ const repositoryHttpMethods = parseRepositoryHttpMethods(repositoryInfo.content);
263
+ const domainPortsInterfacePath = await resolveDomainInterfaceFile({
264
+ contextName,
265
+ domainName: useCasesInfo.domainName,
266
+ interfaceName: useCasesInfo.repositoryInterfaceName
267
+ });
268
+ if (!domainPortsInterfacePath) {
269
+ console.error(`❌ Repository interface "${useCasesInfo.repositoryInterfaceName}" was not found in ${path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'domain', useCasesInfo.domainName, 'ports')}`);
270
+ process.exitCode = 1;
271
+ return;
272
+ }
273
+ const repositoryInterfaceContent = await fs.readFile(domainPortsInterfacePath, 'utf-8');
274
+ const repositoryMethods = parseRepositoryInterfaceMethods(repositoryInterfaceContent).filter((method) => useCasesInfo.methods.includes(method.name));
275
+ const { presenterNameRaw } = await prompts({
276
+ type: 'text',
277
+ name: 'presenterNameRaw',
278
+ message: 'Presenter name (optional):'
279
+ });
280
+ const presenterName = normalizePresenterName(presenterNameRaw, useCasesName);
281
+ const presenterFolder = toKebabCase(presenterName.replace(/Presenter$/, ''));
282
+ const presentationPath = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'presentation', presenterFolder);
283
+ await fs.mkdir(presentationPath, { recursive: true });
284
+ const { contexts, sharedAlias } = await getConfigState();
285
+ const contextAlias = resolveContextAlias(contexts, contextName);
286
+ const presenterImportPath = getFoundationConstructImportPath(sharedAlias, 'presenter');
287
+ const schemaFactoryImportPath = getFoundationConstructImportPath(sharedAlias, 'schema');
288
+ let presenterFactory = String((await loadUserConfig()).defaultPresenterFactory ?? '').trim();
289
+ let useNativePresenter = false;
290
+ if (!presenterFactory) {
291
+ const availableFactories = await getSharedPresenterFactories();
292
+ const { selectedFactory } = await prompts({
293
+ type: 'select',
294
+ name: 'selectedFactory',
295
+ message: 'Select presenter factory:',
296
+ choices: [
297
+ ...availableFactories.map((item) => ({ title: item, value: item })),
298
+ { title: 'Native createPresenter', value: '__native__' }
299
+ ],
300
+ initial: 0
301
+ });
302
+ if (selectedFactory === '__native__') {
303
+ useNativePresenter = true;
304
+ presenterFactory = 'createPresenter';
305
+ }
306
+ else {
307
+ presenterFactory = String(selectedFactory ?? '');
308
+ }
309
+ }
310
+ if (!presenterFactory) {
311
+ useNativePresenter = true;
312
+ presenterFactory = 'createPresenter';
313
+ }
314
+ const mutationMethods = repositoryMethods.filter((method) => {
315
+ const httpMethod = repositoryHttpMethods.get(method.name) ?? 'get';
316
+ return httpMethod !== 'get' && httpMethod !== 'head' && httpMethod !== 'options';
317
+ });
318
+ let schemaFactory = String((await loadUserConfig()).defaultSchemaFactory ?? '').trim();
319
+ let schemaFactoryResolved = false;
320
+ const schemaByMethod = new Map();
321
+ const schemaImports = [];
322
+ let schemaIndexNeeded = false;
323
+ if (mutationMethods.length) {
324
+ for (const method of mutationMethods) {
325
+ const requestParam = method.params.find((item) => !isPathParamName(item.name));
326
+ if (!requestParam)
327
+ continue;
328
+ const { shouldCreateSchema } = await prompts({
329
+ type: 'confirm',
330
+ name: 'shouldCreateSchema',
331
+ message: `Create schema for "${method.name}"?`,
332
+ initial: false
333
+ });
334
+ if (!shouldCreateSchema)
335
+ continue;
336
+ if (!schemaFactoryResolved) {
337
+ if (!schemaFactory) {
338
+ const availableSchemas = await getSharedSchemaFactories();
339
+ if (!availableSchemas.length) {
340
+ console.error('❌ No schema factories found in shared foundation constructs/schema.');
341
+ process.exitCode = 1;
342
+ return;
343
+ }
344
+ const { selectedSchemaFactory } = await prompts({
345
+ type: 'select',
346
+ name: 'selectedSchemaFactory',
347
+ message: 'Select schema factory:',
348
+ choices: availableSchemas.map((item) => ({ title: item, value: item })),
349
+ initial: 0
350
+ });
351
+ schemaFactory = String(selectedSchemaFactory ?? '');
352
+ }
353
+ schemaFactoryResolved = true;
354
+ }
355
+ const schemaConstName = `${toPascalCase(method.name)}${presenterName}Schema`;
356
+ const schemaFileName = `${schemaConstName}.ts`;
357
+ const schemaPath = path.join(presentationPath, 'schema');
358
+ await fs.mkdir(schemaPath, { recursive: true });
359
+ schemaIndexNeeded = true;
360
+ const schemaContent = `import { ${schemaFactory} } from '${schemaFactoryImportPath}';
317
361
  import type { ${requestParam.type} } from '${contextAlias}/layers/domain/${useCasesInfo.domainName}';
318
362
 
319
363
  export const ${schemaConstName} = ${schemaFactory}<${requestParam.type}>()
320
364
  \t.rules((rules) => ({}))
321
365
  \t.create();
322
366
  `;
323
- await writeIfNotExists(path.join(schemaPath, schemaFileName), schemaContent);
324
- schemaByMethod.set(method.name, { constName: schemaConstName });
325
- schemaImports.push(schemaConstName);
326
- }
327
- }
328
- if (schemaIndexNeeded) {
329
- await updateIndexTs(path.join(presentationPath, 'schema'));
330
- }
331
- const hasGetLike = repositoryMethods.some((method) => {
332
- const httpMethod = repositoryHttpMethods.get(method.name) ?? 'get';
333
- return httpMethod === 'get' || httpMethod === 'head' || httpMethod === 'options';
334
- });
335
- const hasMutation = repositoryMethods.some((method) => {
336
- const httpMethod = repositoryHttpMethods.get(method.name) ?? 'get';
337
- return httpMethod !== 'get' && httpMethod !== 'head' && httpMethod !== 'options';
338
- });
339
- const helperParams = [hasGetLike ? 'createAsyncResource' : null, hasMutation ? 'createAsyncAction' : null].filter(Boolean).join(', ');
340
- const typeImports = normalizeTypeImports(
341
- repositoryMethods.flatMap((method) => [method.responseType, ...method.params.map((item) => item.type)])
342
- );
343
- const methodsCode = repositoryMethods
344
- .map((method) => {
345
- const httpMethod = repositoryHttpMethods.get(method.name) ?? 'get';
346
- return buildMethodInvocation({ ...method, httpMethod }, useCasesName, schemaByMethod);
347
- })
348
- .join('\n\n');
349
- const factoryImport = useNativePresenter
350
- ? `import { createPresenter } from '@azure-net/kit/delivery';`
351
- : `import { ${presenterFactory} } from '${presenterImportPath}';`;
352
- const schemaImportLine = schemaImports.length ? `import { ${Array.from(new Set(schemaImports)).join(', ')} } from './schema';` : '';
353
- const typeImportLine = typeImports.length
354
- ? `import type { ${typeImports.join(', ')} } from '${contextAlias}/layers/domain/${useCasesInfo.domainName}';`
355
- : '';
356
- const presenterId = `${toPascalCase(contextName)}${presenterName}`;
357
- const presenterContent = `${factoryImport}
367
+ await writeIfNotExists(path.join(schemaPath, schemaFileName), schemaContent);
368
+ schemaByMethod.set(method.name, { constName: schemaConstName });
369
+ schemaImports.push(schemaConstName);
370
+ }
371
+ }
372
+ if (schemaIndexNeeded) {
373
+ await updateIndexTs(path.join(presentationPath, 'schema'));
374
+ }
375
+ const hasGetLike = repositoryMethods.some((method) => {
376
+ const httpMethod = repositoryHttpMethods.get(method.name) ?? 'get';
377
+ return httpMethod === 'get' || httpMethod === 'head' || httpMethod === 'options';
378
+ });
379
+ const hasMutation = repositoryMethods.some((method) => {
380
+ const httpMethod = repositoryHttpMethods.get(method.name) ?? 'get';
381
+ return httpMethod !== 'get' && httpMethod !== 'head' && httpMethod !== 'options';
382
+ });
383
+ const helperParams = [hasGetLike ? 'createAsyncResource' : null, hasMutation ? 'createAsyncAction' : null].filter(Boolean).join(', ');
384
+ const typeImports = normalizeTypeImports(repositoryMethods.flatMap((method) => [method.responseType, ...method.params.map((item) => item.type)]));
385
+ const methodsCode = repositoryMethods
386
+ .map((method) => {
387
+ const httpMethod = repositoryHttpMethods.get(method.name) ?? 'get';
388
+ return buildMethodInvocation({ ...method, httpMethod }, useCasesName, schemaByMethod);
389
+ })
390
+ .join('\n\n');
391
+ const factoryImport = useNativePresenter
392
+ ? `import { createPresenter } from '@azure-net/kit/delivery';`
393
+ : `import { ${presenterFactory} } from '${presenterImportPath}';`;
394
+ const schemaImportLine = schemaImports.length ? `import { ${Array.from(new Set(schemaImports)).join(', ')} } from './schema';` : '';
395
+ const typeImportLine = typeImports.length
396
+ ? `import type { ${typeImports.join(', ')} } from '${contextAlias}/layers/domain/${useCasesInfo.domainName}';`
397
+ : '';
398
+ const presenterId = `${toPascalCase(contextName)}${presenterName}`;
399
+ const presenterContent = `${factoryImport}
358
400
  import { ${providerInfo.providerName} } from '${contextAlias}/layers/application/providers';
359
401
  ${typeImportLine}
360
402
  ${schemaImportLine}
@@ -366,7 +408,7 @@ ${methodsCode ? `${methodsCode}\n` : ''}
366
408
  \treturn { ${repositoryMethods.map((method) => method.name).join(', ')} };
367
409
  });
368
410
  `;
369
- await writeIfNotExists(path.join(presentationPath, `${presenterName}.ts`), presenterContent);
370
- await fs.writeFile(path.join(presentationPath, 'index.ts'), `export * from './${presenterName}';\n`, 'utf-8');
371
- console.log(`✅ Presenter generated: ${path.join(presentationPath, `${presenterName}.ts`)}`);
411
+ await writeIfNotExists(path.join(presentationPath, `${presenterName}.ts`), presenterContent);
412
+ await fs.writeFile(path.join(presentationPath, 'index.ts'), `export * from './${presenterName}';\n`, 'utf-8');
413
+ console.log(`✅ Presenter generated: ${path.join(presentationPath, `${presenterName}.ts`)}`);
372
414
  }
@@ -142,6 +142,7 @@ const isPrimitive = (typeName: string): boolean => PRIMITIVE_TYPES.has(String(ty
142
142
 
143
143
  const normalizeTypeImports = (types: string[]): string[] => Array.from(new Set(types.filter((typeName) => !isPrimitive(typeName))));
144
144
  const isPathParamName = (name: string): boolean => name === 'pathParam' || name === 'path';
145
+ const toTypeFileName = (typeName: string): string => String(typeName ?? '').replace(/^I/, '') || 'Type';
145
146
 
146
147
  const buildMethodInvocation = (
147
148
  method: RepositoryMethod & { httpMethod: string },
@@ -186,6 +187,46 @@ const getApplicationProviderFile = async (contextName: string): Promise<string |
186
187
  }
187
188
  };
188
189
 
190
+ const resolveDomainInterfaceFile = async ({
191
+ contextName,
192
+ domainName,
193
+ interfaceName
194
+ }: {
195
+ contextName: string;
196
+ domainName: string;
197
+ interfaceName: string;
198
+ }): Promise<string | null> => {
199
+ const portsPath = path.join(process.cwd(), 'src', 'app', contextName, 'layers', 'domain', domainName, 'ports');
200
+ const preferredPath = path.join(portsPath, `${toTypeFileName(interfaceName)}.ts`);
201
+ const legacyPath = path.join(portsPath, `${interfaceName}.ts`);
202
+
203
+ for (const candidate of [preferredPath, legacyPath]) {
204
+ try {
205
+ await fs.access(candidate);
206
+ return candidate;
207
+ } catch {
208
+ // Try the next candidate.
209
+ }
210
+ }
211
+
212
+ try {
213
+ const files = await fs.readdir(portsPath);
214
+ for (const fileName of files) {
215
+ if (!fileName.endsWith('.ts') || fileName === 'index.ts') continue;
216
+ const candidate = path.join(portsPath, fileName);
217
+ const content = await fs.readFile(candidate, 'utf-8');
218
+ const escapedName = interfaceName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
219
+ if (new RegExp(`export\\s+interface\\s+${escapedName}\\b`).test(content)) {
220
+ return candidate;
221
+ }
222
+ }
223
+ } catch {
224
+ return null;
225
+ }
226
+
227
+ return null;
228
+ };
229
+
189
230
  type GeneratePresenterOptions = {
190
231
  contextName?: string;
191
232
  useCasesName?: string;
@@ -263,17 +304,27 @@ export default async function generatePresenter(options: GeneratePresenterOption
263
304
  }
264
305
 
265
306
  const repositoryHttpMethods = parseRepositoryHttpMethods(repositoryInfo.content);
266
- const domainPortsInterfacePath = path.join(
267
- process.cwd(),
268
- 'src',
269
- 'app',
307
+ const domainPortsInterfacePath = await resolveDomainInterfaceFile({
270
308
  contextName,
271
- 'layers',
272
- 'domain',
273
- useCasesInfo.domainName,
274
- 'ports',
275
- `${useCasesInfo.repositoryInterfaceName}.ts`
276
- );
309
+ domainName: useCasesInfo.domainName,
310
+ interfaceName: useCasesInfo.repositoryInterfaceName
311
+ });
312
+ if (!domainPortsInterfacePath) {
313
+ console.error(
314
+ `❌ Repository interface "${useCasesInfo.repositoryInterfaceName}" was not found in ${path.join(
315
+ process.cwd(),
316
+ 'src',
317
+ 'app',
318
+ contextName,
319
+ 'layers',
320
+ 'domain',
321
+ useCasesInfo.domainName,
322
+ 'ports'
323
+ )}`
324
+ );
325
+ process.exitCode = 1;
326
+ return;
327
+ }
277
328
  const repositoryInterfaceContent = await fs.readFile(domainPortsInterfacePath, 'utf-8');
278
329
  const repositoryMethods = parseRepositoryInterfaceMethods(repositoryInterfaceContent).filter((method) =>
279
330
  useCasesInfo.methods.includes(method.name)
@@ -5,79 +5,81 @@ import prompts from 'prompts';
5
5
  import { writeIfNotExists, updateIndexTs } from '../utils/fileUtils.js';
6
6
  import { toPascalCase } from '../utils/contextUtils.js';
7
7
  import { getFoundationConstructPath, getSharedState } from '../utils/sharedFoundation.js';
8
- const createPresenterFactoryTemplate = (
9
- factoryName
10
- ) => `import { createErrorHandler, createAsyncHelpers, createPresenterFactory } from '@azure-net/kit/delivery';
8
+ const createPresenterFactoryTemplate = (factoryName) => `import { createAsyncHelpers, createPresenterFactory } from '@azure-net/kit/delivery';
11
9
 
12
- export const AsyncHelpers = createAsyncHelpers({ handler: createErrorHandler() });
10
+ export const AsyncHelpers = createAsyncHelpers();
13
11
 
14
12
  export const ${factoryName} = createPresenterFactory({ ...AsyncHelpers });
15
13
  `;
16
14
  const resolveConfigFile = (cwd) => {
17
- const tsPath = path.join(cwd, 'azure-net.config.ts');
18
- const jsPath = path.join(cwd, 'azure-net.config.js');
19
- if (fsSync.existsSync(tsPath)) {
20
- return { filepath: tsPath, type: 'ts', exists: true, content: fsSync.readFileSync(tsPath, 'utf-8') };
21
- }
22
- if (fsSync.existsSync(jsPath)) {
23
- return { filepath: jsPath, type: 'js', exists: true, content: fsSync.readFileSync(jsPath, 'utf-8') };
24
- }
25
- return { filepath: tsPath, type: 'ts', exists: false, content: '' };
15
+ const tsPath = path.join(cwd, 'azure-net.config.ts');
16
+ const jsPath = path.join(cwd, 'azure-net.config.js');
17
+ if (fsSync.existsSync(tsPath)) {
18
+ return { filepath: tsPath, type: 'ts', exists: true, content: fsSync.readFileSync(tsPath, 'utf-8') };
19
+ }
20
+ if (fsSync.existsSync(jsPath)) {
21
+ return { filepath: jsPath, type: 'js', exists: true, content: fsSync.readFileSync(jsPath, 'utf-8') };
22
+ }
23
+ return { filepath: tsPath, type: 'ts', exists: false, content: '' };
26
24
  };
27
25
  const buildDefaultPresenterFactoryConfigEntry = (factoryName) => {
28
- return `defaultPresenterFactory: '${factoryName}'`;
26
+ return `defaultPresenterFactory: '${factoryName}'`;
29
27
  };
30
28
  const upsertDefaultPresenterFactoryConfig = (content, factoryName) => {
31
- const hasExportDefaultObject = /export\s+default\s*\{[\s\S]*\}\s*;?/.test(content);
32
- const defaultFactoryEntry = buildDefaultPresenterFactoryConfigEntry(factoryName);
33
- if (!hasExportDefaultObject) {
34
- return `export default {\n\t${defaultFactoryEntry}\n};\n`;
35
- }
36
- let nextContent = content;
37
- if (/defaultPresenterFactory\s*:/.test(nextContent)) {
38
- nextContent = nextContent.replace(/defaultPresenterFactory\s*:\s*(\{[\s\S]*?\n\s*\}|['"`][^'"`]+['"`])/m, defaultFactoryEntry);
39
- } else if (/defaultPresenter\s*:/.test(nextContent)) {
40
- nextContent = nextContent.replace(/defaultPresenter\s*:\s*(\{[\s\S]*?\n\s*\}|['"`][^'"`]+['"`])/m, defaultFactoryEntry);
41
- } else {
42
- nextContent = nextContent.replace(/export\s+default\s*\{([\s\S]*)\}\s*;?/, (_full, body) => {
43
- const trimmedRight = body.replace(/\s*$/, '');
44
- if (!trimmedRight.length) {
45
- return `export default {\n\t${defaultFactoryEntry}\n};`;
46
- }
47
- const withComma = trimmedRight.endsWith(',') ? trimmedRight : `${trimmedRight},`;
48
- return `export default {${withComma}\n\t${defaultFactoryEntry}\n};`;
49
- });
50
- }
51
- return nextContent;
29
+ const hasExportDefaultObject = /export\s+default\s*\{[\s\S]*\}\s*;?/.test(content);
30
+ const defaultFactoryEntry = buildDefaultPresenterFactoryConfigEntry(factoryName);
31
+ if (!hasExportDefaultObject) {
32
+ return `export default {\n\t${defaultFactoryEntry}\n};\n`;
33
+ }
34
+ let nextContent = content;
35
+ if (/defaultPresenterFactory\s*:/.test(nextContent)) {
36
+ nextContent = nextContent.replace(/defaultPresenterFactory\s*:\s*(\{[\s\S]*?\n\s*\}|['"`][^'"`]+['"`])/m, defaultFactoryEntry);
37
+ }
38
+ else if (/defaultPresenter\s*:/.test(nextContent)) {
39
+ nextContent = nextContent.replace(/defaultPresenter\s*:\s*(\{[\s\S]*?\n\s*\}|['"`][^'"`]+['"`])/m, defaultFactoryEntry);
40
+ }
41
+ else {
42
+ nextContent = nextContent.replace(/export\s+default\s*\{([\s\S]*)\}\s*;?/, (_full, body) => {
43
+ const trimmedRight = body.replace(/\s*$/, '');
44
+ if (!trimmedRight.length) {
45
+ return `export default {\n\t${defaultFactoryEntry}\n};`;
46
+ }
47
+ const withComma = trimmedRight.endsWith(',') ? trimmedRight : `${trimmedRight},`;
48
+ return `export default {${withComma}\n\t${defaultFactoryEntry}\n};`;
49
+ });
50
+ }
51
+ return nextContent;
52
52
  };
53
53
  export default async function createPresenterFactory() {
54
- const { presenterFactoryNameRaw } = await prompts({
55
- type: 'text',
56
- name: 'presenterFactoryNameRaw',
57
- message: 'Presenter factory name:',
58
- initial: 'AppPresenter'
59
- });
60
- const presenterFactoryName = toPascalCase(String(presenterFactoryNameRaw ?? 'AppPresenter')) || 'AppPresenter';
61
- const { sharedContext } = await getSharedState();
62
- const presenterRootPath = getFoundationConstructPath(sharedContext.name, 'presenter');
63
- const filePath = path.join(presenterRootPath, `${presenterFactoryName}.ts`);
64
- await fs.mkdir(presenterRootPath, { recursive: true });
65
- const created = await writeIfNotExists(filePath, createPresenterFactoryTemplate(presenterFactoryName));
66
- if (!created) {
67
- console.log(`⚠️ Presenter factory "${presenterFactoryName}" already exists. File was not overwritten.`);
68
- } else {
69
- await updateIndexTs(presenterRootPath);
70
- console.log(`✅ Presenter factory created: ${filePath}`);
71
- }
72
- const { useAsDefault } = await prompts({
73
- type: 'confirm',
74
- name: 'useAsDefault',
75
- message: 'Use this presenter factory as default for the project?',
76
- initial: true
77
- });
78
- if (!useAsDefault) return;
79
- const config = resolveConfigFile(process.cwd());
80
- const nextContent = upsertDefaultPresenterFactoryConfig(config.content, presenterFactoryName);
81
- await fs.writeFile(config.filepath, nextContent, 'utf-8');
82
- console.log(`✅ Default presenter factory saved to ${path.basename(config.filepath)}`);
54
+ const { presenterFactoryNameRaw } = await prompts({
55
+ type: 'text',
56
+ name: 'presenterFactoryNameRaw',
57
+ message: 'Presenter factory name:',
58
+ initial: 'AppPresenter'
59
+ });
60
+ const presenterFactoryName = toPascalCase(String(presenterFactoryNameRaw ?? 'AppPresenter')) || 'AppPresenter';
61
+ const { sharedContext } = await getSharedState();
62
+ const presenterRootPath = getFoundationConstructPath(sharedContext.name, 'presenter');
63
+ const filePath = path.join(presenterRootPath, `${presenterFactoryName}.ts`);
64
+ await fs.mkdir(presenterRootPath, { recursive: true });
65
+ const created = await writeIfNotExists(filePath, createPresenterFactoryTemplate(presenterFactoryName));
66
+ if (!created) {
67
+ console.log(`⚠️ Presenter factory "${presenterFactoryName}" already exists. File was not overwritten.`);
68
+ }
69
+ else {
70
+ await updateIndexTs(presenterRootPath);
71
+ console.log(`✅ Presenter factory created: ${filePath}`);
72
+ }
73
+ const { useAsDefault } = await prompts({
74
+ type: 'confirm',
75
+ name: 'useAsDefault',
76
+ message: 'Use this presenter factory as default for the project?',
77
+ initial: true
78
+ });
79
+ if (!useAsDefault)
80
+ return;
81
+ const config = resolveConfigFile(process.cwd());
82
+ const nextContent = upsertDefaultPresenterFactoryConfig(config.content, presenterFactoryName);
83
+ await fs.writeFile(config.filepath, nextContent, 'utf-8');
84
+ console.log(`✅ Default presenter factory saved to ${path.basename(config.filepath)}`);
83
85
  }
@@ -10,9 +10,9 @@ type ConfigPath = 'ts' | 'js';
10
10
 
11
11
  const createPresenterFactoryTemplate = (
12
12
  factoryName: string
13
- ): string => `import { createErrorHandler, createAsyncHelpers, createPresenterFactory } from '@azure-net/kit/delivery';
13
+ ): string => `import { createAsyncHelpers, createPresenterFactory } from '@azure-net/kit/delivery';
14
14
 
15
- export const AsyncHelpers = createAsyncHelpers({ handler: createErrorHandler() });
15
+ export const AsyncHelpers = createAsyncHelpers();
16
16
 
17
17
  export const ${factoryName} = createPresenterFactory({ ...AsyncHelpers });
18
18
  `;