@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/init.cjs CHANGED
@@ -830,6 +830,51 @@ new Set([
830
830
  'coverage',
831
831
  'storybook-static'
832
832
  ]);
833
+ const serviceLayout = (layer)=>({
834
+ title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
835
+ core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
836
+ files: ({ name })=>[
837
+ `${layer}/services/${name}-${layer}-service.ts`,
838
+ `${layer}/services/${name}-${layer}-service.spec.ts`,
839
+ `wiring/${layer}-services/wire-${name}-${layer}-service.ts`
840
+ ],
841
+ wired: true,
842
+ sharedKernel: true
843
+ });
844
+ const handlerLayout = (kind)=>{
845
+ const folder = 'command' === kind ? 'commands' : 'queries';
846
+ const Suffix = 'command' === kind ? 'Command' : 'Query';
847
+ return {
848
+ title: 'command' === kind ? 'Commands' : 'Queries',
849
+ core: (ClassName)=>`${ClassName}${Suffix}`,
850
+ files: ({ name }, labels)=>[
851
+ `application/${folder}/${name}-${kind}.ts`,
852
+ `application/${folder}/${name}-${kind}.spec.ts`,
853
+ ...labels.map((label)=>`infrastructure/${folder}/${label}/${label}-${name}-${kind}.ts`),
854
+ `wiring/${folder}/wire-${name}-${kind}.ts`
855
+ ],
856
+ implementations: `infrastructure/${folder}`,
857
+ wired: true,
858
+ sharedKernel: false
859
+ };
860
+ };
861
+ const domainModelLayout = (kind)=>{
862
+ const folder = 'entity' === kind ? 'entities' : 'value-objects';
863
+ return {
864
+ title: 'entity' === kind ? 'Entities' : 'Value objects',
865
+ core: (ClassName)=>ClassName,
866
+ files: ({ name, aggregate })=>{
867
+ const base = aggregate ? `domain/aggregates/${aggregate}/${folder}` : `domain/${folder}`;
868
+ return [
869
+ `${base}/${name}.${kind}.ts`,
870
+ `${base}/${name}.${kind}.spec.ts`
871
+ ];
872
+ },
873
+ wired: false,
874
+ sharedKernel: true
875
+ };
876
+ };
877
+ domainModelLayout('entity'), domainModelLayout('value-object'), serviceLayout('domain'), serviceLayout('application'), serviceLayout('infrastructure'), serviceLayout('presentation'), handlerLayout('command'), handlerLayout('query');
833
878
  const help = `Usage: df-init
834
879
 
835
880
  Initializes a Domain-First project: asks for the source folder, the
@@ -2030,6 +2030,51 @@ new Set([
2030
2030
  'coverage',
2031
2031
  'storybook-static'
2032
2032
  ]);
2033
+ const serviceLayout = (layer)=>({
2034
+ title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
2035
+ core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
2036
+ files: ({ name })=>[
2037
+ `${layer}/services/${name}-${layer}-service.ts`,
2038
+ `${layer}/services/${name}-${layer}-service.spec.ts`,
2039
+ `wiring/${layer}-services/wire-${name}-${layer}-service.ts`
2040
+ ],
2041
+ wired: true,
2042
+ sharedKernel: true
2043
+ });
2044
+ const handlerLayout = (kind)=>{
2045
+ const folder = 'command' === kind ? 'commands' : 'queries';
2046
+ const Suffix = 'command' === kind ? 'Command' : 'Query';
2047
+ return {
2048
+ title: 'command' === kind ? 'Commands' : 'Queries',
2049
+ core: (ClassName)=>`${ClassName}${Suffix}`,
2050
+ files: ({ name }, labels)=>[
2051
+ `application/${folder}/${name}-${kind}.ts`,
2052
+ `application/${folder}/${name}-${kind}.spec.ts`,
2053
+ ...labels.map((label)=>`infrastructure/${folder}/${label}/${label}-${name}-${kind}.ts`),
2054
+ `wiring/${folder}/wire-${name}-${kind}.ts`
2055
+ ],
2056
+ implementations: `infrastructure/${folder}`,
2057
+ wired: true,
2058
+ sharedKernel: false
2059
+ };
2060
+ };
2061
+ const domainModelLayout = (kind)=>{
2062
+ const folder = 'entity' === kind ? 'entities' : 'value-objects';
2063
+ return {
2064
+ title: 'entity' === kind ? 'Entities' : 'Value objects',
2065
+ core: (ClassName)=>ClassName,
2066
+ files: ({ name, aggregate })=>{
2067
+ const base = aggregate ? `domain/aggregates/${aggregate}/${folder}` : `domain/${folder}`;
2068
+ return [
2069
+ `${base}/${name}.${kind}.ts`,
2070
+ `${base}/${name}.${kind}.spec.ts`
2071
+ ];
2072
+ },
2073
+ wired: false,
2074
+ sharedKernel: true
2075
+ };
2076
+ };
2077
+ domainModelLayout('entity'), domainModelLayout('value-object'), serviceLayout('domain'), serviceLayout('application'), serviceLayout('infrastructure'), serviceLayout('presentation'), handlerLayout('command'), handlerLayout('query');
2033
2078
  const help = `Usage: df-integration
