@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.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:',
package/dist/init.cjs CHANGED
@@ -550,6 +550,22 @@ const in_memory_db_scaffoldInMemoryDb = (shared)=>{
550
550
  'infrastructure-services'
551
551
  ]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
552
552
  };
553
+ const uncountableEndings = [
554
+ 'data',
555
+ 'info',
556
+ 'usage',
557
+ 'feedback',
558
+ 'media',
559
+ 'ware',
560
+ 'equipment',
561
+ 'information',
562
+ 'knowledge',
563
+ 'traffic',
564
+ 'telemetry',
565
+ 'analytics',
566
+ 'series'
567
+ ];
568
+ new RegExp(`(${uncountableEndings.join('|')})$`, 'i');
553
569
  const hasDependency = (name)=>{
554
570
  const manifestFile = new file_system_File(external_node_path_default().join(new project_root_ProjectRoot().path, 'package.json'));
555
571
  if (!manifestFile.exists) return false;
@@ -830,6 +846,51 @@ new Set([
830
846
  'coverage',
831
847
  'storybook-static'
832
848
  ]);
849
+ const serviceLayout = (layer)=>({
850
+ title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
851
+ core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
852
+ files: ({ name })=>[
853
+ `${layer}/services/${name}-${layer}-service.ts`,
854
+ `${layer}/services/${name}-${layer}-service.spec.ts`,
855
+ `wiring/${layer}-services/wire-${name}-${layer}-service.ts`
856
+ ],
857
+ wired: true,
858
+ sharedKernel: true
859
+ });
860
+ const handlerLayout = (kind)=>{
861
+ const folder = 'command' === kind ? 'commands' : 'queries';
862
+ const Suffix = 'command' === kind ? 'Command' : 'Query';
863
+ return {
864
+ title: 'command' === kind ? 'Commands' : 'Queries',
865
+ core: (ClassName)=>`${ClassName}${Suffix}`,
866
+ files: ({ name }, labels)=>[
867
+ `application/${folder}/${name}-${kind}.ts`,
868
+ `application/${folder}/${name}-${kind}.spec.ts`,
869
+ ...labels.map((label)=>`infrastructure/${folder}/${label}/${label}-${name}-${kind}.ts`),
870
+ `wiring/${folder}/wire-${name}-${kind}.ts`
871
+ ],
872
+ implementations: `infrastructure/${folder}`,
873
+ wired: true,
874
+ sharedKernel: false
875
+ };
876
+ };
877
+ const domainModelLayout = (kind)=>{
878
+ const folder = 'entity' === kind ? 'entities' : 'value-objects';
879
+ return {
880
+ title: 'entity' === kind ? 'Entities' : 'Value objects',
881
+ core: (ClassName)=>ClassName,
882
+ files: ({ name, aggregate })=>{
883
+ const base = aggregate ? `domain/aggregates/${aggregate}/${folder}` : `domain/${folder}`;
884
+ return [
885
+ `${base}/${name}.${kind}.ts`,
886
+ `${base}/${name}.${kind}.spec.ts`
887
+ ];
888
+ },
889
+ wired: false,
890
+ sharedKernel: true
891
+ };
892
+ };
893
+ domainModelLayout('entity'), domainModelLayout('value-object'), serviceLayout('domain'), serviceLayout('application'), serviceLayout('infrastructure'), serviceLayout('presentation'), handlerLayout('command'), handlerLayout('query');
833
894
  const help = `Usage: df-init
834
895
 
835
896
  Initializes a Domain-First project: asks for the source folder, the
@@ -497,6 +497,22 @@ const in_memory_db_scaffoldInMemoryDb = (shared)=>{
497
497
  ]).createFile('wire-in-memory-db-infrastructure-service.ts', inMemoryDbWiring);
498
498
  };
499
499
  const inMemoryDbScaffolded = ()=>serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
500
+ const uncountableEndings = [
501
+ 'data',
502
+ 'info',
503
+ 'usage',
504
+ 'feedback',
505
+ 'media',
506
+ 'ware',
507
+ 'equipment',
508
+ 'information',
509
+ 'knowledge',
510
+ 'traffic',
511
+ 'telemetry',
512
+ 'analytics',
513
+ 'series'
514
+ ];
515
+ new RegExp(`(${uncountableEndings.join('|')})$`, 'i');
500
516
  const addInMemoryDb = ()=>{
501
517
  const config = config_file_ConfigFile.Instance.data;
502
518
  if (!config.withInMemoryDb) config_file_ConfigFile.write({
@@ -2030,6 +2046,51 @@ new Set([
2030
2046
  'coverage',
2031
2047
  'storybook-static'
2032
2048
  ]);
2049
+ const serviceLayout = (layer)=>({
2050
+ title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
2051
+ core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
2052
+ files: ({ name })=>[
2053
+ `${layer}/services/${name}-${layer}-service.ts`,
2054
+ `${layer}/services/${name}-${layer}-service.spec.ts`,
2055
+ `wiring/${layer}-services/wire-${name}-${layer}-service.ts`
2056
+ ],
2057
+ wired: true,
2058
+ sharedKernel: true
2059
+ });
2060
+ const handlerLayout = (kind)=>{
2061
+ const folder = 'command' === kind ? 'commands' : 'queries';
2062
+ const Suffix = 'command' === kind ? 'Command' : 'Query';
2063
+ return {
2064
+ title: 'command' === kind ? 'Commands' : 'Queries',
2065
+ core: (ClassName)=>`${ClassName}${Suffix}`,
2066
+ files: ({ name }, labels)=>[
2067
+ `application/${folder}/${name}-${kind}.ts`,
2068
+ `application/${folder}/${name}-${kind}.spec.ts`,
2069
+ ...labels.map((label)=>`infrastructure/${folder}/${label}/${label}-${name}-${kind}.ts`),
2070
+ `wiring/${folder}/wire-${name}-${kind}.ts`
2071
+ ],
2072
+ implementations: `infrastructure/${folder}`,
2073
+ wired: true,
2074
+ sharedKernel: false
2075
+ };
2076
+ };
2077
+ const domainModelLayout = (kind)=>{
2078
+ const folder = 'entity' === kind ? 'entities' : 'value-objects';
2079
+ return {
2080
+ title: 'entity' === kind ? 'Entities' : 'Value objects',
2081
+ core: (ClassName)=>ClassName,
2082
+ files: ({ name, aggregate })=>{
2083
+ const base = aggregate ? `domain/aggregates/${aggregate}/${folder}` : `domain/${folder}`;
2084
+ return [
2085
+ `${base}/${name}.${kind}.ts`,
2086
+ `${base}/${name}.${kind}.spec.ts`
2087
+ ];
2088
+ },
2089
+ wired: false,
2090
+ sharedKernel: true
2091
+ };
2092
+ };
2093
+ domainModelLayout('entity'), domainModelLayout('value-object'), serviceLayout('domain'), serviceLayout('application'), serviceLayout('infrastructure'), serviceLayout('presentation'), handlerLayout('command'), handlerLayout('query');
2033
2094
  const help = `Usage: df-integration
2034
2095
 
2035
2096
  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
  }
