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