2034
2079
 
2035
2080
  Adds integrations to a Domain-First project: the REST endpoint generator,
@@ -0,0 +1,58 @@
1
+ export declare const codeExtension: RegExp;
2
+ export declare const escapeRegExp: (value: string) => string;
3
+ export declare const walk: (folder: string) => string[];
4
+ export declare const toPosix: (value: string) => string;
5
+ type TsconfigAlias = {
6
+ prefix: string;
7
+ target: string;
8
+ };
9
+ /**
10
+ * Code files of the project and how their import specifiers resolve:
11
+ * relative paths and wildcard tsconfig aliases. Package imports resolve
12
+ * to nothing.
13
+ */
14
+ export declare const projectImports: (projectRoot: string) => {
15
+ resolve: (specifier: string, fromFile: string) => {
16
+ resolved: string;
17
+ alias: undefined;
18
+ } | {
19
+ resolved: string;
20
+ alias: TsconfigAlias;
21
+ } | undefined;
22
+ specifierFor: (fromFile: string, toPath: string, alias: TsconfigAlias | undefined) => string;
23
+ codeFiles: Map<string, string>;
24
+ importsOf: (file: string) => string[];
25
+ };
26
+ export type MovePlan = {
27
+ /** Old path → new path of every file of the module. */
28
+ moves: [string, string][];
29
+ /** Other files with references to the module. */
30
+ updated: string[];
31
+ };
32
+ export type ModuleMove = {
33
+ projectRoot: string;
34
+ /** Folders emptied by the move are removed up to this one (exclusive). */
35
+ stopAt: string;
36
+ /** Old path → new path of every file of the module. */
37
+ moves: Map<string, string>;
38
+ /**
39
+ * Where a path of the module goes, for import resolution: files with or
40
+ * without extension, and folders. Undefined for other paths.
41
+ */
42
+ movedPath: (candidate: string) => string | undefined;
43
+ /**
44
+ * Renames the module's names in a file of the module or in a file that
45
+ * references it, directly or through a barrel.
46
+ */
47
+ rename: (content: string, file: {
48
+ moved: boolean;
49
+ }) => string;
50
+ /** A change every code file gets, references or not. */
51
+ everyFile?: (content: string) => string;
52
+ };
53
+ /**
54
+ * Stages the move with pending changes: files of the module, its imports
55
+ * of other files, and every import of it in the project.
56
+ */
57
+ export declare const stageModuleMove: ({ projectRoot, stopAt, moves, movedPath, rename, everyFile }: ModuleMove) => MovePlan;
58
+ export {};
@@ -1,3 +1,5 @@
1
+ import { type MovePlan } from './module-move';
2
+ export type { MovePlan } from './module-move';
1
3
  export type ReactModuleKind = 'page' | 'widget';