@@ -340,6 +340,22 @@ const save_pending_changes_savePendingChanges = async ()=>{
340
340
  writePendingChanges();
341
341
  return true;
342
342
  };
343
+ const uncountableEndings = [
344
+ 'data',
345
+ 'info',
346
+ 'usage',
347
+ 'feedback',
348
+ 'media',
349
+ 'ware',
350
+ 'equipment',
351
+ 'information',
352
+ 'knowledge',
353
+ 'traffic',
354
+ 'telemetry',
355
+ 'analytics',
356
+ 'series'
357
+ ];
358
+ new RegExp(`(${uncountableEndings.join('|')})$`, 'i');
343
359
  require("node:module");
344
360
  const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
345
361
  class unknown_format_naming_UnknownFormatNaming {
@@ -425,71 +441,21 @@ const ignoredFolders = new Set([
425
441
  'coverage',
426
442
  'storybook-static'
427
443
  ]);
428
- const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
429
- const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
430
- const react_module_move_walk = (folder)=>{
444
+ const module_move_codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
445
+ const module_move_escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
446
+ const module_move_walk = (folder)=>{
431
447
  if (!external_node_fs_default().existsSync(folder)) return [];
432
448
  return external_node_fs_default().readdirSync(folder, {
433
449
  withFileTypes: true
434
450
  }).flatMap((entry)=>{
435
451
  const entryPath = external_node_path_default().join(folder, entry.name);
436
- if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : react_module_move_walk(entryPath);
452
+ if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : module_move_walk(entryPath);
437
453
  return entry.isFile() ? [
438
454
  entryPath
439
455
  ] : [];
440
456
  });
441
457
  };
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
- };
458
+ const module_move_toPosix = (value)=>value.split(external_node_path_default().sep).join('/');
493
459
  const readAliases = (projectRoot)=>{
494
460
  const tsconfig = external_node_path_default().join(projectRoot, 'tsconfig.json');
495
461
  if (!external_node_fs_default().existsSync(tsconfig)) return [];
@@ -507,7 +473,7 @@ const readAliases = (projectRoot)=>{
507
473
  const specifierPattern = /(\bfrom\s*|\bimport\s*\(\s*|\bimport\s+|\brequire\s*\(\s*|\bmock\s*\(\s*)(['"])([^'"\n]+)\2/g;
508
474
  const reExportPattern = /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*(['"])([^'"\n]+)\1/g;
509
475
  const importPaths = (file)=>{
510
- const withoutExtension = file.replace(codeExtension, '');
476
+ const withoutExtension = file.replace(module_move_codeExtension, '');
511
477
  return 'index' === external_node_path_default().basename(withoutExtension) ? [
512
478
  withoutExtension,
513
479
  external_node_path_default().dirname(withoutExtension)
@@ -515,26 +481,7 @@ const importPaths = (file)=>{
515
481
  withoutExtension
516
482
  ];
517
483
  };
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
- ]));
484
+ const module_move_projectImports = (projectRoot)=>{
538
485
  const aliases = readAliases(projectRoot);
539
486
  const resolve = (specifier, fromFile)=>{
540
487
  if (specifier.startsWith('.')) return {
@@ -548,25 +495,29 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
548
495
  } : void 0;
549
496
  };
550
497
  const specifierFor = (fromFile, toPath, alias)=>{
551
- const aliased = alias && toPosix(external_node_path_default().relative(alias.target, toPath));
498
+ const aliased = alias && module_move_toPosix(external_node_path_default().relative(alias.target, toPath));
552
499
  if (aliased && !aliased.startsWith('..')) return `${alias.prefix}${aliased}`;
553
- const relative = toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toPath));
500
+ const relative = module_move_toPosix(external_node_path_default().relative(external_node_path_default().dirname(fromFile), toPath));
554
501
  return relative.startsWith('.') ? relative : `./${relative}`;
555
502
  };
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)=>[
503
+ const codeFiles = new Map(module_move_walk(projectRoot).filter((file)=>module_move_codeExtension.test(file)).map((file)=>[
565
504
  file,
566
505
  external_node_fs_default().readFileSync(file, 'utf8')
567
506
  ]));
507
+ const importsOf = (file)=>[
508
+ ...(codeFiles.get(file) ?? '').matchAll(specifierPattern)
509
+ ].map(([, , , specifier])=>resolve(specifier, file)?.resolved).filter((resolved)=>!!resolved);
510
+ return {
511
+ resolve,
512
+ specifierFor,
513
+ codeFiles,
514
+ importsOf
515
+ };
516
+ };
517
+ const module_move_stageModuleMove = ({ projectRoot, stopAt, moves, movedPath, rename, everyFile = (content)=>content })=>{
518
+ const { resolve, specifierFor, codeFiles } = module_move_projectImports(projectRoot);
568
519
  const barrels = new Set();
569
- const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
520
+ const isBarrel = (resolved)=>barrels.has(resolved.replace(module_move_codeExtension, ''));
570
521
  for(let found = true; found;){
571
522
  found = false;
572
523
  for (const [file, content] of codeFiles){
@@ -594,18 +545,20 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
594
545
  const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
595
546
  return `${keyword}${quote}${next}${quote}`;
596
547
  });
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;
548
+ const changed = everyFile(rewritten);
549
+ if (!referencesModule && !moves.has(oldFile)) return changed;
550
+ return rename(changed, {
551
+ moved: moves.has(oldFile)
552
+ });
600
553
  };
601
- for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new file_system_File(file).moveTo(newFile, reactFolder);
554
+ for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new file_system_File(file).moveTo(newFile, stopAt);
602
555
  const updated = [];
603
556
  for (const [file, content] of codeFiles){
604
557
  const newFile = moves.get(file);
605
558
  const next = rewrite(content, file, newFile ?? file);
606
559
  if (newFile && newFile !== file) {
607
560
  new file_system_File(newFile).data = next;
608
- new file_system_File(file).delete(reactFolder);
561
+ new file_system_File(file).delete(stopAt);
609
562
  } else if (next !== content) {
610
563
  new file_system_File(file).update(next);
611
564
  if (!newFile) updated.push(file);
@@ -618,6 +571,140 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
618
571
  updated
619
572
  };
620
573
  };
574
+ const serviceLayout = (layer)=>({
575
+ title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
576
+ core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
577
+ files: ({ name })=>[
578
+ `${layer}/services/${name}-${layer}-service.ts`,
579
+ `${layer}/services/${name}-${layer}-service.spec.ts`,
580
+ `wiring/${layer}-services/wire-${name}-${layer}-service.ts`
581
+ ],
582
+ wired: true,
583
+ sharedKernel: true
584
+ });
585
+ const handlerLayout = (kind)=>{
586
+ const folder = 'command' === kind ? 'commands' : 'queries';
587
+ const Suffix = 'command' === kind ? 'Command' : 'Query';
588
+ return {
589
+ title: 'command' === kind ? 'Commands' : 'Queries',
590
+ core: (ClassName)=>`${ClassName}${Suffix}`,
591
+ files: ({ name }, labels)=>[
592
+ `application/${folder}/${name}-${kind}.ts`,
593
+ `application/${folder}/${name}-${kind}.spec.ts`,
594
+ ...labels.map((label)=>`infrastructure/${folder}/${label}/${label}-${name}-${kind}.ts`),
595
+ `wiring/${folder}/wire-${name}-${kind}.ts`
596
+ ],
597
+ implementations: `infrastructure/${folder}`,
598
+ wired: true,
599
+ sharedKernel: false
600
+ };
601
+ };
602
+ const domainModelLayout = (kind)=>{
603
+ const folder = 'entity' === kind ? 'entities' : 'value-objects';
604
+ return {
605
+ title: 'entity' === kind ? 'Entities' : 'Value objects',
606
+ core: (ClassName)=>ClassName,
607
+ files: ({ name, aggregate })=>{
608
+ const base = aggregate ? `domain/aggregates/${aggregate}/${folder}` : `domain/${folder}`;
609
+ return [
610
+ `${base}/${name}.${kind}.ts`,
611
+ `${base}/${name}.${kind}.spec.ts`
612
+ ];
613
+ },
614
+ wired: false,
615
+ sharedKernel: true
616
+ };
617
+ };
618
+ domainModelLayout('entity'), domainModelLayout('value-object'), serviceLayout('domain'), serviceLayout('application'), serviceLayout('infrastructure'), serviceLayout('presentation'), handlerLayout('command'), handlerLayout('query');
619
+ const nestedName = (folders, fileBase)=>{
620
+ const prefix = `${folders.join('-')}-`;
621
+ const last = folders.length && fileBase.startsWith(prefix) ? fileBase.slice(prefix.length) : fileBase;
622
+ return [
623
+ ...folders,
624
+ last
625
+ ].join('/');
626
+ };
627
+ const declaredClassName = (filePath, suffix, name)=>{
628
+ const content = external_node_fs_default().readFileSync(filePath, 'utf8');
629
+ const declared = content.match(new RegExp(`export\\s+(?:const|function)\\s+(\\w+)${suffix}\\b`))?.[1];
630
+ return declared ?? new NestedName(name).ClassName;
631
+ };
632
+ const findReactModules = (reactFolder, kind)=>{
633
+ const modules = 'page' === kind ? module_move_walk(external_node_path_default().join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
634
+ 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);
635
+ const fileBase = external_node_path_default().basename(file, '-page.tsx');
636
+ const name = nestedName(folders, fileBase);
637
+ return {
638
+ kind,
639
+ name,
640
+ path: file,
641
+ fileBase,
642
+ ClassName: declaredClassName(file, 'Page', name)
643
+ };
644
+ }) : module_move_walk(external_node_path_default().join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
645
+ const folder = external_node_path_default().dirname(file);
646
+ const name = module_move_toPosix(external_node_path_default().relative(external_node_path_default().join(reactFolder, 'widgets'), folder));
647
+ return {
648
+ kind,
649
+ name,
650
+ path: folder,
651
+ fileBase: external_node_path_default().basename(file, '-widget.tsx'),
652
+ ClassName: declaredClassName(file, 'Widget', name)
653
+ };
654
+ });
655
+ return modules.sort((a, b)=>a.name.localeCompare(b.name));
656
+ };
657
+ const react_module_move_targetPath = (reactFolder, module, rawName)=>{
658
+ const { folders, folderName, fileName } = new NestedName(rawName);
659
+ return 'page' === module.kind ? external_node_path_default().join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : external_node_path_default().join(reactFolder, 'widgets', ...folders, folderName);
660
+ };
661
+ const validateMove = (reactFolder, module, rawName)=>{
662
+ const nameError = NestedName.validate(rawName);
663
+ if (true !== nameError) return nameError;
664
+ const target = react_module_move_targetPath(reactFolder, module, rawName);
665
+ if (target !== module.path && external_node_fs_default().existsSync(target)) return `${external_node_path_default().relative(reactFolder, target)} already exists`;
666
+ if (target.startsWith(`${module.path}${external_node_path_default().sep}`)) return 'A widget cannot be moved into itself';
667
+ return true;
668
+ };
669
+ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
670
+ const newName = new NestedName(rawName);
671
+ const target = react_module_move_targetPath(reactFolder, module, rawName);
672
+ const newClassName = newName.ClassName;
673
+ const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${module_move_escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
674
+ const oldFolder = 'page' === module.kind ? external_node_path_default().dirname(module.path) : module.path;
675
+ const newFolder = 'page' === module.kind ? external_node_path_default().dirname(target) : target;
676
+ 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}`);
677
+ const movedPath = (candidate)=>{
678
+ if (!ownsPath(candidate)) return;
679
+ const segments = external_node_path_default().relative(oldFolder, candidate).split(external_node_path_default().sep);
680
+ const last = segments.length - 1;
681
+ segments[last] = renameFile(segments[last]);
682
+ return external_node_path_default().join(newFolder, ...segments);
683
+ };
684
+ 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);
685
+ const moves = new Map(moduleFiles.map((file)=>[
686
+ file,
687
+ movedPath(file) ?? file
688
+ ]));
689
+ const suffixes = 'page' === module.kind ? 'Page' : 'Widget|UIModel';
690
+ const classPattern = new RegExp(`(?<![\\w$])(use)?${module_move_escapeRegExp(module.ClassName)}(?=${suffixes})`, 'g');
691
+ const oldTitle = `Widgets/${module.name.split('/').map((segment)=>new NestedName(segment).ClassName).join('/')}`;
692
+ const titlePattern = new RegExp(`(['"\`])${module_move_escapeRegExp(oldTitle)}\\1`, 'g');
693
+ const newTitle = [
694
+ 'Widgets',
695
+ ...newName.classNameSegments
696
+ ].join('/');
697
+ return module_move_stageModuleMove({
698
+ projectRoot,
699
+ stopAt: reactFolder,
700
+ moves,
701
+ movedPath,
702
+ rename: (content, { moved })=>{
703
+ const renamed = content.replace(classPattern, (_, use = '')=>`${use}${newClassName}`);
704
+ return moved && 'widget' === module.kind ? renamed.replace(titlePattern, (_, quote)=>`${quote}${newTitle}${quote}`) : renamed;
705
+ }
706
+ });
707
+ };
621
708
  const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
622
709
  const reactFolder = presentationReactFolder.path;
623
710
  const modules = findReactModules(reactFolder, kind);
@@ -651,7 +738,7 @@ const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
651
738
  message: 'Apply?',
652
739
  default: true
653
740
  })) {
654
- discardPendingChanges();
741
+ file_system_discardPendingChanges();
655
742
  console.log('Cancelled: nothing was written.');
656
743
  }
657
744
  };
@@ -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.1",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",