@domain-first/project-structure 2.18.1 → 3.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.
package/dist/index.cjs CHANGED
@@ -1184,76 +1184,6 @@ const addIntegration = async ()=>{
1184
1184
  if (sections.length) console.log(sections.join('\n\n'));
1185
1185
  }
1186
1186
  };
1187
- const initializeUseCase = async ()=>{
1188
- const rootFolderName = await (0, prompts_namespaceObject.input)({
1189
- message: 'Root folder (use "/" for inner folders):',
1190
- default: 'src'
1191
- });
1192
- const domainFirstPackages = await (0, prompts_namespaceObject.checkbox)({
1193
- message: '@domain-first packages',
1194
- choices: [
1195
- '@domain-first/types',
1196
- '@domain-first/errors',
1197
- '@domain-first/handlers',
1198
- '@domain-first/wire',
1199
- '@domain-first/handlers-rest'
1200
- ]
1201
- });
1202
- const defaultPersistenceLayerImplementation = await (0, prompts_namespaceObject.input)({
1203
- message: 'Default persistence layer implementation:'
1204
- });
1205
- const useReact = await (0, prompts_namespaceObject.confirm)({
1206
- message: 'Use React'
1207
- });
1208
- let storybookFramework;
1209
- const withStorybook = useReact ? await (0, prompts_namespaceObject.confirm)({
1210
- message: 'Use Storybook'
1211
- }) : false;
1212
- if (withStorybook) storybookFramework = await (0, prompts_namespaceObject.input)({
1213
- message: 'Storybook framework package:',
1214
- default: '@storybook/react-vite'
1215
- });
1216
- let testingLibrary;
1217
- const withTests = await (0, prompts_namespaceObject.confirm)({
1218
- message: 'Scaffold unit tests'
1219
- });
1220
- if (withTests) testingLibrary = await (0, prompts_namespaceObject.input)({
1221
- message: 'Unit testing library:',
1222
- default: 'vitest'
1223
- });
1224
- ConfigFile.write({
1225
- rootFolder: rootFolderName,
1226
- domainFirstPackages,
1227
- defaultPersistenceLayerImplementation,
1228
- useReact,
1229
- storybookFramework,
1230
- testingLibrary
1231
- });
1232
- const { path } = new ProjectRoot();
1233
- const rootFolder = new Folder(path);
1234
- if (domainFirstPackages.includes('@domain-first/wire')) rootFolder.subitem([
1235
- rootFolderName,
1236
- 'shared',
1237
- 'wiring'
1238
- ]).createFile('env-branched-wire.ts', `
1239
- import { branchedWire } from '@domain-first/wire'
1240
-
1241
- export const envBranchedWire = branchedWire(() => {
1242
- return process.env.NODE_ENV ?? 'development' as 'test' | 'development' | 'production'
1243
- });
1244
- `.trim());
1245
- if (domainFirstPackages.includes('@domain-first/errors')) rootFolder.subitem([
1246
- rootFolderName,
1247
- 'shared'
1248
- ]).subitem([
1249
- 'domain',
1250
- 'errors'
1251
- ]).createFile('index.ts', `
1252
- import { errorNamespace } from '@domain-first/errors'
1253
-
1254
- export const SharedErrors = errorNamespace('shared')
1255
- `.trim());
1256
- };
1257
1187
  class UnknownFormatNaming {
1258
1188
  rawSource;
1259
1189
  camelCase;
@@ -1282,328 +1212,65 @@ class UnknownFormatNaming {
1282
1212
  return this.fileName.replaceAll('-', ' ');
1283
1213
  }
1284
1214
  }
1285
- const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
1286
- class NestedName {
1287
- folders;
1288
- folderName;
1289
- fileName;
1290
- ClassName;
1291
- classNameSegments;
1292
- constructor(rawSource){
1293
- const segments = splitSegments(rawSource);
1294
- this.folders = segments.slice(0, -1);
1295
- this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
1296
- this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
1297
- this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
1298
- this.ClassName = this.classNameSegments.join('');
1299
- }
1300
- static validate = (rawSource)=>{
1301
- const segments = splitSegments(rawSource);
1302
- if (!segments.length) return 'Name is required';
1303
- if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
1304
- return true;
1305
- };
1306
- }
1307
- const ignoredFolders = new Set([
1308
- 'node_modules',
1309
- '.git',
1310
- '.next',
1311
- 'dist',
1312
- 'build',
1313
- 'out',
1314
- 'coverage',
1315
- 'storybook-static'
1316
- ]);
1317
- const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
1318
- const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1319
- const react_module_move_walk = (folder)=>{
1320
- if (!external_node_fs_default().existsSync(folder)) return [];
1321
- return external_node_fs_default().readdirSync(folder, {
1322
- withFileTypes: true
1323
- }).flatMap((entry)=>{
1324
- const entryPath = external_node_path_default().join(folder, entry.name);
1325
- if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : react_module_move_walk(entryPath);
1326
- return entry.isFile() ? [
1327
- entryPath
1328
- ] : [];
1329
- });
1330
- };
1331
- const toPosix = (value)=>value.split(external_node_path_default().sep).join('/');
1332
- const nestedName = (folders, fileBase)=>{
1333
- const prefix = `${folders.join('-')}-`;
1334
- const last = folders.length && fileBase.startsWith(prefix) ? fileBase.slice(prefix.length) : fileBase;
1335
- return [
1336
- ...folders,
1337
- last
1338
- ].join('/');
1339
- };
1340
- const declaredClassName = (filePath, suffix, name)=>{
1341
- const content = external_node_fs_default().readFileSync(filePath, 'utf8');
1342
- const declared = content.match(new RegExp(`export\\s+(?:const|function)\\s+(\\w+)${suffix}\\b`))?.[1];
1343
- return declared ?? new NestedName(name).ClassName;
1344
- };
1345
- const findReactModules = (reactFolder, kind)=>{
1346
- const modules = 'page' === kind ? react_module_move_walk(external_node_path_default().join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
1347
- const folders = external_node_path_default().relative(external_node_path_default().join(reactFolder, 'pages'), external_node_path_default().dirname(file)).split(external_node_path_default().sep).filter((segment)=>!!segment);
1348
- const fileBase = external_node_path_default().basename(file, '-page.tsx');
1349
- const name = nestedName(folders, fileBase);
1350
- return {
1351
- kind,
1352
- name,
1353
- path: file,
1354
- fileBase,
1355
- ClassName: declaredClassName(file, 'Page', name)
1356
- };
1357
- }) : react_module_move_walk(external_node_path_default().join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
1358
- const folder = external_node_path_default().dirname(file);
1359
- const name = toPosix(external_node_path_default().relative(external_node_path_default().join(reactFolder, 'widgets'), folder));
1360
- return {
1361
- kind,
1362
- name,
1363
- path: folder,
1364
- fileBase: external_node_path_default().basename(file, '-widget.tsx'),
1365
- ClassName: declaredClassName(file, 'Widget', name)
1366
- };
1367
- });
1368
- return modules.sort((a, b)=>a.name.localeCompare(b.name));
1215
+ const wiring_layers = [
1216
+ 'domain',
1217
+ 'application',
1218
+ 'infrastructure',
1219
+ 'presentation'
1220
+ ];
1221
+ const visibleLayers = {
1222
+ domain: [
1223
+ 'domain'
1224
+ ],
1225
+ application: [
1226
+ 'domain',
1227
+ 'application'
1228
+ ],
1229
+ infrastructure: [
1230
+ 'domain',
1231
+ 'infrastructure'
1232
+ ],
1233
+ presentation: [
1234
+ 'application',
1235
+ 'presentation'
1236
+ ]
1369
1237
  };