2
4
  export type ReactModule = {
3
5
  kind: ReactModuleKind;
@@ -11,12 +13,6 @@ export type ReactModule = {
11
13
  };
12
14
  export declare const findReactModules: (reactFolder: string, kind: ReactModuleKind) => ReactModule[];
13
15
  export declare const validateMove: (reactFolder: string, module: ReactModule, rawName: string) => string | true;
14
- export type MovePlan = {
15
- /** Old path → new path of every file of the module. */
16
- moves: [string, string][];
17
- /** Other files with references to the module. */
18
- updated: string[];
19
- };
20
16
  /**
21
17
  * Stages the move with pending changes: files of the module, its imports
22
18
  * of other files, and every import of it in the project.
package/dist/react.cjs CHANGED
@@ -129,7 +129,7 @@ const pendingDeletions = new Map();
129
129
  const filesToOverwrite = ()=>[
130
130
  ...pendingFiles
131
131
  ].filter(([filePath, { replacesFile }])=>replacesFile && external_node_fs_default().existsSync(filePath)).map(([filePath])=>filePath);
132
- const discardPendingChanges = ()=>{
132
+ const file_system_discardPendingChanges = ()=>{
133
133
  pendingFolders.clear();
134
134
  pendingFiles.clear();
135
135
  pendingMoves.clear();
@@ -163,7 +163,7 @@ const writePendingChanges = ()=>{
163
163
  });
164
164
  for (const [filePath, stopAt] of pendingDeletions)removeEmptyFolders(external_node_path_default().dirname(filePath), stopAt);
165
165
  for (const { sourcePath, stopAt } of pendingMoves.values())removeEmptyFolders(external_node_path_default().dirname(sourcePath), stopAt);
166
- discardPendingChanges();
166
+ file_system_discardPendingChanges();
167
167
  };
168
168
  class FileSystemItem {
169
169
  path;
@@ -332,7 +332,7 @@ const save_pending_changes_savePendingChanges = async ()=>{
332
332
  default: false
333
333
  });
334
334
  if (!overwrite) {
335
- discardPendingChanges();
335
+ file_system_discardPendingChanges();
336
336
  console.log('Cancelled: nothing was written.');
337
337
  return false;
338
338
  }
@@ -425,71 +425,21 @@ const ignoredFolders = new Set([
425
425
  'coverage',
426
426
  'storybook-static'
427
427
  ]);
428
- const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
429
- const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
430
- const react_module_move_walk = (folder)=>{
428
+ const module_move_codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
429
+ const module_move_escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
430
+ const module_move_walk = (folder)=>{
431
431
  if (!external_node_fs_default().existsSync(folder)) return [];
432
432
  return external_node_fs_default().readdirSync(folder, {
433
433
  withFileTypes: true
434
434
  }).flatMap((entry)=>{
435
435
  const entryPath = external_node_path_default().join(folder, entry.name);
436
- if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : react_module_move_walk(entryPath);
436
+ if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : module_move_walk(entryPath);
437
437
  return entry.isFile() ? [
438
438
  entryPath
439
439
  ] : [];
440
440
  });
441
441
  };
442
- const toPosix = (value)=>value.split(external_node_path_default().sep).join('/');
443
- const nestedName = (folders, fileBase)=>{
444
- const prefix = `${folders.join('-')}-`;
445
- const last = folders.length && fileBase.startsWith(prefix) ? fileBase.slice(prefix.length) : fileBase;
446
- return [
447
- ...folders,
448
- last
449
- ].join('/');
450
- };
451
- const declaredClassName = (filePath, suffix, name)=>{
452
- const content = external_node_fs_default().readFileSync(filePath, 'utf8');
453
- const declared = content.match(new RegExp(`export\\s+(?:const|function)\\s+(\\w+)${suffix}\\b`))?.[1];
454
- return declared ?? new NestedName(name).ClassName;
455
- };
456
- const findReactModules = (reactFolder, kind)=>{
457
- const modules = 'page' === kind ? react_module_move_walk(external_node_path_default().join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
458
- 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);
459
- const fileBase = external_node_path_default().basename(file, '-page.tsx');
460
- const name = nestedName(folders, fileBase);
461
- return {
462
- kind,
463
- name,
464
- path: file,
465
- fileBase,
466
- ClassName: declaredClassName(file, 'Page', name)
467
- };
468
- }) : react_module_move_walk(external_node_path_default().join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
469
- const folder = external_node_path_default().dirname(file);
470
- const name = toPosix(external_node_path_default().relative(external_node_path_default().join(reactFolder, 'widgets'), folder));
471
- return {
472
- kind,
473
- name,
474
- path: folder,
475
- fileBase: external_node_path_default().basename(file, '-widget.tsx'),
476
- ClassName: declaredClassName(file, 'Widget', name)
477
- };
478
- });
479
- return modules.sort((a, b)=>a.name.localeCompare(b.name));
480
- };
481
- const react_module_move_targetPath = (reactFolder, module, rawName)=>{
482
- const { folders, folderName, fileName } = new NestedName(rawName);
483
- return 'page' === module.kind ? external_node_path_default().join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : external_node_path_default().join(reactFolder, 'widgets', ...folders, folderName);
484
- };
485
- const validateMove = (reactFolder, module, rawName)=>{
486
- const nameError = NestedName.validate(rawName);
487
- if (true !== nameError) return nameError;
488
- const target = react_module_move_targetPath(reactFolder, module, rawName);
489
- if (target !== module.path && external_node_fs_default().existsSync(target)) return `${external_node_path_default().relative(reactFolder, target)} already exists`;
490
- if (target.startsWith(`${module.path}${external_node_path_default().sep}`)) return 'A widget cannot be moved into itself';
491
- return true;
492
- };
442
+ const module_move_toPosix = (value)=>value.split(external_node_path_default().sep).join('/');
493
443
  const readAliases = (projectRoot)=>{
494
444
  const tsconfig = external_node_path_default().join(projectRoot, 'tsconfig.json');
495
445
  if (!external_node_fs_default().existsSync(tsconfig)) return [];
@@ -507,7 +457,7 @@ const readAliases = (projectRoot)=>{
507
457
  const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
508
458
  const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
509
459
  const importPaths = (file)=>{
510
- const withoutExtension = file.replace(codeExtension, '');
460
+ const withoutExtension = file.replace(module_move_codeExtension, '');
511
461
  return 'index' === external_node_path_default().basename(withoutExtension) ? [
512
462
  withoutExtension,
513
463
  external_node_path_default().dirname(withoutExtension)
@@ -515,26 +465,7 @@ const importPaths = (file)=>{
515
465
  withoutExtension
516
466
  ];
517
467
  };
518
- const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
519
- const newName = new NestedName(rawName);
520
- const target = react_module_move_targetPath(reactFolder, module, rawName);
521
- const newClassName = newName.ClassName;
522
- const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
523
- const oldFolder = 'page' === module.kind ? external_node_path_default().dirname(module.path) : module.path;
524
- const newFolder = 'page' === module.kind ? external_node_path_default().dirname(target) : target;
525
- 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}`);
526
- const movedPath = (candidate)=>{
527
- if (!ownsPath(candidate)) return;
528
- const segments = external_node_path_default().relative(oldFolder, candidate).split(external_node_path_default().sep);
529
- const last = segments.length - 1;
530
- segments[last] = renameFile(segments[last]);
531
- return external_node_path_default().join(newFolder, ...segments);
532
- };
533
- 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);
534
- const moves = new Map(moduleFiles.map((file)=>[
535
- file,
536
- movedPath(file) ?? file
537
- ]));
468
+ const module_move_projectImports = (projectRoot)=>{
538
469
  const aliases = readAliases(projectRoot);
539
470
  const resolve = (specifier, fromFile)=>{
540
471
  if (specifier.startsWith('.')) return {
@@ -548,25 +479,29 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
548
479
  } : void 0;
549
480
  };
550
481
  const specifierFor = (fromFile, toPath, alias)=>{
551
- const aliased = alias && toPosix(external_node_path_default().relative(alias.target, toPath));
482
+ const aliased = alias && module_move_toPosix(external_node_path_default().relative(alias.target, toPath));
552
483
  if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
553
- const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toPath));
484
+ const relative = module_move_toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toPath));
554
485
  return relative.startsWith('.') ? relative : `./${relative}`;
555
486
  };
556
- const suffixes = 'page' === module.kind ? 'Page' : 'Widget|UIModel';
557
- const classPattern = new RegExp(`(?<![\\w$])(use)?${escapeRegExp(module.ClassName)}(?=${suffixes})`, 'g');
558
- const oldTitle = `Widgets/${module.name.split('/').map((segment)=>new NestedName(segment).ClassName).join('/')}`;
559
- const titlePattern = new RegExp(`(['"\`])${escapeRegExp(oldTitle)}\\1`, 'g');
560
- const newTitle = [
561
- 'Widgets',
562
- ...newName.classNameSegments
563
- ].join('/');
564
- const codeFiles = new Map(react_module_move_walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
487
+ const codeFiles = new Map(module_move_walk(projectRoot).filter((file)=>module_move_codeExtension.test(file)).map((file)=>[
565
488
  file,
566
489
  external_node_fs_default().readFileSync(file, 'utf8')
567
490
  ]));
491
+ const importsOf = (file)=>[
492
+ ...(codeFiles.get(file) ?? '').matchAll(specifierPattern)
493
+ ].map(([, , , specifier])=>resolve(specifier, file)?.resolved).filter((resolved)=>!!resolved);
494
+ return {
495
+ resolve,
496
+ specifierFor,
497
+ codeFiles,
498
+ importsOf
499
+ };
500
+ };
501
+ const module_move_stageModuleMove = ({ projectRoot, stopAt, moves, movedPath, rename, everyFile = (content)=>content })=>{
502
+ const { resolve, specifierFor, codeFiles } = module_move_projectImports(projectRoot);
568
503
  const barrels = new Set();
569
- const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
504
+ const isBarrel = (resolved)=>barrels.has(resolved.replace(module_move_codeExtension, ''));
570
505
  for(let found = true; found;){
571
506
  found = false;
572
507
  for (const [file, content] of codeFiles){
@@ -594,18 +529,20 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
594
529
  const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
595
530
  return `${keyword}${quote}${next}${quote}`;
596
531
  });
597
- if (!referencesModule && !moves.has(oldFile)) return content;
598
- const renamed = rewritten.replace(classPattern, (_, use = '')=>`${use}${newClassName}`);
599
- return moves.has(oldFile) && 'widget' === module.kind ? renamed.replace(titlePattern, (_, quote)=>`${quote}${newTitle}${quote}`) : renamed;
532
+ const changed = everyFile(rewritten);
533
+ if (!referencesModule && !moves.has(oldFile)) return changed;
534
+ return rename(changed, {
535
+ moved: moves.has(oldFile)
536
+ });
600
537
  };
601
- for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new file_system_File(file).moveTo(newFile, reactFolder);
538
+ for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new file_system_File(file).moveTo(newFile, stopAt);
602
539
  const updated = [];
603
540
  for (const [file, content] of codeFiles){
604
541
  const newFile = moves.get(file);
605
542
  const next = rewrite(content, file, newFile ?? file);
606
543
  if (newFile && newFile !== file) {
607
544
  new file_system_File(newFile).data = next;
608
- new file_system_File(file).delete(reactFolder);
545
+ new file_system_File(file).delete(stopAt);
609
546
  } else if (next !== content) {
610
547
  new file_system_File(file).update(next);
611
548
  if (!newFile) updated.push(file);
@@ -618,6 +555,140 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
618
555
  updated
619
556
  };
620
557
  };
558
+ const serviceLayout = (layer)=>({
559
+ title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
560
+ core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
561
+ files: ({ name })=>[
562
+ `${layer}/services/${name}-${layer}-service.ts`,
563
+ `${layer}/services/${name}-${layer}-service.spec.ts`,
564
+ `wiring/${layer}-services/wire-${name}-${layer}-service.ts`
565
+ ],
566
+ wired: true,
567
+ sharedKernel: true
568
+ });
569
+ const handlerLayout = (kind)=>{
570
+ const folder = 'command' === kind ? 'commands' : 'queries';
571
+ const Suffix = 'command' === kind ? 'Command' : 'Query';
572
+ return {
573
+ title: 'command' === kind ? 'Commands' : 'Queries',
574
+ core: (ClassName)=>`${ClassName}${Suffix}`,
575
+ files: ({ name }, labels)=>[
576
+ `application/${folder}/${name}-${kind}.ts`,
577
+ `application/${folder}/${name}-${kind}.spec.ts`,
578
+ ...labels.map((label)=>`infrastructure/${folder}/${label}/${label}-${name}-${kind}.ts`),
579
+ `wiring/${folder}/wire-${name}-${kind}.ts`
580
+ ],
581
+ implementations: `infrastructure/${folder}`,
582
+ wired: true,
583
+ sharedKernel: false
584
+ };
585
+ };
586
+ const domainModelLayout = (kind)=>{
587
+ const folder = 'entity' === kind ? 'entities' : 'value-objects';
588
+ return {
589
+ title: 'entity' === kind ? 'Entities' : 'Value objects',
590
+ core: (ClassName)=>ClassName,
591
+ files: ({ name, aggregate })=>{
592
+ const base = aggregate ? `domain/aggregates/${aggregate}/${folder}` : `domain/${folder}`;
593
+ return [
594
+ `${base}/${name}.${kind}.ts`,
595
+ `${base}/${name}.${kind}.spec.ts`
596
+ ];
597
+ },
598
+ wired: false,
599
+ sharedKernel: true
600
+ };
601
+ };
602
+ domainModelLayout('entity'), domainModelLayout('value-object'), serviceLayout('domain'), serviceLayout('application'), serviceLayout('infrastructure'), serviceLayout('presentation'), handlerLayout('command'), handlerLayout('query');
603
+ const nestedName = (folders, fileBase)=>{
604
+ const prefix = `${folders.join('-')}-`;
605
+ const last = folders.length && fileBase.startsWith(prefix) ? fileBase.slice(prefix.length) : fileBase;
606
+ return [
607
+ ...folders,
608
+ last
609
+ ].join('/');
610
+ };
611
+ const declaredClassName = (filePath, suffix, name)=>{
612
+ const content = external_node_fs_default().readFileSync(filePath, 'utf8');
613
+ const declared = content.match(new RegExp(`export\\s+(?:const|function)\\s+(\\w+)${suffix}\\b`))?.[1];
614
+ return declared ?? new NestedName(name).ClassName;
615
+ };
616
+ const findReactModules = (reactFolder, kind)=>{
617
+ const modules = 'page' === kind ? module_move_walk(external_node_path_default().join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
618
+ 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);
619
+ const fileBase = external_node_path_default().basename(file, '-page.tsx');
620
+ const name = nestedName(folders, fileBase);
621
+ return {
622
+ kind,
623
+ name,
624
+ path: file,
625
+ fileBase,
626
+ ClassName: declaredClassName(file, 'Page', name)
627
+ };
628
+ }) : module_move_walk(external_node_path_default().join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
629
+ const folder = external_node_path_default().dirname(file);
630
+ const name = module_move_toPosix(external_node_path_default().relative(external_node_path_default().join(reactFolder, 'widgets'), folder));
631
+ return {
632
+ kind,
633
+ name,
634
+ path: folder,
635
+ fileBase: external_node_path_default().basename(file, '-widget.tsx'),
636
+ ClassName: declaredClassName(file, 'Widget', name)
637
+ };
638
+ });
639
+ return modules.sort((a, b)=>a.name.localeCompare(b.name));
640
+ };
641
+ const react_module_move_targetPath = (reactFolder, module, rawName)=>{
642
+ const { folders, folderName, fileName } = new NestedName(rawName);
643
+ return 'page' === module.kind ? external_node_path_default().join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : external_node_path_default().join(reactFolder, 'widgets', ...folders, folderName);
644
+ };
645
+ const validateMove = (reactFolder, module, rawName)=>{
646
+ const nameError = NestedName.validate(rawName);
647
+ if (true !== nameError) return nameError;
648
+ const target = react_module_move_targetPath(reactFolder, module, rawName);
649
+ if (target !== module.path && external_node_fs_default().existsSync(target)) return `${external_node_path_default().relative(reactFolder, target)} already exists`;
650
+ if (target.startsWith(`${module.path}${external_node_path_default().sep}`)) return 'A widget cannot be moved into itself';
651
+ return true;
652
+ };
653
+ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
654
+ const newName = new NestedName(rawName);
655
+ const target = react_module_move_targetPath(reactFolder, module, rawName);
656
+ const newClassName = newName.ClassName;
657
+ const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${module_move_escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
658
+ const oldFolder = 'page' === module.kind ? external_node_path_default().dirname(module.path) : module.path;
659
+ const newFolder = 'page' === module.kind ? external_node_path_default().dirname(target) : target;
660
+ const ownsPath = (candidate)=>'page' === module.kind ? external_node_path_default().dirname(candidate) === oldFolder && new RegExp(`^${module_move_escapeRegExp(module.fileBase)}-page(?:\\.|$)`).test(external_node_path_default().basename(candidate)) : candidate === oldFolder || candidate.startsWith(`${oldFolder}${external_node_path_default().sep}`);
661
+ const movedPath = (candidate)=>{
662
+ if (!ownsPath(candidate)) return;
663
+ const segments = external_node_path_default().relative(oldFolder, candidate).split(external_node_path_default().sep);
664
+ const last = segments.length - 1;
665
+ segments[last] = renameFile(segments[last]);
666
+ return external_node_path_default().join(newFolder, ...segments);
667
+ };
668
+ 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)) : module_move_walk(oldFolder);
669
+ const moves = new Map(moduleFiles.map((file)=>[
670
+ file,
671
+ movedPath(file) ?? file
672
+ ]));
673
+ const suffixes = 'page' === module.kind ? 'Page' : 'Widget|UIModel';
674
+ const classPattern = new RegExp(`(?<![\\w$])(use)?${module_move_escapeRegExp(module.ClassName)}(?=${suffixes})`, 'g');
675
+ const oldTitle = `Widgets/${module.name.split('/').map((segment)=>new NestedName(segment).ClassName).join('/')}`;
676
+ const titlePattern = new RegExp(`(['"\`])${module_move_escapeRegExp(oldTitle)}\\1`, 'g');
677
+ const newTitle = [
678
+ 'Widgets',
679
+ ...newName.classNameSegments
680
+ ].join('/');
681
+ return module_move_stageModuleMove({
682
+ projectRoot,
683
+ stopAt: reactFolder,
684
+ moves,
685
+ movedPath,
686
+ rename: (content, { moved })=>{
687
+ const renamed = content.replace(classPattern, (_, use = '')=>`${use}${newClassName}`);
688
+ return moved && 'widget' === module.kind ? renamed.replace(titlePattern, (_, quote)=>`${quote}${newTitle}${quote}`) : renamed;
689
+ }
690
+ });
691
+ };
621
692
  const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
622
693
  const reactFolder = presentationReactFolder.path;
623
694
  const modules = findReactModules(reactFolder, kind);
@@ -651,7 +722,7 @@ const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
651
722
  message: 'Apply?',
652
723
  default: true
653
724
  })) {
654
- discardPendingChanges();
725
+ file_system_discardPendingChanges();
655
726
  console.log('Cancelled: nothing was written.');
656
727
  }
657
728
  };
@@ -1,5 +1,6 @@
1
1
  export * from './add-integration';
2
2
  export * from './initialize';
3
+ export * from './move-backend-unit';
3
4
  export * from './move-react-module';
4
5
  export * from './scaffold-new-aggregate';
5
6
  export * from './scaffold-new-application-port';
@@ -0,0 +1,7 @@
1
+ import { Folder } from '../file-system';
2
+ /**
3
+ * Renames a unit of a bounded context or the Shared Kernel, or moves it
4
+ * to another context or the Shared Kernel, with every file, name and
5
+ * import that follows it.
6
+ */
7
+ export declare const moveBackendUnitUseCase: (ownerFolder: Folder) => Promise<void>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@domain-first/project-structure",
3
3
  "description": "Build and manage your Domain-First project structure with CLI",
4
- "version": "7.0.0",
4
+ "version": "7.1.0",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -10,7 +10,7 @@ Generated files contain placeholders: empty classes, `{}` schemas, `[]` dependen
10
10
  ## Ground rules
11
11
 
12
12
  - New files need an approved work plan (`df-ps-scaffold`, rule 1) and come only via df-scaffold or its listed exceptions (rule 2). Edits to existing files don't need approval; report them.
13
- - Keep generated names and paths: barrels, wiring, specs, and `presentation/rest/wires.ts` import them.
13
+ - Keep generated names and paths: barrels, wiring, specs, and `presentation/rest/wires.ts` import them. To rename or move a module, use `Move or rename` of df-scaffold (`df-ps-scaffold/references/units/move-or-rename.md`), never by hand.
14
14
  - Layers: domain imports nothing from other layers. Application uses domain and its own abstractions. Infrastructure implements repositories, contracts, and ports, and may use application ports (of its context and the Shared Kernel), never other application modules. Infrastructure needing logic from an application service means the logic is misplaced: pure logic without ports → a domain service; logic over ports → call those ports directly; technical logic (mapping, retries, formatting for an external API) → an infrastructure service. Presentation calls application handlers. Only `wiring/` knows concrete classes.
15
15
  - Constructors take abstractions (`OrderRepository`, abstract `PlaceOrderCommand`, port `PaymentGateway`), never `PrismaOrderRepository`.
16
16
  - Implementation order: domain → application → schema tool runs (migrations, only if infrastructure needs data the database lacks) → infrastructure (repositories, commands/queries, adapters) → endpoints → other tool runs (OpenAPI, API client) → React. Widgets need the regenerated client. How to run tools and handle their output: the project's scripts skill (`project-scripts`), if there is one.
@@ -75,7 +75,7 @@ Anything else (helpers, types, constants, mappers, wiring, barrels): put it in a
75
75
 
76
76
  If the CLI can't run, give the user the menu path and answers to run `npx df-scaffold` (or `npx df-react` for React modules) themselves (`! npx df-scaffold`). Never hand-write its output. Missing generated files are only recreated by re-running the generator, as an approved overwrite.
77
77
 
78
- Moving or renaming a page or widget is a df-react run, never done by hand: see `df-ps-react`.
78
+ Moving or renaming a module (aggregate, entity, value object, service, port, query, command, use case) is a df-scaffold run, `Move or rename` (`references/units/move-or-rename.md`); a page or widget, a df-react run (`df-ps-react`). Never by hand: it creates files at the new paths, so it needs an approved plan.
79
79
 
80
80
  ### 3. New dependencies only through df-scaffold
81
81
 
@@ -106,6 +106,7 @@ One file per unit in `references/units/`: when to choose it, how to generate it
106
106
  | Port + adapters | `port.md` | Application → New Port |
107
107
  | REST endpoint | `endpoint.md` | Presentation → New Handlers-REST Endpoint |
108
108
  | Dependency of an existing module | `wire-dependency.md` | Wire dependency |
109
+ | Moving or renaming a module | `move-or-rename.md` | Move or rename |
109
110
  | React modules | `df-ps-react` skill | `df-react` |
110
111
 
111
112
  ## Preparing runs
@@ -143,7 +144,7 @@ Check every run: exit code 0, no `WARNING`/`ABORTED`, and exactly the planned fi
143
144
  | Infrastructure | New Service | New Service |
144
145
  | Presentation | New Handlers-REST Endpoint (needs handlers-rest), New Service | New Service |
145
146
 
146
- With `@domain-first/wire`, the layer menu of a context and of the Shared Kernel also has `Wire dependency`: it adds dependencies to an existing wired module.
147
+ With `@domain-first/wire`, the layer menu of a context and of the Shared Kernel also has `Wire dependency`: it adds dependencies to an existing wired module. Every layer menu has `Move or rename`.
147
148
 
148
149
  The main menu also has `Scaffold new bounded context`. React modules come from a separate CLI, `df-react`: see `df-ps-react`.
149
150
 
@@ -0,0 +1,21 @@
1
+ # Move or rename
2
+
3
+ When: a module's name no longer fits, or it belongs elsewhere: another bounded context, the Shared Kernel (entities, value objects, services, ports only), or in or out of an aggregate. Never move, rename or copy module files by hand, and never rename their classes, wires or parameters by hand: the CLI keeps files, names and imports in sync.
4
+
5
+ ## Generate (context and Shared Kernel)
6
+
7
+ Prompts: `Module:` (select, grouped by kind; entities and value objects of an aggregate show it: `order-line (order)`) → `Move to:` (`Bounded Context: <current> (stays)`, other contexts, `Shared Kernel` for the kinds it has) → `Aggregate:` (entities and value objects only, when the target context has aggregates: `No aggregate` or one of them) → `New name:` (default: the current one) → `Apply?`.
8
+
9
+ `… "pick:Move or rename" pick:order "pick:Bounded Context: sales" text:purchase yes`
10
+ `… "pick:Move or rename" pick:money "pick:Shared Kernel" default yes`
11
+ `… "pick:Move or rename" pick:order-line "pick:Bounded Context: sales" "pick:No aggregate" default yes`
12
+
13
+ Every file of the module moves (contract, implementations, wire, specs; an aggregate with its whole folder), every import of it follows, and derived names change in the module and its importers: `OrderRepository`, `PrismaOrderRepository`, `wireOrderRepository`, dependents' `orderRepository` parameters, an aggregate's in-memory DB section. An entity leaving its aggregate is no longer re-exported there; its importers import its file.
14
+
15
+ Before `Apply?` the CLI lists the files to move and to update: check them against the plan. A move that would make a context import another one prints `Nothing was moved: these imports would cross a bounded context boundary.` with the imports: nothing changed. Fix the design instead (`../choosing-components.md`, step 9: the other context gets its own query or command), or move the dependency first.
16
+
17
+ In the plan, list a move as a run: old → new place and name, the files to move (`→`) and the files whose imports or names change (`~`).
18
+
19
+ ## Implement
20
+
21
+ Nothing to fill in. Re-read the moved module's files: names inside method bodies that only resemble the old name (local variables, strings, comments) are not renamed. Run `npx df-lint` and the project's tsc/tests.