@domain-first/project-structure 7.0.0 → 7.1.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/dist/index.cjs CHANGED
@@ -421,7 +421,7 @@ const layerOf = (file, contextPath)=>{
421
421
  const [firstSegment] = external_node_path_default().relative(contextPath, file).split(external_node_path_default().sep);
422
422
  return wiring_layers.find((layer)=>layer === firstSegment);
423
423
  };
424
- const namedImports = (source, fromFile)=>{
424
+ const wiring_namedImports = (source, fromFile)=>{
425
425
  const result = new Map();
426
426
  for (const [, names, importPath] of source.matchAll(/import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g))for (const name of names.split(',')){
427
427
  const cleanName = name.replace(/^\s*type\s+/, '').trim();
@@ -455,7 +455,7 @@ const readWiredModule = (wireFile, contextPath)=>{
455
455
  const exportMatch = new RegExp(`export\\s+const\\s+${wireName}\\s*=\\s*`).exec(source);
456
456
  if (!exportMatch) return;
457
457
  const branched = source.slice(exportMatch.index + exportMatch[0].length).startsWith('envBranchedWire(');
458
- const imports = namedImports(source, wireFile);
458
+ const imports = wiring_namedImports(source, wireFile);
459
459
  const implementations = wiredClassNames(source, wireName, exportMatch.index + exportMatch[0].length, branched).flatMap((className)=>{
460
460
  const file = imports.get(className);
461
461
  return file ? [
@@ -698,8 +698,26 @@ const in_memory_db_wireFile = ()=>new file_system_File(in_memory_db_sharedFolder
698
698
  ]);
699
699
  const in_memory_db_inMemoryDbScaffolded = ()=>serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
700
700
  const usesInMemoryDb = (implementationType)=>Boolean(config_file_ConfigFile.Instance.data.withInMemoryDb) && new unknown_format_naming_UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && in_memory_db_inMemoryDbScaffolded();
701
+ const uncountableEndings = [
702
+ 'data',
703
+ 'info',
704
+ 'usage',
705
+ 'feedback',
706
+ 'media',
707
+ 'ware',
708
+ 'equipment',
709
+ 'information',
710
+ 'knowledge',
711
+ 'traffic',
712
+ 'telemetry',
713
+ 'analytics',
714
+ 'series'
715
+ ];
716
+ const uncountable = new RegExp(`(${uncountableEndings.join('|')})$`, 'i');
701
717
  const plural = (word)=>{
718
+ if (uncountable.test(word)) return word;
702
719
  if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
720
+ if (/(^|[^aeiou]|qu)[aeiou]z$/i.test(word)) return `${word}zes`;
703
721
  if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
704
722
  return `${word}s`;
705
723
  };
@@ -738,6 +756,7 @@ const passInMemoryDb = (specFile, implementationName)=>{
738
756
  specFile.update(addImport(specFile.data, `import { ${in_memory_db_className} } from '${wiring_relativeImport(specFile.path, serviceFile().path)}'`).replace(`new ${implementationName}()`, `new ${implementationName}(new ${in_memory_db_className}())`));
739
757
  };
740
758
  require("node:module");
759
+ const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
741
760
  const kindTitles = {
742
761
  repositories: 'Repositories',
743
762
  'domain-services': 'Domain services',
@@ -921,7 +940,7 @@ const rest_endpoint_generator_findRestEndpointGenerator = (sharedFolder)=>{
921
940
  };
922
941
  };
923
942
  require("node:util");
924
- new Set([
943
+ const ignoredFolders = new Set([
925
944
  'node_modules',
926
945
  '.git',
927
946
  '.next',
@@ -931,6 +950,549 @@ new Set([
931
950
  'coverage',
932
951
  'storybook-static'
933
952
  ]);
953
+ const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
954
+ const module_move_escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
955
+ const module_move_walk = (folder)=>{
956
+ if (!external_node_fs_default().existsSync(folder)) return [];
957
+ return external_node_fs_default().readdirSync(folder, {
958
+ withFileTypes: true
959
+ }).flatMap((entry)=>{
960
+ const entryPath = external_node_path_default().join(folder, entry.name);
961
+ if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : module_move_walk(entryPath);
962
+ return entry.isFile() ? [
963
+ entryPath
964
+ ] : [];
965
+ });
966
+ };
967
+ const module_move_toPosix = (value)=>value.split(external_node_path_default().sep).join('/');
968
+ const readAliases = (projectRoot)=>{
969
+ const tsconfig = external_node_path_default().join(projectRoot, 'tsconfig.json');
970
+ if (!external_node_fs_default().existsSync(tsconfig)) return [];
971
+ try {
972
+ const { compilerOptions = {} } = JSON.parse(stripJsonComments(external_node_fs_default().readFileSync(tsconfig, 'utf8')));
973
+ const base = external_node_path_default().resolve(projectRoot, compilerOptions.baseUrl ?? '.');
974
+ return Object.entries(compilerOptions.paths ?? {}).filter(([pattern, targets])=>pattern.endsWith('*') && targets[0]?.endsWith('*')).map(([pattern, [target]])=>({
975
+ prefix: pattern.slice(0, -1),
976
+ target: external_node_path_default().resolve(base, target.slice(0, -1))
977
+ }));
978
+ } catch {
979
+ return [];
980
+ }
981
+ };
982
+ const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
983
+ const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
984
+ const importPaths = (file)=>{
985
+ const withoutExtension = file.replace(codeExtension, '');
986
+ return 'index' === external_node_path_default().basename(withoutExtension) ? [
987
+ withoutExtension,
988
+ external_node_path_default().dirname(withoutExtension)
989
+ ] : [
990
+ withoutExtension
991
+ ];
992
+ };
993
+ const projectImports = (projectRoot)=>{
994
+ const aliases = readAliases(projectRoot);
995
+ const resolve = (specifier, fromFile)=>{
996
+ if (specifier.startsWith('.')) return {
997
+ resolved: external_node_path_default().resolve(external_node_path_default().dirname(fromFile), specifier),
998
+ alias: void 0
999
+ };
1000
+ const alias = aliases.find(({ prefix })=>specifier.startsWith(prefix));
1001
+ return alias ? {
1002
+ resolved: external_node_path_default().resolve(alias.target, specifier.slice(alias.prefix.length)),
1003
+ alias
1004
+ } : void 0;
1005
+ };
1006
+ const specifierFor = (fromFile, toPath, alias)=>{
1007
+ const aliased = alias && module_move_toPosix(external_node_path_default().relative(alias.target, toPath));
1008
+ if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
1009
+ const relative = module_move_toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toPath));
1010
+ return relative.startsWith('.') ? relative : `./${relative}`;
1011
+ };
1012
+ const codeFiles = new Map(module_move_walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
1013
+ file,
1014
+ external_node_fs_default().readFileSync(file, 'utf8')
1015
+ ]));
1016
+ const importsOf = (file)=>[
1017
+ ...(codeFiles.get(file) ?? '').matchAll(specifierPattern)
1018
+ ].map(([, , , specifier])=>resolve(specifier, file)?.resolved).filter((resolved)=>!!resolved);
1019
+ return {
1020
+ resolve,
1021
+ specifierFor,
1022
+ codeFiles,
1023
+ importsOf
1024
+ };
1025
+ };
1026
+ const module_move_stageModuleMove = ({ projectRoot, stopAt, moves, movedPath, rename, everyFile = (content)=>content })=>{
1027
+ const { resolve, specifierFor, codeFiles } = projectImports(projectRoot);
1028
+ const barrels = new Set();
1029
+ const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
1030
+ for(let found = true; found;){
1031
+ found = false;
1032
+ for (const [file, content] of codeFiles){
1033
+ if (moves.has(file) || isBarrel(file)) continue;
1034
+ const reExportsModule = [
1035
+ ...content.matchAll(reExportPattern)
1036
+ ].some(([, , specifier])=>{
1037
+ const resolution = resolve(specifier, file);
1038
+ return !!resolution && (!!movedPath(resolution.resolved) || isBarrel(resolution.resolved));
1039
+ });
1040
+ if (reExportsModule) {
1041
+ for (const importPath of importPaths(file))barrels.add(importPath);
1042
+ found = true;
1043
+ }
1044
+ }
1045
+ }
1046
+ const rewrite = (content, oldFile, newFile)=>{
1047
+ let referencesModule = false;
1048
+ const rewritten = content.replace(specifierPattern, (match, keyword, quote, specifier)=>{
1049
+ const resolution = resolve(specifier, oldFile);
1050
+ if (!resolution) return match;
1051
+ const moved = movedPath(resolution.resolved);
1052
+ if (moved || isBarrel(resolution.resolved)) referencesModule = true;
1053
+ if (!moved && oldFile === newFile) return match;
1054
+ const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
1055
+ return `${keyword}${quote}${next}${quote}`;
1056
+ });
1057
+ const changed = everyFile(rewritten);
1058
+ if (!referencesModule && !moves.has(oldFile)) return changed;
1059
+ return rename(changed, {
1060
+ moved: moves.has(oldFile)
1061
+ });
1062
+ };
1063
+ for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new file_system_File(file).moveTo(newFile, stopAt);
1064
+ const updated = [];
1065
+ for (const [file, content] of codeFiles){
1066
+ const newFile = moves.get(file);
1067
+ const next = rewrite(content, file, newFile ?? file);
1068
+ if (newFile && newFile !== file) {
1069
+ new file_system_File(newFile).data = next;
1070
+ new file_system_File(file).delete(stopAt);
1071
+ } else if (next !== content) {
1072
+ new file_system_File(file).update(next);
1073
+ if (!newFile) updated.push(file);
1074
+ }
1075
+ }
1076
+ return {
1077
+ moves: [
1078
+ ...moves
1079
+ ].filter(([from, to])=>from !== to),
1080
+ updated
1081
+ };
1082
+ };
1083
+ const serviceLayout = (layer)=>({
1084
+ title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
1085
+ core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
1086
+ files: ({ name })=>[
1087
+ `${layer}/services/${name}-${layer}-service.ts`,
1088
+ `${layer}/services/${name}-${layer}-service.spec.ts`,
1089
+ `wiring/${layer}-services/wire-${name}-${layer}-service.ts`
1090
+ ],
1091
+ wired: true,
1092
+ sharedKernel: true
1093
+ });
1094
+ const handlerLayout = (kind)=>{
1095
+ const folder = 'command' === kind ? 'commands' : 'queries';
1096
+ const Suffix = 'command' === kind ? 'Command' : 'Query';
1097
+ return {
1098
+ title: 'command' === kind ? 'Commands' : 'Queries',
1099
+ core: (ClassName)=>`${ClassName}${Suffix}`,
1100
+ files: ({ name }, labels)=>[
1101
+ `application/${folder}/${name}-${kind}.ts`,
1102
+ `application/${folder}/${name}-${kind}.spec.ts`,
1103
+ ...labels.map((label)=>`infrastructure/${folder}/${label}/${label}-${name}-${kind}.ts`),
1104
+ `wiring/${folder}/wire-${name}-${kind}.ts`
1105
+ ],
1106
+ implementations: `infrastructure/${folder}`,
1107
+ wired: true,
1108
+ sharedKernel: false
1109
+ };
1110
+ };
1111
+ const domainModelLayout = (kind)=>{
1112
+ const folder = 'entity' === kind ? 'entities' : 'value-objects';
1113
+ return {
1114
+ title: 'entity' === kind ? 'Entities' : 'Value objects',
1115
+ core: (ClassName)=>ClassName,
1116
+ files: ({ name, aggregate })=>{
1117
+ const base = aggregate ? `domain/aggregates/${aggregate}/${folder}` : `domain/${folder}`;
1118
+ return [
1119
+ `${base}/${name}.${kind}.ts`,
1120
+ `${base}/${name}.${kind}.spec.ts`
1121
+ ];
1122
+ },
1123
+ wired: false,
1124
+ sharedKernel: true
1125
+ };
1126
+ };
1127
+ const aggregateOwnFiles = (name)=>[
1128
+ `${name}.aggregate-root.ts`,
1129
+ `${name}.aggregate-root.spec.ts`,
1130
+ `${name}-repository.ts`,
1131
+ `${name}-repository.spec.ts`,
1132
+ 'index.ts'
1133
+ ];
1134
+ const kindLayouts = {
1135
+ aggregate: {
1136
+ title: 'Aggregates',
1137
+ core: (ClassName)=>`${ClassName}Repository`,
1138
+ files: ({ name }, labels)=>[
1139
+ ...aggregateOwnFiles(name).map((file)=>`domain/aggregates/${name}/${file}`),
1140
+ ...labels.map((label)=>`infrastructure/repositories/${label}/${label}-${name}-repository.ts`),
1141
+ `wiring/repositories/wire-${name}-repository.ts`
1142
+ ],
1143
+ implementations: 'infrastructure/repositories',
1144
+ wired: true,
1145
+ sharedKernel: false
1146
+ },
1147
+ entity: domainModelLayout('entity'),
1148
+ 'value-object': domainModelLayout('value-object'),
1149
+ 'domain-service': serviceLayout('domain'),
1150
+ 'application-service': serviceLayout('application'),
1151
+ 'infrastructure-service': serviceLayout('infrastructure'),
1152
+ 'presentation-service': serviceLayout('presentation'),
1153
+ 'use-case': {
1154
+ title: 'Use cases',
1155
+ core: (ClassName)=>`${ClassName}UseCase`,
1156
+ files: ({ name })=>[
1157
+ `application/use-cases/${name}-use-case.ts`,
1158
+ `application/use-cases/${name}-use-case.spec.ts`,
1159
+ `wiring/use-cases/wire-${name}-use-case.ts`
1160
+ ],
1161
+ wired: true,
1162
+ sharedKernel: false
1163
+ },
1164
+ command: handlerLayout('command'),
1165
+ query: handlerLayout('query'),
1166
+ port: {
1167
+ title: 'Ports',
1168
+ core: (ClassName)=>ClassName,
1169
+ files: ({ name }, labels)=>[
1170
+ `application/ports/${name}.ts`,
1171
+ `application/ports/${name}.spec.ts`,
1172
+ ...labels.map((label)=>`infrastructure/application-adapters/${label}/${label}-${name}.ts`),
1173
+ `wiring/application-ports/wire-${name}.ts`
1174
+ ],
1175
+ implementations: 'infrastructure/application-adapters',
1176
+ wired: true,
1177
+ sharedKernel: true
1178
+ }
1179
+ };
1180
+ const subfolders = (folder)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder, {
1181
+ withFileTypes: true
1182
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort() : [];
1183
+ const namesBySuffix = (folder, suffix)=>external_node_fs_default().existsSync(folder) ? external_node_fs_default().readdirSync(folder).filter((file)=>file.endsWith(suffix) && !file.endsWith('.spec.ts')).map((file)=>file.slice(0, -suffix.length)).sort() : [];
1184
+ const labelsOf = (ownerPath, kind, name)=>{
1185
+ const { implementations } = kindLayouts[kind];
1186
+ if (!implementations) return [];
1187
+ return subfolders(external_node_path_default().join(ownerPath, implementations)).filter((label)=>kindLayouts[kind].files({
1188
+ ownerPath,
1189
+ name
1190
+ }, [
1191
+ label
1192
+ ]).some((file)=>file.startsWith(`${implementations}/`) && external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, file))));
1193
+ };
1194
+ const aggregatesOf = (ownerPath)=>subfolders(external_node_path_default().join(ownerPath, 'domain/aggregates')).filter((name)=>external_node_fs_default().existsSync(external_node_path_default().join(ownerPath, 'domain/aggregates', name, `${name}.aggregate-root.ts`)));
1195
+ const findBackendUnits = (ownerPath)=>{
1196
+ const unit = (kind, name, aggregate)=>({
1197
+ kind,
1198
+ name,
1199
+ ownerPath,
1200
+ aggregate,
1201
+ labels: labelsOf(ownerPath, kind, name)
1202
+ });
1203
+ const aggregates = aggregatesOf(ownerPath);
1204
+ const inAggregates = (kind)=>aggregates.flatMap((aggregate)=>namesBySuffix(external_node_path_default().join(ownerPath, 'domain/aggregates', aggregate, 'entity' === kind ? 'entities' : 'value-objects'), `.${kind}.ts`).map((name)=>unit(kind, name, aggregate)));
1205
+ const at = (folder, suffix, kind)=>namesBySuffix(external_node_path_default().join(ownerPath, folder), suffix).map((name)=>unit(kind, name));
1206
+ return [
1207
+ ...aggregates.map((name)=>unit('aggregate', name)),
1208
+ ...inAggregates('entity'),
1209
+ ...at('domain/entities', '.entity.ts', 'entity'),
1210
+ ...inAggregates('value-object'),
1211
+ ...at('domain/value-objects', '.value-object.ts', 'value-object'),
1212
+ ...at('domain/services', '-domain-service.ts', 'domain-service'),
1213
+ ...at('application/ports', '.ts', 'port'),
1214
+ ...at('application/queries', '-query.ts', 'query'),
1215
+ ...at('application/commands', '-command.ts', 'command'),
1216
+ ...at('application/use-cases', '-use-case.ts', 'use-case'),
1217
+ ...at('application/services', '-application-service.ts', 'application-service'),
1218
+ ...at('infrastructure/services', '-infrastructure-service.ts', 'infrastructure-service'),
1219
+ ...at('presentation/services', '-presentation-service.ts', 'presentation-service')
1220
+ ];
1221
+ };
1222
+ const kebabName = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
1223
+ const lowerFirst = (value)=>value[0].toLowerCase() + value.slice(1);
1224
+ const unitMoves = (unit, target)=>{
1225
+ const layout = kindLayouts[unit.kind];
1226
+ const from = layout.files(unit, unit.labels);
1227
+ const to = layout.files(target, unit.labels);
1228
+ const moves = new Map();
1229
+ from.forEach((file, index)=>{
1230
+ const oldPath = external_node_path_default().join(unit.ownerPath, file);
1231
+ if (external_node_fs_default().existsSync(oldPath)) moves.set(oldPath, external_node_path_default().join(target.ownerPath, to[index]));
1232
+ });
1233
+ if ('aggregate' === unit.kind) {
1234
+ const oldFolder = external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.name);
1235
+ const newFolder = external_node_path_default().join(target.ownerPath, 'domain/aggregates', target.name);
1236
+ const own = new Set(aggregateOwnFiles(unit.name).map((file)=>external_node_path_default().join(oldFolder, file)));
1237
+ for (const file of module_move_walk(oldFolder))if (!own.has(file)) moves.set(file, external_node_path_default().join(newFolder, external_node_path_default().relative(oldFolder, file)));
1238
+ }
1239
+ return moves;
1240
+ };
1241
+ const validateBackendMove = (unit, target, sharedKernelPath)=>{
1242
+ if (!kebabName.test(target.name)) return 'Use kebab-case: lowercase words split by "-", e.g. place-order';
1243
+ if (target.ownerPath === sharedKernelPath && !kindLayouts[unit.kind].sharedKernel) return `${kindLayouts[unit.kind].title} are not part of the Shared Kernel`;
1244
+ if (target.ownerPath === unit.ownerPath && target.name === unit.name && target.aggregate === unit.aggregate) return 'Nothing to change: enter a new name or pick another place';
1245
+ for (const [from, to] of unitMoves(unit, target))if (to !== from && external_node_fs_default().existsSync(to)) return `${external_node_path_default().relative(target.ownerPath, to)} already exists`;
1246
+ return true;
1247
+ };
1248
+ const ownerOf = (rootFolderPath, file)=>{
1249
+ const [area, context] = external_node_path_default().relative(rootFolderPath, file).split(external_node_path_default().sep);
1250
+ if ('bounded-contexts' === area && context) return {
1251
+ context,
1252
+ path: external_node_path_default().join(rootFolderPath, area, context)
1253
+ };
1254
+ if ('shared-kernel' === area) return {
1255
+ context: void 0,
1256
+ path: external_node_path_default().join(rootFolderPath, area)
1257
+ };
1258
+ };
1259
+ const inMemoryDbFile = (rootFolderPath)=>external_node_path_default().join(rootFolderPath, 'shared-kernel/infrastructure/services/in-memory-db-infrastructure-service.ts');
1260
+ const isolationAllows = (rootFolderPath, from, to)=>{
1261
+ const fromOwner = ownerOf(rootFolderPath, from);
1262
+ const toOwner = ownerOf(rootFolderPath, to);
1263
+ if (!fromOwner || !toOwner?.context) return true;
1264
+ if (fromOwner.context) return fromOwner.context === toOwner.context;
1265
+ const inside = (folder)=>to === external_node_path_default().join(toOwner.path, folder) || to.startsWith(external_node_path_default().join(toOwner.path, folder) + external_node_path_default().sep);
1266
+ return inside('domain/errors') || from.replace(codeExtension, '') === inMemoryDbFile(rootFolderPath).replace(codeExtension, '') && inside('domain');
1267
+ };
1268
+ const moveBackendUnit = (projectRoot, rootFolderPath, unit, target)=>{
1269
+ const layout = kindLayouts[unit.kind];
1270
+ const moves = unitMoves(unit, target);
1271
+ const withoutExtension = new Map([
1272
+ ...moves
1273
+ ].map(([from, to])=>[
1274
+ from.replace(codeExtension, ''),
1275
+ to.replace(codeExtension, '')
1276
+ ]));
1277
+ const folders = 'aggregate' === unit.kind ? [
1278
+ [
1279
+ external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.name),
1280
+ external_node_path_default().join(target.ownerPath, 'domain/aggregates', target.name)
1281
+ ]
1282
+ ] : [];
1283
+ const movedPath = (candidate)=>{
1284
+ const extension = candidate.match(codeExtension)?.[0];
1285
+ if (extension) return moves.get(candidate);
1286
+ return withoutExtension.get(candidate) ?? folders.find(([from])=>from === candidate)?.[1];
1287
+ };
1288
+ const { codeFiles, importsOf, resolve } = projectImports(projectRoot);
1289
+ const oldNaming = new unknown_format_naming_UnknownFormatNaming(unit.name);
1290
+ const newNaming = new unknown_format_naming_UnknownFormatNaming(target.name);
1291
+ const leavesAggregate = !!unit.aggregate && (unit.aggregate !== target.aggregate || unit.ownerPath !== target.ownerPath);
1292
+ const oldAggregateFolder = unit.aggregate && external_node_path_default().join(unit.ownerPath, 'domain/aggregates', unit.aggregate);
1293
+ const isOldBarrel = (resolved)=>!!oldAggregateFolder && (resolved === oldAggregateFolder || resolved === external_node_path_default().join(oldAggregateFolder, 'index'));
1294
+ const mainFile = [
1295
+ ...moves.keys()
1296
+ ][0];
1297
+ const newMainFile = moves.get(mainFile);
1298
+ const namedImports = /import\s+(type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\3;?/g;
1299
+ const barrelImporters = leavesAggregate ? [
1300
+ ...codeFiles
1301
+ ].filter(([file, content])=>!moves.has(file) && [
1302
+ ...content.matchAll(namedImports)
1303
+ ].some(([, , names, , specifier])=>isOldBarrel(resolve(specifier, file)?.resolved) && new RegExp(`(?<![\\w$])${oldNaming.ClassName}(?![\\w$])`).test(names))) : [];
1304
+ const violations = [];
1305
+ const relative = (file)=>module_move_toPosix(external_node_path_default().relative(projectRoot, file));
1306
+ for (const file of codeFiles.keys()){
1307
+ const from = moves.get(file) ?? file;
1308
+ for (const imported of importsOf(file)){
1309
+ const to = movedPath(imported);
1310
+ if (moves.has(file) || to) {
1311
+ if (!isolationAllows(rootFolderPath, from, to ?? imported)) violations.push([
1312
+ relative(from),
1313
+ relative(to ?? imported)
1314
+ ]);
1315
+ }
1316
+ }
1317
+ }
1318
+ for (const [file] of barrelImporters)if (!isolationAllows(rootFolderPath, file, newMainFile)) violations.push([
1319
+ relative(file),
1320
+ relative(newMainFile)
1321
+ ]);
1322
+ if (violations.length) return {
1323
+ violations
1324
+ };
1325
+ const word = (form)=>`(?<![\\w$])${module_move_escapeRegExp(form)}(?![\\w$])`;
1326
+ const oldCore = layout.core(oldNaming.ClassName);
1327
+ const newCore = layout.core(newNaming.ClassName);
1328
+ const prefixes = [
1329
+ ...unit.labels.map((label)=>new unknown_format_naming_UnknownFormatNaming(label).ClassName),
1330
+ ...layout.wired ? [
1331
+ 'wire'
1332
+ ] : []
1333
+ ];
1334
+ const renames = [
1335
+ {
1336
+ pattern: new RegExp(`(?<![\\w$])(${prefixes.map(module_move_escapeRegExp).join('|')})?${module_move_escapeRegExp(oldCore)}(?![\\w$])`, 'g'),
1337
+ to: `$1${newCore}`
1338
+ },
1339
+ {
1340
+ pattern: new RegExp(word(lowerFirst(oldCore)), 'g'),
1341
+ to: lowerFirst(newCore)
1342
+ },
1343
+ {
1344
+ pattern: new RegExp(`(describe\\(\\s*['"\`])${module_move_escapeRegExp(oldNaming.withSpaces)}(?=[ '"\`])`, 'g'),
1345
+ to: `$1${newNaming.withSpaces}`,
1346
+ movedOnly: true
1347
+ }
1348
+ ];
1349
+ if ('aggregate' === unit.kind) renames.push({
1350
+ pattern: new RegExp(word(oldNaming.ClassName), 'g'),
1351
+ to: newNaming.ClassName
1352
+ }, {
1353
+ pattern: new RegExp(word(oldNaming.variableName), 'g'),
1354
+ to: newNaming.variableName,
1355
+ movedOnly: true
1356
+ });
1357
+ if ('entity' === unit.kind || 'value-object' === unit.kind) renames.push({
1358
+ pattern: new RegExp(word(oldNaming.variableName), 'g'),
1359
+ to: newNaming.variableName,
1360
+ movedOnly: true
1361
+ });
1362
+ const oldSection = new unknown_format_naming_UnknownFormatNaming(plural(unit.name));
1363
+ const newSection = new unknown_format_naming_UnknownFormatNaming(plural(target.name));
1364
+ const renamesSection = 'aggregate' === unit.kind && unit.name !== target.name;
1365
+ const everyFile = (content)=>renamesSection ? content.replace(new RegExp(`(InMemoryDbInfrastructureService\\[\\s*['"])${oldSection.variableName}(?=['"]\\s*\\])`, 'g'), `$1${newSection.variableName}`).replace(new RegExp(`(inMemoryDbInfrastructureService\\s*\\.\\s*)${oldSection.variableName}(?![\\w$])`, 'g'), `$1${newSection.variableName}`).replace(new RegExp(`(?<![\\w$.])${oldSection.variableName}(\\s*=\\s*this\\.section<[^>]*>\\(\\s*['"])${oldSection.fileName.toUpperCase()}(?=['"])`, 'g'), `${newSection.variableName}$1${newSection.fileName.toUpperCase()}`) : content;
1366
+ const plan = module_move_stageModuleMove({
1367
+ projectRoot,
1368
+ stopAt: rootFolderPath,
1369
+ moves,
1370
+ movedPath,
1371
+ rename: (content, { moved })=>renames.reduce((result, { pattern, to, movedOnly })=>movedOnly && !moved ? result : result.replace(pattern, to), content),
1372
+ everyFile
1373
+ });
1374
+ if (leavesAggregate && oldAggregateFolder) {
1375
+ const indexFile = new file_system_File(external_node_path_default().join(oldAggregateFolder, 'index.ts'));
1376
+ const exportLine = /^export\s+\*\s+from\s+(['"])([^'"\n]+)\1;?\s*$/;
1377
+ indexFile.update(indexFile.data.split('\n').filter((line)=>{
1378
+ const specifier = line.match(exportLine)?.[2];
1379
+ return !specifier || external_node_path_default().resolve(external_node_path_default().dirname(indexFile.path), specifier) !== newMainFile.replace(codeExtension, '');
1380
+ }).join('\n'));
1381
+ if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
1382
+ for (const [file] of barrelImporters){
1383
+ const importer = new file_system_File(file);
1384
+ let content = importer.data;
1385
+ for (const match of content.matchAll(namedImports)){
1386
+ const [statement, typeOnly = '', names, quote, specifier] = match;
1387
+ if (!isOldBarrel(resolve(specifier, file)?.resolved)) continue;
1388
+ const items = names.split(',').map((item)=>item.trim()).filter((item)=>!!item);
1389
+ const own = new RegExp(`^(?:type\\s+)?${newNaming.ClassName}(?:\\s+as\\s+[\\w$]+)?$`);
1390
+ const moved = items.filter((item)=>own.test(item));
1391
+ if (!moved.length) continue;
1392
+ const rest = items.filter((item)=>!own.test(item));
1393
+ const direct = `import ${typeOnly}{ ${moved.join(', ')} } from ${quote}${projectRelative(file, newMainFile)}${quote}`;
1394
+ content = content.replace(statement, rest.length ? `import ${typeOnly}{ ${rest.join(', ')} } from ${quote}${specifier}${quote}\n${direct}` : direct);
1395
+ }
1396
+ importer.update(content);
1397
+ }
1398
+ }
1399
+ if (target.aggregate && (target.aggregate !== unit.aggregate || target.ownerPath !== unit.ownerPath)) {
1400
+ const kindFolder = 'entity' === unit.kind ? 'entities' : 'value-objects';
1401
+ const indexFile = new file_system_File(external_node_path_default().join(target.ownerPath, 'domain/aggregates', target.aggregate, 'index.ts'));
1402
+ indexFile.addLineIfMissing(`export * from './${kindFolder}/${target.name}.${unit.kind}'`);
1403
+ if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
1404
+ }
1405
+ return plan;
1406
+ };
1407
+ const projectRelative = (fromFile, toFile)=>{
1408
+ const relative = module_move_toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toFile.replace(codeExtension, '')));
1409
+ return relative.startsWith('.') ? relative : `./${relative}`;
1410
+ };
1411
+ const noAggregate = 'No aggregate';
1412
+ const moveBackendUnitUseCase = async (ownerFolder)=>{
1413
+ const root = new project_root_ProjectRoot().path;
1414
+ const rootFolderPath = external_node_path_default().join(root, config_file_ConfigFile.Instance.data.rootFolder);
1415
+ const sharedKernelPath = external_node_path_default().join(rootFolderPath, 'shared-kernel');
1416
+ const units = findBackendUnits(ownerFolder.path);
1417
+ if (!units.length) return void console.log('No modules generated by df-scaffold were found here.');
1418
+ const unit = await (0, prompts_namespaceObject.select)({
1419
+ message: 'Module:',
1420
+ choices: Object.keys(kindLayouts).flatMap((kind)=>{
1421
+ const group = units.filter((x)=>x.kind === kind);
1422
+ return group.length ? [
1423
+ new prompts_namespaceObject.Separator(`── ${kindLayouts[group[0].kind].title}`),
1424
+ ...group.map((value)=>({
1425
+ name: value.aggregate ? `${value.name} (${value.aggregate})` : value.name,
1426
+ value
1427
+ }))
1428
+ ] : [];
1429
+ }),
1430
+ pageSize: 20
1431
+ });
1432
+ const placeName = (ownerPath)=>ownerPath === sharedKernelPath ? 'Shared Kernel' : `Bounded Context: ${external_node_path_default().basename(ownerPath)}`;
1433
+ const contexts = new file_system_Folder(rootFolderPath).subitem([
1434
+ 'bounded-contexts'
1435
+ ]).content.subfolderNames.map((name)=>external_node_path_default().join(rootFolderPath, 'bounded-contexts', name));
1436
+ const places = [
1437
+ unit.ownerPath,
1438
+ ...contexts,
1439
+ ...kindLayouts[unit.kind].sharedKernel ? [
1440
+ sharedKernelPath
1441
+ ] : []
1442
+ ].filter((place, index, all)=>all.indexOf(place) === index);
1443
+ const ownerPath = await (0, prompts_namespaceObject.select)({
1444
+ message: 'Move to:',
1445
+ choices: places.map((value)=>({
1446
+ name: value === unit.ownerPath ? `${placeName(value)} (stays)` : placeName(value),
1447
+ value
1448
+ }))
1449
+ });
1450
+ let aggregate;
1451
+ const aggregates = ownerPath === sharedKernelPath ? [] : aggregatesOf(ownerPath);
1452
+ if (('entity' === unit.kind || 'value-object' === unit.kind) && aggregates.length) {
1453
+ const picked = await (0, prompts_namespaceObject.select)({
1454
+ message: 'Aggregate:',
1455
+ choices: [
1456
+ noAggregate,
1457
+ ...aggregates
1458
+ ],
1459
+ default: ownerPath === unit.ownerPath && unit.aggregate ? unit.aggregate : noAggregate
1460
+ });
1461
+ aggregate = picked === noAggregate ? void 0 : picked;
1462
+ }
1463
+ const target = (name)=>({
1464
+ ownerPath,
1465
+ aggregate,
1466
+ name: name.trim()
1467
+ });
1468
+ const name = await (0, prompts_namespaceObject.input)({
1469
+ message: 'New name:',
1470
+ default: unit.name,
1471
+ validate: (value)=>validateBackendMove(unit, target(value), sharedKernelPath)
1472
+ });
1473
+ const result = moveBackendUnit(root, rootFolderPath, unit, target(name));
1474
+ if (result.violations) return void console.log([
1475
+ "Nothing was moved: these imports would cross a bounded context boundary.",
1476
+ ...result.violations.map(([from, to])=>` ${from} → ${to}`),
1477
+ 'Give the other context its own query or command, or move what it depends on first.'
1478
+ ].join('\n'));
1479
+ const relative = (file)=>external_node_path_default().relative(root, file);
1480
+ console.log([
1481
+ 'Files to move:',
1482
+ ...result.moves.map(([from, to])=>` ${relative(from)} → ${relative(to)}`),
1483
+ ...result.updated.length ? [
1484
+ 'Files with updated imports and names:',
1485
+ ...result.updated.map((file)=>` ${relative(file)}`)
1486
+ ] : []
1487
+ ].join('\n'));
1488
+ if (!await (0, prompts_namespaceObject.confirm)({
1489
+ message: 'Apply?',
1490
+ default: true
1491
+ })) {
1492
+ file_system_discardPendingChanges();
1493
+ console.log('Cancelled: nothing was written.');
1494
+ }
1495
+ };
934
1496
  const scaffoldNewAggregateUseCase = async (boundedContextFolder)=>{
935
1497
  const aggregateName = await (0, prompts_namespaceObject.input)({
936
1498
  message: 'Aggregate name:'
@@ -1357,7 +1919,7 @@ export const wire${naming.ClassName}Command = envBranchedWire({
1357
1919
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
1358
1920
  }
1359
1921
  };
1360
- const noAggregate = 'No aggregate';
1922
+ const scaffold_new_domain_object_noAggregate = 'No aggregate';
1361
1923
  const scaffoldNewDomainObject = async (boundedContextFolder, kind)=>{
1362
1924
  const name = await (0, prompts_namespaceObject.input)({
1363
1925
  message: 'Name: '
@@ -1372,11 +1934,11 @@ const scaffoldNewDomainObject = async (boundedContextFolder, kind)=>{
1372
1934
  message: 'Aggregate:',
1373
1935
  choices: [
1374
1936
  ...aggregateNames,
1375
- noAggregate
1937
+ scaffold_new_domain_object_noAggregate
1376
1938
  ]
1377
- }) : noAggregate;
1939
+ }) : scaffold_new_domain_object_noAggregate;
1378
1940
  const kindFolderName = 'entity' === kind ? 'entities' : 'value-objects';
1379
- const folder = aggregate === noAggregate ? boundedContextFolder.subitem([
1941
+ const folder = aggregate === scaffold_new_domain_object_noAggregate ? boundedContextFolder.subitem([
1380
1942
  'domain',
1381
1943
  kindFolderName
1382
1944
  ]) : aggregatesFolder.subitem([
@@ -1391,7 +1953,7 @@ import { domainType } from '@domain-first/types'
1391
1953
  export class ${naming.ClassName} extends domainType() {
1392
1954
 
1393
1955
  }`.trim() : `export class ${naming.ClassName} {}`);
1394
- if (aggregate !== noAggregate) aggregatesFolder.subitem([
1956
+ if (aggregate !== scaffold_new_domain_object_noAggregate) aggregatesFolder.subitem([
1395
1957
  aggregate
1396
1958
  ]).file('index.ts').addLineIfMissing(`export * from './${kindFolderName}/${fileName}'`);
1397
1959
  const { testingLibrary } = config_file_ConfigFile.Instance.data;
@@ -1941,10 +2503,12 @@ const main = async ()=>{
1941
2503
  'Application',
1942
2504
  'Infrastructure',
1943
2505
  'Presentation',
1944
- config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? 'Wire dependency' : void 0
2506
+ config_file_ConfigFile.Instance.data.domainFirstPackages.includes('@domain-first/wire') ? 'Wire dependency' : void 0,
2507
+ 'Move or rename'
1945
2508
  ].filter((x)=>!!x)
1946
2509
  });
1947
2510
  if ('Wire dependency' === layer) return void await wireDependency(boundedContextFolder);
2511
+ if ('Move or rename' === layer) return void await moveBackendUnitUseCase(boundedContextFolder);
1948
2512
  if ('Domain' === layer) {
1949
2513
  const operation = await (0, prompts_namespaceObject.select)({
1950
2514
  message: 'Domain layer operation:',