1370
- const react_module_move_targetPath = (reactFolder, module, rawName)=>{
1371
- const { folders, folderName, fileName } = new NestedName(rawName);
1372
- return 'page' === module.kind ? external_node_path_default().join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : external_node_path_default().join(reactFolder, 'widgets', ...folders, folderName);
1238
+ const branchedTypeFiles = {
1239
+ repositories: (fileBase)=>[
1240
+ 'domain',
1241
+ 'aggregates',
1242
+ fileBase.replace(/-repository$/, ''),
1243
+ `${fileBase}.ts`
1244
+ ],
1245
+ commands: (fileBase)=>[
1246
+ 'application',
1247
+ 'commands',
1248
+ 'execution',
1249
+ `${fileBase}.ts`
1250
+ ],
1251
+ queries: (fileBase)=>[
1252
+ 'application',
1253
+ 'queries',
1254
+ 'execution',
1255
+ `${fileBase}.ts`
1256
+ ],
1257
+ 'application-ports': (fileBase)=>[
1258
+ 'application',
1259
+ 'ports',
1260
+ `${fileBase}.ts`
1261
+ ]
1373
1262
  };
1374
- const validateMove = (reactFolder, module, rawName)=>{
1375
- const nameError = NestedName.validate(rawName);
1376
- if (true !== nameError) return nameError;
1377
- const target = react_module_move_targetPath(reactFolder, module, rawName);
1378
- if (target !== module.path && external_node_fs_default().existsSync(target)) return `${external_node_path_default().relative(reactFolder, target)} already exists`;
1379
- if (target.startsWith(`${module.path}${external_node_path_default().sep}`)) return 'A widget cannot be moved into itself';
1380
- return true;
1263
+ const layerOf = (file, contextPath)=>{
1264
+ const [firstSegment] = external_node_path_default().relative(contextPath, file).split(external_node_path_default().sep);
1265
+ return wiring_layers.find((layer)=>layer === firstSegment);
1381
1266
  };
1382
- const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
1383
- const readAliases = (projectRoot)=>{
1384
- const tsconfig = external_node_path_default().join(projectRoot, 'tsconfig.json');
1385
- if (!external_node_fs_default().existsSync(tsconfig)) return [];
1386
- try {
1387
- const { compilerOptions = {} } = JSON.parse(stripJsonComments(external_node_fs_default().readFileSync(tsconfig, 'utf8')));
1388
- const base = external_node_path_default().resolve(projectRoot, compilerOptions.baseUrl ?? '.');
1389
- return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
1390
- prefix: pattern.slice(0, -1),
1391
- target: external_node_path_default().resolve(base, target.slice(0, -1))
1392
- }));
1393
- } catch {
1394
- return [];
1267
+ const namedImports = (source, fromFile)=>{
1268
+ const result = new Map();
1269
+ for (const [, names, importPath] of source.matchAll(/import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g))for (const name of names.split(',')){
1270
+ const cleanName = name.replace(/^\s*type\s+/, '').trim();
1271
+ if (cleanName) result.set(cleanName, `${external_node_path_default().resolve(external_node_path_default().dirname(fromFile), importPath)}.ts`);
1395
1272
  }
1396
- };
1397
- const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
1398
- const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
1399
- const importPaths = (file)=>{
1400
- const withoutExtension = file.replace(codeExtension, '');
1401
- return 'index' === external_node_path_default().basename(withoutExtension) ? [
1402
- withoutExtension,
1403
- external_node_path_default().dirname(withoutExtension)
1404
- ] : [
1405
- withoutExtension
1406
- ];
1407
- };
1408
- const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
1409
- const newName = new NestedName(rawName);
1410
- const target = react_module_move_targetPath(reactFolder, module, rawName);
1411
- const newClassName = newName.ClassName;
1412
- const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
1413
- const oldFolder = 'page' === module.kind ? external_node_path_default().dirname(module.path) : module.path;
1414
- const newFolder = 'page' === module.kind ? external_node_path_default().dirname(target) : target;
1415
- const ownsPath = (candidate)=>'page' === module.kind ? external_node_path_default().dirname(candidate) === oldFolder && new RegExp(`^${escapeRegExp(module.fileBase)}-page(?:\\.|$)`).test(external_node_path_default().basename(candidate)) : candidate === oldFolder || candidate.startsWith(`${oldFolder}${external_node_path_default().sep}`);
1416
- const movedPath = (candidate)=>{
1417
- if (!ownsPath(candidate)) return;
1418
- const segments = external_node_path_default().relative(oldFolder, candidate).split(external_node_path_default().sep);
1419
- const last = segments.length - 1;
1420
- segments[last] = renameFile(segments[last]);
1421
- return external_node_path_default().join(newFolder, ...segments);
1422
- };
1423
- const moduleFiles = 'page' === module.kind ? external_node_fs_default().readdirSync(oldFolder).map((name)=>external_node_path_default().join(oldFolder, name)).filter((file)=>external_node_fs_default().statSync(file).isFile() && ownsPath(file)) : react_module_move_walk(oldFolder);
1424
- const moves = new Map(moduleFiles.map((file)=>[
1425
- file,
1426
- movedPath(file) ?? file
1427
- ]));
1428
- const aliases = readAliases(projectRoot);
1429
- const resolve = (specifier, fromFile)=>{
1430
- if (specifier.startsWith('.')) return {
1431
- resolved: external_node_path_default().resolve(external_node_path_default().dirname(fromFile), specifier),
1432
- alias: void 0
1433
- };
1434
- const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
1435
- return alias ? {
1436
- resolved: external_node_path_default().resolve(alias.target, specifier.slice(alias.prefix.length)),
1437
- alias
1438
- } : void 0;
1439
- };
1440
- const specifierFor = (fromFile, toPath, alias)=>{
1441
- const aliased = alias && toPosix(external_node_path_default().relative(alias.target, toPath));
1442
- if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
1443
- const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toPath));
1444
- return relative.startsWith('.') ? relative : `./${relative}`;
1445
- };
1446
- const suffixes = 'page' === module.kind ? 'Page' : 'Widget|UIModel';
1447
- const classPattern = new RegExp(`(?<![\\w$])(use)?${escapeRegExp(module.ClassName)}(?=${suffixes})`, 'g');
1448
- const oldTitle = `Widgets/${module.name.split('/').map((segment)=>new NestedName(segment).ClassName).join('/')}`;
1449
- const titlePattern = new RegExp(`(['"\`])${escapeRegExp(oldTitle)}\\1`, 'g');
1450
- const newTitle = [
1451
- 'Widgets',
1452
- ...newName.classNameSegments
1453
- ].join('/');
1454
- const codeFiles = new Map(react_module_move_walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
1455
- file,
1456
- external_node_fs_default().readFileSync(file, 'utf8')
1457
- ]));
1458
- const barrels = new Set();
1459
- const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
1460
- for(let found = true; found;){
1461
- found = false;
1462
- for (const [file, content] of codeFiles){
1463
- if (moves.has(file) || isBarrel(file)) continue;
1464
- const reExportsModule = [
1465
- ...content.matchAll(reExportPattern)
1466
- ].some(([, , specifier])=>{
1467
- const resolution = resolve(specifier, file);
1468
- return !!resolution && (!!movedPath(resolution.resolved) || isBarrel(resolution.resolved));
1469
- });
1470
- if (reExportsModule) {
1471
- for (const importPath of importPaths(file))barrels.add(importPath);
1472
- found = true;
1473
- }
1474
- }
1475
- }
1476
- const rewrite = (content, oldFile, newFile)=>{
1477
- let referencesModule = false;
1478
- const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
1479
- const resolution = resolve(specifier, oldFile);
1480
- if (!resolution) return match;
1481
- const moved = movedPath(resolution.resolved);
1482
- if (moved || isBarrel(resolution.resolved)) referencesModule = true;
1483
- if (!moved && oldFile === newFile) return match;
1484
- const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
1485
- return `${keyword}${quote}${next}${quote}`;
1486
- });
1487
- if (!referencesModule && !moves.has(oldFile)) return content;
1488
- const renamed = rewritten.replace(classPattern, (_, use = '')=>`${use}${newClassName}`);
1489
- return moves.has(oldFile) && 'widget' === module.kind ? renamed.replace(titlePattern, (_, quote)=>`${quote}${newTitle}${quote}`) : renamed;
1490
- };
1491
- for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new File(file).moveTo(newFile, reactFolder);
1492
- const updated = [];
1493
- for (const [file, content] of codeFiles){
1494
- const newFile = moves.get(file);
1495
- const next = rewrite(content, file, newFile ?? file);
1496
- if (newFile && newFile !== file) {
1497
- new File(newFile).data = next;
1498
- new File(file).delete(reactFolder);
1499
- } else if (next !== content) {
1500
- new File(file).update(next);
1501
- if (!newFile) updated.push(file);
1502
- }
1503
- }
1504
- return {
1505
- moves: [
1506
- ...moves
1507
- ].filter(([from, to])=>from !== to),
1508
- updated
1509
- };
1510
- };
1511
- const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
1512
- const reactFolder = presentationReactFolder.path;
1513
- const modules = findReactModules(reactFolder, kind);
1514
- if (!modules.length) return void console.log(`No ${kind}s generated by df-ps were found.`);
1515
- const module = await (0, prompts_namespaceObject.select)({
1516
- message: 'page' === kind ? 'Page:' : 'Widget:',
1517
- choices: modules.map((value)=>({
1518
- name: value.name,
1519
- value,
1520
- description: external_node_path_default().relative(reactFolder, value.path)
1521
- }))
1522
- });
1523
- const name = await (0, prompts_namespaceObject.input)({
1524
- message: 'New name (folders split by "/"):',
1525
- default: module.name,
1526
- validate: (value)=>validateMove(reactFolder, module, value)
1527
- });
1528
- const root = new ProjectRoot().path;
1529
- const { moves, updated } = moveReactModule(root, reactFolder, module, name);
1530
- if (!moves.length && !updated.length) return void console.log('Nothing to change.');
1531
- const relative = (file)=>external_node_path_default().relative(root, file);
1532
- console.log([
1533
- 'Files to move:',
1534
- ...moves.map(([from, to])=>` ${relative(from)} → ${relative(to)}`),
1535
- ...updated.length ? [
1536
- 'Files with updated imports:',
1537
- ...updated.map((file)=>` ${relative(file)}`)
1538
- ] : []
1539
- ].join('\n'));
1540
- if (!await (0, prompts_namespaceObject.confirm)({
1541
- message: 'Apply?',
1542
- default: true
1543
- })) {
1544
- discardPendingChanges();
1545
- console.log('Cancelled: nothing was written.');
1546
- }
1547
- };
1548
- const wiring_layers = [
1549
- 'domain',
1550
- 'application',
1551
- 'infrastructure',
1552
- 'presentation'
1553
- ];
1554
- const visibleLayers = {
1555
- domain: [
1556
- 'domain'
1557
- ],
1558
- application: [
1559
- 'domain',
1560
- 'application'
1561
- ],
1562
- infrastructure: [
1563
- 'domain',
1564
- 'infrastructure'
1565
- ],
1566
- presentation: [
1567
- 'application',
1568
- 'presentation'
1569
- ]
1570
- };
1571
- const branchedTypeFiles = {
1572
- repositories: (fileBase)=>[
1573
- 'domain',
1574
- 'aggregates',
1575
- fileBase.replace(/-repository$/, ''),
1576
- `${fileBase}.ts`
1577
- ],
1578
- commands: (fileBase)=>[
1579
- 'application',
1580
- 'commands',
1581
- 'execution',
1582
- `${fileBase}.ts`
1583
- ],
1584
- queries: (fileBase)=>[
1585
- 'application',
1586
- 'queries',
1587
- 'execution',
1588
- `${fileBase}.ts`
1589
- ],
1590
- 'application-ports': (fileBase)=>[
1591
- 'application',
1592
- 'ports',
1593
- `${fileBase}.ts`
1594
- ]
1595
- };
1596
- const layerOf = (file, contextPath)=>{
1597
- const [firstSegment] = external_node_path_default().relative(contextPath, file).split(external_node_path_default().sep);
1598
- return wiring_layers.find((layer)=>layer === firstSegment);
1599
- };
1600
- const namedImports = (source, fromFile)=>{
1601
- const result = new Map();
1602
- for (const [, names, importPath] of source.matchAll(/import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g))for (const name of names.split(',')){
1603
- const cleanName = name.replace(/^\s*type\s+/, '').trim();
1604
- if (cleanName) result.set(cleanName, `${external_node_path_default().resolve(external_node_path_default().dirname(fromFile), importPath)}.ts`);
1605
- }
1606
- return result;
1273
+ return result;
1607
1274
  };
1608
1275
  const isEndpointWire = (wiringRelativePath)=>wiringRelativePath.startsWith([
1609
1276
  'presentation',
@@ -1691,7 +1358,6 @@ const kindRules = {
1691
1358
  };
1692
1359
  const wiring_implementationType = (consumer, implementation)=>consumer.branched ? external_node_path_default().basename(external_node_path_default().dirname(implementation.file)) : void 0;
1693
1360
  const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && `-${external_node_path_default().basename(candidate.typeFile, '.ts')}-`.includes(`-${implementation}-`);
1694
- const isSuggestedEndpointGenerator = (candidate)=>candidate.typeName.toLowerCase().includes('endpoint');
1695
1361
  const canDependOn = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && (kindRules[consumer.kind]?.(candidate, consumer) ?? true);
1696
1362
  const availableDependencies = (consumer, implementation, candidates)=>{
1697
1363
  const wired = wiredDependencyNames(new File(consumer.wireFile).data, implementation.className);
@@ -1906,78 +1572,504 @@ const contextAndSharedModules = (boundedContextFolder)=>{
1906
1572
  }))
1907
1573
  ];
1908
1574
  };
1909
- const promptDependencies = async (boundedContextFolder, consumer, implementations = consumer.implementations)=>{
1910
- const options = contextAndSharedModules(boundedContextFolder);
1911
- let asked = false;
1912
- for (const implementation of implementations){
1913
- const available = availableDependencies(consumer, implementation, options.map((x)=>x.module));
1914
- const candidates = options.filter((x)=>available.includes(x.module));
1915
- if (!candidates.length) continue;
1916
- asked = true;
1917
- const type = wiring_implementationType(consumer, implementation);
1918
- const suggested = type ? candidates.filter((x)=>isSuggestedFor(x.module, type)) : [];
1919
- const dependencies = await (0, prompts_namespaceObject.checkbox)({
1920
- message: consumer.branched ? `Dependencies for ${implementation.className}:` : 'Dependencies:',
1921
- choices: groupedChoices(candidates, suggested),
1922
- pageSize: groupedPageSize,
1923
- loop: false
1575
+ const promptDependencies = async (boundedContextFolder, consumer, implementations = consumer.implementations)=>{
1576
+ const options = contextAndSharedModules(boundedContextFolder);
1577
+ let asked = false;
1578
+ for (const implementation of implementations){
1579
+ const available = availableDependencies(consumer, implementation, options.map((x)=>x.module));
1580
+ const candidates = options.filter((x)=>available.includes(x.module));
1581
+ if (!candidates.length) continue;
1582
+ asked = true;
1583
+ const type = wiring_implementationType(consumer, implementation);
1584
+ const suggested = type ? candidates.filter((x)=>isSuggestedFor(x.module, type)) : [];
1585
+ const dependencies = await (0, prompts_namespaceObject.checkbox)({
1586
+ message: consumer.branched ? `Dependencies for ${implementation.className}:` : 'Dependencies:',
1587
+ choices: groupedChoices(candidates, suggested),
1588
+ pageSize: groupedPageSize,
1589
+ loop: false
1590
+ });
1591
+ if (dependencies.length) wireDependencies(consumer, implementation, dependencies.map((x)=>x.module));
1592
+ }
1593
+ return asked;
1594
+ };
1595
+ const wireNewModuleDependencies = async (boundedContextFolder, wireFile)=>{
1596
+ const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
1597
+ if (consumer) await promptDependencies(boundedContextFolder, consumer);
1598
+ };
1599
+ const wireDependency = async (boundedContextFolder)=>{
1600
+ const modules = findWiredModules(boundedContextFolder.path);
1601
+ if (!modules.length) return void console.log('No wired modules here yet.');
1602
+ const { module: consumer, implementation } = await (0, prompts_namespaceObject.select)({
1603
+ message: 'Module:',
1604
+ choices: groupedChoices(modules.flatMap((x)=>x.implementations.map((implementation)=>{
1605
+ const type = wiring_implementationType(x, implementation);
1606
+ return {
1607
+ module: x,
1608
+ label: type ? `${x.typeName} (${type})` : x.typeName,
1609
+ implementation
1610
+ };
1611
+ }))),
1612
+ pageSize: groupedPageSize,
1613
+ loop: false
1614
+ });
1615
+ if (!await promptDependencies(boundedContextFolder, consumer, [
1616
+ implementation
1617
+ ])) console.log('No dependencies available for this module.');
1618
+ };
1619
+ const promptEndpointHandler = async (boundedContextFolder)=>{
1620
+ const handlers = findWiredModules(boundedContextFolder.path).filter((x)=>[
1621
+ 'queries',
1622
+ 'commands',
1623
+ 'use-cases'
1624
+ ].includes(x.kind)).map((x)=>({
1625
+ module: x,
1626
+ label: x.typeName
1627
+ }));
1628
+ return handlers.length ? (await (0, prompts_namespaceObject.select)({
1629
+ message: 'Handler:',
1630
+ choices: groupedChoices(handlers),
1631
+ pageSize: groupedPageSize,
1632
+ loop: false
1633
+ })).module : void 0;
1634
+ };
1635
+ const createPresentationService = (boundedContextFolder, name, classFile)=>{
1636
+ const naming = new UnknownFormatNaming(name);
1637
+ const className = `${naming.ClassName}PresentationService`;
1638
+ const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
1639
+ const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
1640
+ const wiringFolder = boundedContextFolder.subitem([
1641
+ 'wiring',
1642
+ 'presentation-services'
1643
+ ]);
1644
+ const presentationServicesFolder = boundedContextFolder.subitem([
1645
+ 'presentation',
1646
+ 'services'
1647
+ ]);
1648
+ presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.ts`, classFile?.(className) ?? `
1649
+ export class ${className} {
1650
+
1651
+ }
1652
+ `.trim());
1653
+ if (scaffoldUnitTests) presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.spec.ts`, `
1654
+ import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
1655
+ ${withWiring ? `import { type ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'
1656
+ import { wire${naming.ClassName}PresentationService } from '../../wiring/presentation-services/wire-${naming.fileName}-presentation-service'` : `import { ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'`}
1657
+
1658
+ let ${naming.variableName}PresentationService: ${naming.ClassName}PresentationService
1659
+
1660
+ beforeEach(() => {
1661
+ ${naming.variableName}PresentationService = ${withWiring ? `wire${naming.ClassName}PresentationService()` : `new ${naming.ClassName}PresentationService()`}
1662
+ })
1663
+
1664
+ describe('${naming.withSpaces}', () => {
1665
+ test('can be ${withWiring ? 'wired' : 'created'}', () => {
1666
+ expect(${naming.variableName}PresentationService).toBeDefined()
1667
+ })
1668
+ })
1669
+ `.trim());
1670
+ if (withWiring) return wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
1671
+ import { wireClass } from '@domain-first/wire'
1672
+ import { ${naming.ClassName}PresentationService } from '../../presentation/services/${naming.fileName}-presentation-service'
1673
+
1674
+ export const wire${naming.ClassName}PresentationService = wireClass(
1675
+ ${naming.ClassName}PresentationService,
1676
+ []
1677
+ )
1678
+ `.trim());
1679
+ };
1680
+ const scaffoldNewPresentationService = async (boundedContextFolder)=>{
1681
+ const name = await (0, prompts_namespaceObject.input)({
1682
+ message: 'Name: '
1683
+ });
1684
+ const wireFile = createPresentationService(boundedContextFolder, name);
1685
+ if (wireFile) await wireNewModuleDependencies(boundedContextFolder, wireFile);
1686
+ };
1687
+ const rest_endpoint_generator_name = 'rest-endpoint-generator';
1688
+ const scaffoldRestEndpointGenerator = (sharedFolder)=>createPresentationService(sharedFolder, rest_endpoint_generator_name, (className)=>`
1689
+ import {
1690
+ type Adapter,
1691
+ type EndpointGenerator,
1692
+ type ErrorStatuses,
1693
+ createEndpoint,
1694
+ InputMappingError,
1695
+ RequestParsingError
1696
+ } from '@domain-first/handlers-rest'
1697
+
1698
+ export class ${className} {
1699
+ get withoutGuards(): EndpointGenerator {
1700
+ return createEndpoint({
1701
+ errorStatuses: {
1702
+ 400: {
1703
+ checks: this.invalidRequestChecks,
1704
+ description: 'Invalid request'
1705
+ }
1706
+ }
1707
+ })(this.adapter) as EndpointGenerator
1708
+ }
1709
+
1710
+ /**
1711
+ * Default checks of an invalid request, to spread into a generator's
1712
+ * own checks.
1713
+ */
1714
+ private get invalidRequestChecks(): ErrorStatuses[number]['checks'] {
1715
+ return [RequestParsingError.is, InputMappingError.is]
1716
+ }
1717
+
1718
+ /**
1719
+ * The adapter of your HTTP framework.
1720
+ */
1721
+ private get adapter(): Adapter<any[], any> {
1722
+ throw new Error('REST adapter is not set')
1723
+ }
1724
+ }
1725
+ `.trim());
1726
+ const findRestEndpointGenerator = (sharedFolder)=>{
1727
+ const typeFile = external_node_path_default().join(sharedFolder.path, 'presentation', 'services', `${rest_endpoint_generator_name}-presentation-service.ts`);
1728
+ if (!new File(typeFile).exists) return;
1729
+ return {
1730
+ typeName: 'RestEndpointGeneratorPresentationService',
1731
+ typeFile,
1732
+ wireName: 'wireRestEndpointGeneratorPresentationService',
1733
+ wireFile: external_node_path_default().join(sharedFolder.path, 'wiring', 'presentation-services', `wire-${rest_endpoint_generator_name}-presentation-service.ts`)
1734
+ };
1735
+ };
1736
+ const initializeUseCase = async ()=>{
1737
+ const rootFolderName = await (0, prompts_namespaceObject.input)({
1738
+ message: 'Root folder (use "/" for inner folders):',
1739
+ default: 'src'
1740
+ });
1741
+ const domainFirstPackages = await (0, prompts_namespaceObject.checkbox)({
1742
+ message: '@domain-first packages',
1743
+ choices: [
1744
+ '@domain-first/types',
1745
+ '@domain-first/errors',
1746
+ '@domain-first/handlers',
1747
+ '@domain-first/wire',
1748
+ '@domain-first/handlers-rest'
1749
+ ]
1750
+ });
1751
+ const defaultPersistenceLayerImplementation = await (0, prompts_namespaceObject.input)({
1752
+ message: 'Default persistence layer implementation:'
1753
+ });
1754
+ const useReact = await (0, prompts_namespaceObject.confirm)({
1755
+ message: 'Use React'
1756
+ });
1757
+ let storybookFramework;
1758
+ const withStorybook = useReact ? await (0, prompts_namespaceObject.confirm)({
1759
+ message: 'Use Storybook'
1760
+ }) : false;
1761
+ if (withStorybook) storybookFramework = await (0, prompts_namespaceObject.input)({
1762
+ message: 'Storybook framework package:',
1763
+ default: '@storybook/react-vite'
1764
+ });
1765
+ let testingLibrary;
1766
+ const withTests = await (0, prompts_namespaceObject.confirm)({
1767
+ message: 'Scaffold unit tests'
1768
+ });
1769
+ if (withTests) testingLibrary = await (0, prompts_namespaceObject.input)({
1770
+ message: 'Unit testing library:',
1771
+ default: 'vitest'
1772
+ });
1773
+ ConfigFile.write({
1774
+ rootFolder: rootFolderName,
1775
+ domainFirstPackages,
1776
+ defaultPersistenceLayerImplementation,
1777
+ useReact,
1778
+ storybookFramework,
1779
+ testingLibrary
1780
+ });
1781
+ const { path } = new ProjectRoot();
1782
+ const rootFolder = new Folder(path);
1783
+ if (domainFirstPackages.includes('@domain-first/wire')) rootFolder.subitem([
1784
+ rootFolderName,
1785
+ 'shared',
1786
+ 'wiring'
1787
+ ]).createFile('env-branched-wire.ts', `
1788
+ import { branchedWire } from '@domain-first/wire'
1789
+
1790
+ export const envBranchedWire = branchedWire(() => {
1791
+ return process.env.NODE_ENV ?? 'development' as 'test' | 'development' | 'production'
1792
+ });
1793
+ `.trim());
1794
+ if (domainFirstPackages.includes('@domain-first/errors')) rootFolder.subitem([
1795
+ rootFolderName,
1796
+ 'shared'
1797
+ ]).subitem([
1798
+ 'domain',
1799
+ 'errors'
1800
+ ]).createFile('index.ts', `
1801
+ import { errorNamespace } from '@domain-first/errors'
1802
+
1803
+ export const SharedErrors = errorNamespace('shared')
1804
+ `.trim());
1805
+ if (domainFirstPackages.includes('@domain-first/handlers-rest')) scaffoldRestEndpointGenerator(rootFolder.subitem([
1806
+ rootFolderName,
1807
+ 'shared'
1808
+ ]));
1809
+ };
1810
+ const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
1811
+ class NestedName {
1812
+ folders;
1813
+ folderName;
1814
+ fileName;
1815
+ ClassName;
1816
+ classNameSegments;
1817
+ constructor(rawSource){
1818
+ const segments = splitSegments(rawSource);
1819
+ this.folders = segments.slice(0, -1);
1820
+ this.folderName = new UnknownFormatNaming(segments.at(-1) ?? '').fileName;
1821
+ this.fileName = segments.map((segment)=>new UnknownFormatNaming(segment).fileName).join('-');
1822
+ this.classNameSegments = segments.map((segment)=>new UnknownFormatNaming(segment).ClassName);
1823
+ this.ClassName = this.classNameSegments.join('');
1824
+ }
1825
+ static validate = (rawSource)=>{
1826
+ const segments = splitSegments(rawSource);
1827
+ if (!segments.length) return 'Name is required';
1828
+ if (segments.some((segment)=>'.' === segment || '..' === segment)) return 'Use a path relative to the folder, without "." or ".."';
1829
+ return true;
1830
+ };
1831
+ }
1832
+ const ignoredFolders = new Set([
1833
+ 'node_modules',
1834
+ '.git',
1835
+ '.next',
1836
+ 'dist',
1837
+ 'build',
1838
+ 'out',
1839
+ 'coverage',
1840
+ 'storybook-static'
1841
+ ]);
1842
+ const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
1843
+ const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1844
+ const react_module_move_walk = (folder)=>{
1845
+ if (!external_node_fs_default().existsSync(folder)) return [];
1846
+ return external_node_fs_default().readdirSync(folder, {
1847
+ withFileTypes: true
1848
+ }).flatMap((entry)=>{
1849
+ const entryPath = external_node_path_default().join(folder, entry.name);
1850
+ if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : react_module_move_walk(entryPath);
1851
+ return entry.isFile() ? [
1852
+ entryPath
1853
+ ] : [];
1854
+ });
1855
+ };
1856
+ const toPosix = (value)=>value.split(external_node_path_default().sep).join('/');
1857
+ const nestedName = (folders, fileBase)=>{
1858
+ const prefix = `${folders.join('-')}-`;
1859
+ const last = folders.length && fileBase.startsWith(prefix) ? fileBase.slice(prefix.length) : fileBase;
1860
+ return [
1861
+ ...folders,
1862
+ last
1863
+ ].join('/');
1864
+ };
1865
+ const declaredClassName = (filePath, suffix, name)=>{
1866
+ const content = external_node_fs_default().readFileSync(filePath, 'utf8');
1867
+ const declared = content.match(new RegExp(`export\\s+(?:const|function)\\s+(\\w+)${suffix}\\b`))?.[1];
1868
+ return declared ?? new NestedName(name).ClassName;
1869
+ };
1870
+ const findReactModules = (reactFolder, kind)=>{
1871
+ const modules = 'page' === kind ? react_module_move_walk(external_node_path_default().join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
1872
+ const folders = external_node_path_default().relative(external_node_path_default().join(reactFolder, 'pages'), external_node_path_default().dirname(file)).split(external_node_path_default().sep).filter((segment)=>!!segment);
1873
+ const fileBase = external_node_path_default().basename(file, '-page.tsx');
1874
+ const name = nestedName(folders, fileBase);
1875
+ return {
1876
+ kind,
1877
+ name,
1878
+ path: file,
1879
+ fileBase,
1880
+ ClassName: declaredClassName(file, 'Page', name)
1881
+ };
1882
+ }) : react_module_move_walk(external_node_path_default().join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
1883
+ const folder = external_node_path_default().dirname(file);
1884
+ const name = toPosix(external_node_path_default().relative(external_node_path_default().join(reactFolder, 'widgets'), folder));
1885
+ return {
1886
+ kind,
1887
+ name,
1888
+ path: folder,
1889
+ fileBase: external_node_path_default().basename(file, '-widget.tsx'),
1890
+ ClassName: declaredClassName(file, 'Widget', name)
1891
+ };
1892
+ });
1893
+ return modules.sort((a, b)=>a.name.localeCompare(b.name));
1894
+ };
1895
+ const react_module_move_targetPath = (reactFolder, module, rawName)=>{
1896
+ const { folders, folderName, fileName } = new NestedName(rawName);
1897
+ return 'page' === module.kind ? external_node_path_default().join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : external_node_path_default().join(reactFolder, 'widgets', ...folders, folderName);
1898
+ };
1899
+ const validateMove = (reactFolder, module, rawName)=>{
1900
+ const nameError = NestedName.validate(rawName);
1901
+ if (true !== nameError) return nameError;
1902
+ const target = react_module_move_targetPath(reactFolder, module, rawName);
1903
+ if (target !== module.path && external_node_fs_default().existsSync(target)) return `${external_node_path_default().relative(reactFolder, target)} already exists`;
1904
+ if (target.startsWith(`${module.path}${external_node_path_default().sep}`)) return 'A widget cannot be moved into itself';
1905
+ return true;
1906
+ };
1907
+ const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
1908
+ const readAliases = (projectRoot)=>{
1909
+ const tsconfig = external_node_path_default().join(projectRoot, 'tsconfig.json');
1910
+ if (!external_node_fs_default().existsSync(tsconfig)) return [];
1911
+ try {
1912
+ const { compilerOptions = {} } = JSON.parse(stripJsonComments(external_node_fs_default().readFileSync(tsconfig, 'utf8')));
1913
+ const base = external_node_path_default().resolve(projectRoot, compilerOptions.baseUrl ?? '.');
1914
+ return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
1915
+ prefix: pattern.slice(0, -1),
1916
+ target: external_node_path_default().resolve(base, target.slice(0, -1))
1917
+ }));
1918
+ } catch {
1919
+ return [];
1920
+ }
1921
+ };
1922
+ const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
1923
+ const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
1924
+ const importPaths = (file)=>{
1925
+ const withoutExtension = file.replace(codeExtension, '');
1926
+ return 'index' === external_node_path_default().basename(withoutExtension) ? [
1927
+ withoutExtension,
1928
+ external_node_path_default().dirname(withoutExtension)
1929
+ ] : [
1930
+ withoutExtension
1931
+ ];
1932
+ };
1933
+ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
1934
+ const newName = new NestedName(rawName);
1935
+ const target = react_module_move_targetPath(reactFolder, module, rawName);
1936
+ const newClassName = newName.ClassName;
1937
+ const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
1938
+ const oldFolder = 'page' === module.kind ? external_node_path_default().dirname(module.path) : module.path;
1939
+ const newFolder = 'page' === module.kind ? external_node_path_default().dirname(target) : target;
1940
+ const ownsPath = (candidate)=>'page' === module.kind ? external_node_path_default().dirname(candidate) === oldFolder && new RegExp(`^${escapeRegExp(module.fileBase)}-page(?:\\.|$)`).test(external_node_path_default().basename(candidate)) : candidate === oldFolder || candidate.startsWith(`${oldFolder}${external_node_path_default().sep}`);
1941
+ const movedPath = (candidate)=>{
1942
+ if (!ownsPath(candidate)) return;
1943
+ const segments = external_node_path_default().relative(oldFolder, candidate).split(external_node_path_default().sep);
1944
+ const last = segments.length - 1;
1945
+ segments[last] = renameFile(segments[last]);
1946
+ return external_node_path_default().join(newFolder, ...segments);
1947
+ };
1948
+ const moduleFiles = 'page' === module.kind ? external_node_fs_default().readdirSync(oldFolder).map((name)=>external_node_path_default().join(oldFolder, name)).filter((file)=>external_node_fs_default().statSync(file).isFile() && ownsPath(file)) : react_module_move_walk(oldFolder);
1949
+ const moves = new Map(moduleFiles.map((file)=>[
1950
+ file,
1951
+ movedPath(file) ?? file
1952
+ ]));
1953
+ const aliases = readAliases(projectRoot);
1954
+ const resolve = (specifier, fromFile)=>{
1955
+ if (specifier.startsWith('.')) return {
1956
+ resolved: external_node_path_default().resolve(external_node_path_default().dirname(fromFile), specifier),
1957
+ alias: void 0
1958
+ };
1959
+ const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
1960
+ return alias ? {
1961
+ resolved: external_node_path_default().resolve(alias.target, specifier.slice(alias.prefix.length)),
1962
+ alias
1963
+ } : void 0;
1964
+ };
1965
+ const specifierFor = (fromFile, toPath, alias)=>{
1966
+ const aliased = alias && toPosix(external_node_path_default().relative(alias.target, toPath));
1967
+ if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
1968
+ const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toPath));
1969
+ return relative.startsWith('.') ? relative : `./${relative}`;
1970
+ };
1971
+ const suffixes = 'page' === module.kind ? 'Page' : 'Widget|UIModel';
1972
+ const classPattern = new RegExp(`(?<![\\w$])(use)?${escapeRegExp(module.ClassName)}(?=${suffixes})`, 'g');
1973
+ const oldTitle = `Widgets/${module.name.split('/').map((segment)=>new NestedName(segment).ClassName).join('/')}`;
1974
+ const titlePattern = new RegExp(`(['"\`])${escapeRegExp(oldTitle)}\\1`, 'g');
1975
+ const newTitle = [
1976
+ 'Widgets',
1977
+ ...newName.classNameSegments
1978
+ ].join('/');
1979
+ const codeFiles = new Map(react_module_move_walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
1980
+ file,
1981
+ external_node_fs_default().readFileSync(file, 'utf8')
1982
+ ]));
1983
+ const barrels = new Set();
1984
+ const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
1985
+ for(let found = true; found;){
1986
+ found = false;
1987
+ for (const [file, content] of codeFiles){
1988
+ if (moves.has(file) || isBarrel(file)) continue;
1989
+ const reExportsModule = [
1990
+ ...content.matchAll(reExportPattern)
1991
+ ].some(([, , specifier])=>{
1992
+ const resolution = resolve(specifier, file);
1993
+ return !!resolution && (!!movedPath(resolution.resolved) || isBarrel(resolution.resolved));
1994
+ });
1995
+ if (reExportsModule) {
1996
+ for (const importPath of importPaths(file))barrels.add(importPath);
1997
+ found = true;
1998
+ }
1999
+ }
2000
+ }
2001
+ const rewrite = (content, oldFile, newFile)=>{
2002
+ let referencesModule = false;
2003
+ const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
2004
+ const resolution = resolve(specifier, oldFile);
2005
+ if (!resolution) return match;
2006
+ const moved = movedPath(resolution.resolved);
2007
+ if (moved || isBarrel(resolution.resolved)) referencesModule = true;
2008
+ if (!moved && oldFile === newFile) return match;
2009
+ const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
2010
+ return `${keyword}${quote}${next}${quote}`;
1924
2011
  });
1925
- if (dependencies.length) wireDependencies(consumer, implementation, dependencies.map((x)=>x.module));
2012
+ if (!referencesModule && !moves.has(oldFile)) return content;
2013
+ const renamed = rewritten.replace(classPattern, (_, use = '')=>`${use}${newClassName}`);
2014
+ return moves.has(oldFile) && 'widget' === module.kind ? renamed.replace(titlePattern, (_, quote)=>`${quote}${newTitle}${quote}`) : renamed;
2015
+ };
2016
+ for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new File(file).moveTo(newFile, reactFolder);
2017
+ const updated = [];
2018
+ for (const [file, content] of codeFiles){
2019
+ const newFile = moves.get(file);
2020
+ const next = rewrite(content, file, newFile ?? file);
2021
+ if (newFile && newFile !== file) {
2022
+ new File(newFile).data = next;
2023
+ new File(file).delete(reactFolder);
2024
+ } else if (next !== content) {
2025
+ new File(file).update(next);
2026
+ if (!newFile) updated.push(file);
2027
+ }
1926
2028
  }
1927
- return asked;
1928
- };
1929
- const wireNewModuleDependencies = async (boundedContextFolder, wireFile)=>{
1930
- const consumer = readWiredModule(wireFile.path, boundedContextFolder.path);
1931
- if (consumer) await promptDependencies(boundedContextFolder, consumer);
1932
- };
1933
- const wireDependency = async (boundedContextFolder)=>{
1934
- const modules = findWiredModules(boundedContextFolder.path);
1935
- if (!modules.length) return void console.log('No wired modules here yet.');
1936
- const { module: consumer, implementation } = await (0, prompts_namespaceObject.select)({
1937
- message: 'Module:',
1938
- choices: groupedChoices(modules.flatMap((x)=>x.implementations.map((implementation)=>{
1939
- const type = wiring_implementationType(x, implementation);
1940
- return {
1941
- module: x,
1942
- label: type ? `${x.typeName} (${type})` : x.typeName,
1943
- implementation
1944
- };
1945
- }))),
1946
- pageSize: groupedPageSize,
1947
- loop: false
1948
- });
1949
- if (!await promptDependencies(boundedContextFolder, consumer, [
1950
- implementation
1951
- ])) console.log('No dependencies available for this module.');
1952
- };
1953
- const promptEndpointDependencies = async (boundedContextFolder)=>{
1954
- const options = contextAndSharedModules(boundedContextFolder);
1955
- const generators = options.filter((x)=>'presentation-services' === x.module.kind);
1956
- const handlers = findWiredModules(boundedContextFolder.path).filter((x)=>[
1957
- 'queries',
1958
- 'commands',
1959
- 'use-cases'
1960
- ].includes(x.kind)).map((x)=>({
1961
- module: x,
1962
- label: x.typeName
1963
- }));
1964
- const endpointGenerator = generators.length ? (await (0, prompts_namespaceObject.select)({
1965
- message: 'Endpoint generator:',
1966
- choices: groupedChoices(generators, generators.filter((x)=>isSuggestedEndpointGenerator(x.module))),
1967
- pageSize: groupedPageSize,
1968
- loop: false
1969
- })).module : void 0;
1970
- const handler = handlers.length ? (await (0, prompts_namespaceObject.select)({
1971
- message: 'Handler:',
1972
- choices: groupedChoices(handlers),
1973
- pageSize: groupedPageSize,
1974
- loop: false
1975
- })).module : void 0;
1976
2029
  return {
1977
- endpointGenerator,
1978
- handler
2030
+ moves: [
2031
+ ...moves
2032
+ ].filter(([from, to])=>from !== to),
2033
+ updated
1979
2034
  };
1980
2035
  };
2036
+ const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
2037
+ const reactFolder = presentationReactFolder.path;
2038
+ const modules = findReactModules(reactFolder, kind);
2039
+ if (!modules.length) return void console.log(`No ${kind}s generated by df-ps were found.`);
2040
+ const module = await (0, prompts_namespaceObject.select)({
2041
+ message: 'page' === kind ? 'Page:' : 'Widget:',
2042
+ choices: modules.map((value)=>({
2043
+ name: value.name,
2044
+ value,
2045
+ description: external_node_path_default().relative(reactFolder, value.path)
2046
+ }))
2047
+ });
2048
+ const name = await (0, prompts_namespaceObject.input)({
2049
+ message: 'New name (folders split by "/"):',
2050
+ default: module.name,
2051
+ validate: (value)=>validateMove(reactFolder, module, value)
2052
+ });
2053
+ const root = new ProjectRoot().path;
2054
+ const { moves, updated } = moveReactModule(root, reactFolder, module, name);
2055
+ if (!moves.length && !updated.length) return void console.log('Nothing to change.');
2056
+ const relative = (file)=>external_node_path_default().relative(root, file);
2057
+ console.log([
2058
+ 'Files to move:',
2059
+ ...moves.map(([from, to])=>` ${relative(from)} → ${relative(to)}`),
2060
+ ...updated.length ? [
2061
+ 'Files with updated imports:',
2062
+ ...updated.map((file)=>` ${relative(file)}`)
2063
+ ] : []
2064
+ ].join('\n'));
2065
+ if (!await (0, prompts_namespaceObject.confirm)({
2066
+ message: 'Apply?',
2067
+ default: true
2068
+ })) {
2069
+ discardPendingChanges();
2070
+ console.log('Cancelled: nothing was written.');
2071
+ }
2072
+ };
1981
2073
  const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
1982
2074
  const aggregateName = await (0, prompts_namespaceObject.input)({
1983
2075
  message: 'Aggregate name:'
@@ -2674,10 +2766,12 @@ export const restHandlers = restWires.map(x => x().handle)
2674
2766
  'endpoint'
2675
2767
  ].map((segment)=>segment.startsWith(':') ? pathParameterAsName(segment) : new UnknownFormatNaming(segment).ClassName).join('');
2676
2768
  const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
2677
- const { endpointGenerator, handler } = withWiring ? await promptEndpointDependencies(boundedContextFolder) : {
2678
- endpointGenerator: void 0,
2679
- handler: void 0
2680
- };
2769
+ const endpointGenerator = findRestEndpointGenerator(boundedContextFolder.subitem([
2770
+ '..',
2771
+ '..',
2772
+ 'shared'
2773
+ ]));
2774
+ const handler = withWiring ? await promptEndpointHandler(boundedContextFolder) : void 0;
2681
2775
  const endpointFile = external_node_path_default().join(endpointFolder.path, `${method.toUpperCase()}.ts`);
2682
2776
  endpointFolder.createFile(`${method.toUpperCase()}.ts`, `
2683
2777
  ${endpointGenerator ? `import type { ${endpointGenerator.typeName} } from '${relativeImport(endpointFile, endpointGenerator.typeFile)}'` : "import { EndpointGenerator } from '@domain-first/handlers-rest'"}${handler ? `
@@ -2774,56 +2868,6 @@ export const wire${naming.ClassName}InfrastructureService = wireClass(
2774
2868
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2775
2869
  }
2776
2870
  };
2777
- const scaffoldNewPresentationService = async (boundedContextFolder)=>{
2778
- const name = await (0, prompts_namespaceObject.input)({
2779
- message: 'Name: '
2780
- });
2781
- const naming = new UnknownFormatNaming(name);
2782
- const scaffoldUnitTests = Boolean(ConfigFile.Instance.data.testingLibrary);
2783
- const withWiring = ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire');
2784
- const wiringFolder = boundedContextFolder.subitem([
2785
- 'wiring',
2786
- 'presentation-services'
2787
- ]);
2788
- const presentationServicesFolder = boundedContextFolder.subitem([
2789
- 'presentation',
2790
- 'services'
2791
- ]);
2792
- presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.ts`, `
2793
- export class ${naming.ClassName}PresentationService {
2794
-
2795
- }
2796
- `.trim());
2797
- if (scaffoldUnitTests) presentationServicesFolder.createFile(`${naming.fileName}-presentation-service.spec.ts`, `
2798
- import { describe, test, expect, beforeEach } from '${ConfigFile.Instance.data.testingLibrary}'
2799
- ${withWiring ? `import { type ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'
2800
- import { wire${naming.ClassName}PresentationService } from '../../wiring/presentation-services/wire-${naming.fileName}-presentation-service'` : `import { ${naming.ClassName}PresentationService } from './${naming.fileName}-presentation-service'`}
2801
-
2802
- let ${naming.variableName}PresentationService: ${naming.ClassName}PresentationService
2803
-
2804
- beforeEach(() => {
2805
- ${naming.variableName}PresentationService = ${withWiring ? `wire${naming.ClassName}PresentationService()` : `new ${naming.ClassName}PresentationService()`}
2806
- })
2807
-
2808
- describe('${naming.withSpaces}', () => {
2809
- test('can be ${withWiring ? 'wired' : 'created'}', () => {
2810
- expect(${naming.variableName}PresentationService).toBeDefined()
2811
- })
2812
- })
2813
- `.trim());
2814
- if (withWiring) {
2815
- const wireFile = wiringFolder.createFile(`wire-${naming.fileName}-presentation-service.ts`, `
2816
- import { wireClass } from '@domain-first/wire'
2817
- import { ${naming.ClassName}PresentationService } from '../../presentation/services/${naming.fileName}-presentation-service'
2818
-
2819
- export const wire${naming.ClassName}PresentationService = wireClass(
2820
- ${naming.ClassName}PresentationService,
2821
- []
2822
- )
2823
- `.trim());
2824
- await wireNewModuleDependencies(boundedContextFolder, wireFile);
2825
- }
2826
- };
2827
2871
  const scaffoldNewQuery = async (boundedContextFolder)=>{
2828
2872
  const queriesFolder = boundedContextFolder.subitem([
2829
2873
  'application',