@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/287.js CHANGED
@@ -188,8 +188,26 @@ const scaffoldInMemoryDb = (shared)=>{
188
188
  };
189
189
  const inMemoryDbScaffolded = ()=>serviceFile().exists && (!in_memory_db_withWiring() || in_memory_db_wireFile().exists);
190
190
  const usesInMemoryDb = (implementationType)=>Boolean(ConfigFile.Instance.data.withInMemoryDb) && new UnknownFormatNaming(implementationType).fileName === inMemoryImplementationType && inMemoryDbScaffolded();
191
+ const uncountableEndings = [
192
+ 'data',
193
+ 'info',
194
+ 'usage',
195
+ 'feedback',
196
+ 'media',
197
+ 'ware',
198
+ 'equipment',
199
+ 'information',
200
+ 'knowledge',
201
+ 'traffic',
202
+ 'telemetry',
203
+ 'analytics',
204
+ 'series'
205
+ ];
206
+ const uncountable = new RegExp(`(${uncountableEndings.join('|')})$`, 'i');
191
207
  const plural = (word)=>{
208
+ if (uncountable.test(word)) return word;
192
209
  if (/[^aeiou]y$/i.test(word)) return `${word.slice(0, -1)}ies`;
210
+ if (/(^|[^aeiou]|qu)[aeiou]z$/i.test(word)) return `${word}zes`;
193
211
  if (/(s|x|z|ch|sh)$/i.test(word)) return `${word}es`;
194
212
  return `${word}s`;
195
213
  };
@@ -1927,56 +1945,6 @@ const walk = (folder)=>{
1927
1945
  });
1928
1946
  };
1929
1947
  const toPosix = (value)=>value.split(node_path.sep).join('/');
1930
- const nestedName = (folders, fileBase)=>{
1931
- const prefix = `${folders.join('-')}-`;
1932
- const last = folders.length && fileBase.startsWith(prefix) ? fileBase.slice(prefix.length) : fileBase;
1933
- return [
1934
- ...folders,
1935
- last
1936
- ].join('/');
1937
- };
1938
- const declaredClassName = (filePath, suffix, name)=>{
1939
- const content = node_fs.readFileSync(filePath, 'utf8');
1940
- const declared = content.match(new RegExp(`export\\s+(?:const|function)\\s+(\\w+)${suffix}\\b`))?.[1];
1941
- return declared ?? new NestedName(name).ClassName;
1942
- };
1943
- const findReactModules = (reactFolder, kind)=>{
1944
- const modules = 'page' === kind ? walk(node_path.join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
1945
- const folders = node_path.relative(node_path.join(reactFolder, 'pages'), node_path.dirname(file)).split(node_path.sep).filter((segment)=>!!segment);
1946
- const fileBase = node_path.basename(file, '-page.tsx');
1947
- const name = nestedName(folders, fileBase);
1948
- return {
1949
- kind,
1950
- name,
1951
- path: file,
1952
- fileBase,
1953
- ClassName: declaredClassName(file, 'Page', name)
1954
- };
1955
- }) : walk(node_path.join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
1956
- const folder = node_path.dirname(file);
1957
- const name = toPosix(node_path.relative(node_path.join(reactFolder, 'widgets'), folder));
1958
- return {
1959
- kind,
1960
- name,
1961
- path: folder,
1962
- fileBase: node_path.basename(file, '-widget.tsx'),
1963
- ClassName: declaredClassName(file, 'Widget', name)
1964
- };
1965
- });
1966
- return modules.sort((a, b)=>a.name.localeCompare(b.name));
1967
- };
1968
- const targetPath = (reactFolder, module, rawName)=>{
1969
- const { folders, folderName, fileName } = new NestedName(rawName);
1970
- return 'page' === module.kind ? node_path.join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : node_path.join(reactFolder, 'widgets', ...folders, folderName);
1971
- };
1972
- const validateMove = (reactFolder, module, rawName)=>{
1973
- const nameError = NestedName.validate(rawName);
1974
- if (true !== nameError) return nameError;
1975
- const target = targetPath(reactFolder, module, rawName);
1976
- if (target !== module.path && node_fs.existsSync(target)) return `${node_path.relative(reactFolder, target)} already exists`;
1977
- if (target.startsWith(`${module.path}${node_path.sep}`)) return 'A widget cannot be moved into itself';
1978
- return true;
1979
- };
1980
1948
  const readAliases = (projectRoot)=>{
1981
1949
  const tsconfig = node_path.join(projectRoot, 'tsconfig.json');
1982
1950
  if (!node_fs.existsSync(tsconfig)) return [];
@@ -2002,26 +1970,7 @@ const importPaths = (file)=>{
2002
1970
  withoutExtension
2003
1971
  ];
2004
1972
  };
2005
- const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
2006
- const newName = new NestedName(rawName);
2007
- const target = targetPath(reactFolder, module, rawName);
2008
- const newClassName = newName.ClassName;
2009
- const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
2010
- const oldFolder = 'page' === module.kind ? node_path.dirname(module.path) : module.path;
2011
- const newFolder = 'page' === module.kind ? node_path.dirname(target) : target;
2012
- const ownsPath = (candidate)=>'page' === module.kind ? node_path.dirname(candidate) === oldFolder && new RegExp(`^${escapeRegExp(module.fileBase)}-page(?:\\.|$)`).test(node_path.basename(candidate)) : candidate === oldFolder || candidate.startsWith(`${oldFolder}${node_path.sep}`);
2013
- const movedPath = (candidate)=>{
2014
- if (!ownsPath(candidate)) return;
2015
- const segments = node_path.relative(oldFolder, candidate).split(node_path.sep);
2016
- const last = segments.length - 1;
2017
- segments[last] = renameFile(segments[last]);
2018
- return node_path.join(newFolder, ...segments);
2019
- };
2020
- const moduleFiles = 'page' === module.kind ? node_fs.readdirSync(oldFolder).map((name)=>node_path.join(oldFolder, name)).filter((file)=>node_fs.statSync(file).isFile() && ownsPath(file)) : walk(oldFolder);
2021
- const moves = new Map(moduleFiles.map((file)=>[
2022
- file,
2023
- movedPath(file) ?? file
2024
- ]));
1973
+ const projectImports = (projectRoot)=>{
2025
1974
  const aliases = readAliases(projectRoot);
2026
1975
  const resolve = (specifier, fromFile)=>{
2027
1976
  if (specifier.startsWith('.')) return {
@@ -2040,18 +1989,22 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
2040
1989
  const relative = toPosix(node_path.relative(node_path.dirname(fromFile), toPath));
2041
1990
  return relative.startsWith('.') ? relative : `./${relative}`;
2042
1991
  };
2043
- const suffixes = 'page' === module.kind ? 'Page' : 'Widget|UIModel';
2044
- const classPattern = new RegExp(`(?<![\\w$])(use)?${escapeRegExp(module.ClassName)}(?=${suffixes})`, 'g');
2045
- const oldTitle = `Widgets/${module.name.split('/').map((segment)=>new NestedName(segment).ClassName).join('/')}`;
2046
- const titlePattern = new RegExp(`(['"\`])${escapeRegExp(oldTitle)}\\1`, 'g');
2047
- const newTitle = [
2048
- 'Widgets',
2049
- ...newName.classNameSegments
2050
- ].join('/');
2051
1992
  const codeFiles = new Map(walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
2052
1993
  file,
2053
1994
  node_fs.readFileSync(file, 'utf8')
2054
1995
  ]));
1996
+ const importsOf = (file)=>[
1997
+ ...(codeFiles.get(file) ?? '').matchAll(specifierPattern)
1998
+ ].map(([, , , specifier])=>resolve(specifier, file)?.resolved).filter((resolved)=>!!resolved);
1999
+ return {
2000
+ resolve,
2001
+ specifierFor,
2002
+ codeFiles,
2003
+ importsOf
2004
+ };
2005
+ };
2006
+ const stageModuleMove = ({ projectRoot, stopAt, moves, movedPath, rename, everyFile = (content)=>content })=>{
2007
+ const { resolve, specifierFor, codeFiles } = projectImports(projectRoot);
2055
2008
  const barrels = new Set();
2056
2009
  const isBarrel = (resolved)=>barrels.has(resolved.replace(codeExtension, ''));
2057
2010
  for(let found = true; found;){
@@ -2081,18 +2034,20 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
2081
2034
  const next = specifierFor(newFile, moved ?? resolution.resolved, resolution.alias);
2082
2035
  return `${keyword}${quote}${next}${quote}`;
2083
2036
  });
2084
- if (!referencesModule && !moves.has(oldFile)) return content;
2085
- const renamed = rewritten.replace(classPattern, (_, use = '')=>`${use}${newClassName}`);
2086
- return moves.has(oldFile) && 'widget' === module.kind ? renamed.replace(titlePattern, (_, quote)=>`${quote}${newTitle}${quote}`) : renamed;
2037
+ const changed = everyFile(rewritten);
2038
+ if (!referencesModule && !moves.has(oldFile)) return changed;
2039
+ return rename(changed, {
2040
+ moved: moves.has(oldFile)
2041
+ });
2087
2042
  };
2088
- for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new File(file).moveTo(newFile, reactFolder);
2043
+ for (const [file, newFile] of moves)if (!codeFiles.has(file) && newFile !== file) new File(file).moveTo(newFile, stopAt);
2089
2044
  const updated = [];
2090
2045
  for (const [file, content] of codeFiles){
2091
2046
  const newFile = moves.get(file);
2092
2047
  const next = rewrite(content, file, newFile ?? file);
2093
2048
  if (newFile && newFile !== file) {
2094
2049
  new File(newFile).data = next;
2095
- new File(file).delete(reactFolder);
2050
+ new File(file).delete(stopAt);
2096
2051
  } else if (next !== content) {
2097
2052
  new File(file).update(next);
2098
2053
  if (!newFile) updated.push(file);
@@ -2105,6 +2060,508 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
2105
2060
  updated
2106
2061
  };
2107
2062
  };
2063
+ const serviceLayout = (layer)=>({
2064
+ title: `${layer[0].toUpperCase()}${layer.slice(1)} services`,
2065
+ core: (ClassName)=>`${ClassName}${layer[0].toUpperCase()}${layer.slice(1)}Service`,
2066
+ files: ({ name })=>[
2067
+ `${layer}/services/${name}-${layer}-service.ts`,
2068
+ `${layer}/services/${name}-${layer}-service.spec.ts`,
2069
+ `wiring/${layer}-services/wire-${name}-${layer}-service.ts`
2070
+ ],
2071
+ wired: true,
2072
+ sharedKernel: true
2073
+ });
2074
+ const handlerLayout = (kind)=>{
2075
+ const folder = 'command' === kind ? 'commands' : 'queries';
2076
+ const Suffix = 'command' === kind ? 'Command' : 'Query';
2077
+ return {
2078
+ title: 'command' === kind ? 'Commands' : 'Queries',
2079
+ core: (ClassName)=>`${ClassName}${Suffix}`,
2080
+ files: ({ name }, labels)=>[
2081
+ `application/${folder}/${name}-${kind}.ts`,
2082
+ `application/${folder}/${name}-${kind}.spec.ts`,
2083
+ ...labels.map((label)=>`infrastructure/${folder}/${label}/${label}-${name}-${kind}.ts`),
2084
+ `wiring/${folder}/wire-${name}-${kind}.ts`
2085
+ ],
2086
+ implementations: `infrastructure/${folder}`,
2087
+ wired: true,
2088
+ sharedKernel: false
2089
+ };
2090
+ };
2091
+ const domainModelLayout = (kind)=>{
2092
+ const folder = 'entity' === kind ? 'entities' : 'value-objects';
2093
+ return {
2094
+ title: 'entity' === kind ? 'Entities' : 'Value objects',
2095
+ core: (ClassName)=>ClassName,
2096
+ files: ({ name, aggregate })=>{
2097
+ const base = aggregate ? `domain/aggregates/${aggregate}/${folder}` : `domain/${folder}`;
2098
+ return [
2099
+ `${base}/${name}.${kind}.ts`,
2100
+ `${base}/${name}.${kind}.spec.ts`
2101
+ ];
2102
+ },
2103
+ wired: false,
2104
+ sharedKernel: true
2105
+ };
2106
+ };
2107
+ const aggregateOwnFiles = (name)=>[
2108
+ `${name}.aggregate-root.ts`,
2109
+ `${name}.aggregate-root.spec.ts`,
2110
+ `${name}-repository.ts`,
2111
+ `${name}-repository.spec.ts`,
2112
+ 'index.ts'
2113
+ ];
2114
+ const kindLayouts = {
2115
+ aggregate: {
2116
+ title: 'Aggregates',
2117
+ core: (ClassName)=>`${ClassName}Repository`,
2118
+ files: ({ name }, labels)=>[
2119
+ ...aggregateOwnFiles(name).map((file)=>`domain/aggregates/${name}/${file}`),
2120
+ ...labels.map((label)=>`infrastructure/repositories/${label}/${label}-${name}-repository.ts`),
2121
+ `wiring/repositories/wire-${name}-repository.ts`
2122
+ ],
2123
+ implementations: 'infrastructure/repositories',
2124
+ wired: true,
2125
+ sharedKernel: false
2126
+ },
2127
+ entity: domainModelLayout('entity'),
2128
+ 'value-object': domainModelLayout('value-object'),
2129
+ 'domain-service': serviceLayout('domain'),
2130
+ 'application-service': serviceLayout('application'),
2131
+ 'infrastructure-service': serviceLayout('infrastructure'),
2132
+ 'presentation-service': serviceLayout('presentation'),
2133
+ 'use-case': {
2134
+ title: 'Use cases',
2135
+ core: (ClassName)=>`${ClassName}UseCase`,
2136
+ files: ({ name })=>[
2137
+ `application/use-cases/${name}-use-case.ts`,
2138
+ `application/use-cases/${name}-use-case.spec.ts`,
2139
+ `wiring/use-cases/wire-${name}-use-case.ts`
2140
+ ],
2141
+ wired: true,
2142
+ sharedKernel: false
2143
+ },
2144
+ command: handlerLayout('command'),
2145
+ query: handlerLayout('query'),
2146
+ port: {
2147
+ title: 'Ports',
2148
+ core: (ClassName)=>ClassName,
2149
+ files: ({ name }, labels)=>[
2150
+ `application/ports/${name}.ts`,
2151
+ `application/ports/${name}.spec.ts`,
2152
+ ...labels.map((label)=>`infrastructure/application-adapters/${label}/${label}-${name}.ts`),
2153
+ `wiring/application-ports/wire-${name}.ts`
2154
+ ],
2155
+ implementations: 'infrastructure/application-adapters',
2156
+ wired: true,
2157
+ sharedKernel: true
2158
+ }
2159
+ };
2160
+ const subfolders = (folder)=>node_fs.existsSync(folder) ? node_fs.readdirSync(folder, {
2161
+ withFileTypes: true
2162
+ }).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name).sort() : [];
2163
+ const namesBySuffix = (folder, suffix)=>node_fs.existsSync(folder) ? node_fs.readdirSync(folder).filter((file)=>file.endsWith(suffix) && !file.endsWith('.spec.ts')).map((file)=>file.slice(0, -suffix.length)).sort() : [];
2164
+ const labelsOf = (ownerPath, kind, name)=>{
2165
+ const { implementations } = kindLayouts[kind];
2166
+ if (!implementations) return [];
2167
+ return subfolders(node_path.join(ownerPath, implementations)).filter((label)=>kindLayouts[kind].files({
2168
+ ownerPath,
2169
+ name
2170
+ }, [
2171
+ label
2172
+ ]).some((file)=>file.startsWith(`${implementations}/`) && node_fs.existsSync(node_path.join(ownerPath, file))));
2173
+ };
2174
+ const aggregatesOf = (ownerPath)=>subfolders(node_path.join(ownerPath, 'domain/aggregates')).filter((name)=>node_fs.existsSync(node_path.join(ownerPath, 'domain/aggregates', name, `${name}.aggregate-root.ts`)));
2175
+ const findBackendUnits = (ownerPath)=>{
2176
+ const unit = (kind, name, aggregate)=>({
2177
+ kind,
2178
+ name,
2179
+ ownerPath,
2180
+ aggregate,
2181
+ labels: labelsOf(ownerPath, kind, name)
2182
+ });
2183
+ const aggregates = aggregatesOf(ownerPath);
2184
+ const inAggregates = (kind)=>aggregates.flatMap((aggregate)=>namesBySuffix(node_path.join(ownerPath, 'domain/aggregates', aggregate, 'entity' === kind ? 'entities' : 'value-objects'), `.${kind}.ts`).map((name)=>unit(kind, name, aggregate)));
2185
+ const at = (folder, suffix, kind)=>namesBySuffix(node_path.join(ownerPath, folder), suffix).map((name)=>unit(kind, name));
2186
+ return [
2187
+ ...aggregates.map((name)=>unit('aggregate', name)),
2188
+ ...inAggregates('entity'),
2189
+ ...at('domain/entities', '.entity.ts', 'entity'),
2190
+ ...inAggregates('value-object'),
2191
+ ...at('domain/value-objects', '.value-object.ts', 'value-object'),
2192
+ ...at('domain/services', '-domain-service.ts', 'domain-service'),
2193
+ ...at('application/ports', '.ts', 'port'),
2194
+ ...at('application/queries', '-query.ts', 'query'),
2195
+ ...at('application/commands', '-command.ts', 'command'),
2196
+ ...at('application/use-cases', '-use-case.ts', 'use-case'),
2197
+ ...at('application/services', '-application-service.ts', 'application-service'),
2198
+ ...at('infrastructure/services', '-infrastructure-service.ts', 'infrastructure-service'),
2199
+ ...at('presentation/services', '-presentation-service.ts', 'presentation-service')
2200
+ ];
2201
+ };
2202
+ const kebabName = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
2203
+ const lowerFirst = (value)=>value[0].toLowerCase() + value.slice(1);
2204
+ const unitMoves = (unit, target)=>{
2205
+ const layout = kindLayouts[unit.kind];
2206
+ const from = layout.files(unit, unit.labels);
2207
+ const to = layout.files(target, unit.labels);
2208
+ const moves = new Map();
2209
+ from.forEach((file, index)=>{
2210
+ const oldPath = node_path.join(unit.ownerPath, file);
2211
+ if (node_fs.existsSync(oldPath)) moves.set(oldPath, node_path.join(target.ownerPath, to[index]));
2212
+ });
2213
+ if ('aggregate' === unit.kind) {
2214
+ const oldFolder = node_path.join(unit.ownerPath, 'domain/aggregates', unit.name);
2215
+ const newFolder = node_path.join(target.ownerPath, 'domain/aggregates', target.name);
2216
+ const own = new Set(aggregateOwnFiles(unit.name).map((file)=>node_path.join(oldFolder, file)));
2217
+ for (const file of walk(oldFolder))if (!own.has(file)) moves.set(file, node_path.join(newFolder, node_path.relative(oldFolder, file)));
2218
+ }
2219
+ return moves;
2220
+ };
2221
+ const validateBackendMove = (unit, target, sharedKernelPath)=>{
2222
+ if (!kebabName.test(target.name)) return 'Use kebab-case: lowercase words split by "-", e.g. place-order';
2223
+ if (target.ownerPath === sharedKernelPath && !kindLayouts[unit.kind].sharedKernel) return `${kindLayouts[unit.kind].title} are not part of the Shared Kernel`;
2224
+ 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';
2225
+ for (const [from, to] of unitMoves(unit, target))if (to !== from && node_fs.existsSync(to)) return `${node_path.relative(target.ownerPath, to)} already exists`;
2226
+ return true;
2227
+ };
2228
+ const ownerOf = (rootFolderPath, file)=>{
2229
+ const [area, context] = node_path.relative(rootFolderPath, file).split(node_path.sep);
2230
+ if ('bounded-contexts' === area && context) return {
2231
+ context,
2232
+ path: node_path.join(rootFolderPath, area, context)
2233
+ };
2234
+ if ('shared-kernel' === area) return {
2235
+ context: void 0,
2236
+ path: node_path.join(rootFolderPath, area)
2237
+ };
2238
+ };
2239
+ const inMemoryDbFile = (rootFolderPath)=>node_path.join(rootFolderPath, 'shared-kernel/infrastructure/services/in-memory-db-infrastructure-service.ts');
2240
+ const isolationAllows = (rootFolderPath, from, to)=>{
2241
+ const fromOwner = ownerOf(rootFolderPath, from);
2242
+ const toOwner = ownerOf(rootFolderPath, to);
2243
+ if (!fromOwner || !toOwner?.context) return true;
2244
+ if (fromOwner.context) return fromOwner.context === toOwner.context;
2245
+ const inside = (folder)=>to === node_path.join(toOwner.path, folder) || to.startsWith(node_path.join(toOwner.path, folder) + node_path.sep);
2246
+ return inside('domain/errors') || from.replace(codeExtension, '') === inMemoryDbFile(rootFolderPath).replace(codeExtension, '') && inside('domain');
2247
+ };
2248
+ const moveBackendUnit = (projectRoot, rootFolderPath, unit, target)=>{
2249
+ const layout = kindLayouts[unit.kind];
2250
+ const moves = unitMoves(unit, target);
2251
+ const withoutExtension = new Map([
2252
+ ...moves
2253
+ ].map(([from, to])=>[
2254
+ from.replace(codeExtension, ''),
2255
+ to.replace(codeExtension, '')
2256
+ ]));
2257
+ const folders = 'aggregate' === unit.kind ? [
2258
+ [
2259
+ node_path.join(unit.ownerPath, 'domain/aggregates', unit.name),
2260
+ node_path.join(target.ownerPath, 'domain/aggregates', target.name)
2261
+ ]
2262
+ ] : [];
2263
+ const movedPath = (candidate)=>{
2264
+ const extension = candidate.match(codeExtension)?.[0];
2265
+ if (extension) return moves.get(candidate);
2266
+ return withoutExtension.get(candidate) ?? folders.find(([from])=>from === candidate)?.[1];
2267
+ };
2268
+ const { codeFiles, importsOf, resolve } = projectImports(projectRoot);
2269
+ const oldNaming = new UnknownFormatNaming(unit.name);
2270
+ const newNaming = new UnknownFormatNaming(target.name);
2271
+ const leavesAggregate = !!unit.aggregate && (unit.aggregate !== target.aggregate || unit.ownerPath !== target.ownerPath);
2272
+ const oldAggregateFolder = unit.aggregate && node_path.join(unit.ownerPath, 'domain/aggregates', unit.aggregate);
2273
+ const isOldBarrel = (resolved)=>!!oldAggregateFolder && (resolved === oldAggregateFolder || resolved === node_path.join(oldAggregateFolder, 'index'));
2274
+ const mainFile = [
2275
+ ...moves.keys()
2276
+ ][0];
2277
+ const newMainFile = moves.get(mainFile);
2278
+ const namedImports = /import\s+(type\s+)?\{([^}]*)\}\s*from\s*(['"])([^'"\n]+)\3;?/g;
2279
+ const barrelImporters = leavesAggregate ? [
2280
+ ...codeFiles
2281
+ ].filter(([file, content])=>!moves.has(file) && [
2282
+ ...content.matchAll(namedImports)
2283
+ ].some(([, , names, , specifier])=>isOldBarrel(resolve(specifier, file)?.resolved) && new RegExp(`(?<![\\w$])${oldNaming.ClassName}(?![\\w$])`).test(names))) : [];
2284
+ const violations = [];
2285
+ const relative = (file)=>toPosix(node_path.relative(projectRoot, file));
2286
+ for (const file of codeFiles.keys()){
2287
+ const from = moves.get(file) ?? file;
2288
+ for (const imported of importsOf(file)){
2289
+ const to = movedPath(imported);
2290
+ if (moves.has(file) || to) {
2291
+ if (!isolationAllows(rootFolderPath, from, to ?? imported)) violations.push([
2292
+ relative(from),
2293
+ relative(to ?? imported)
2294
+ ]);
2295
+ }
2296
+ }
2297
+ }
2298
+ for (const [file] of barrelImporters)if (!isolationAllows(rootFolderPath, file, newMainFile)) violations.push([
2299
+ relative(file),
2300
+ relative(newMainFile)
2301
+ ]);
2302
+ if (violations.length) return {
2303
+ violations
2304
+ };
2305
+ const word = (form)=>`(?<![\\w$])${escapeRegExp(form)}(?![\\w$])`;
2306
+ const oldCore = layout.core(oldNaming.ClassName);
2307
+ const newCore = layout.core(newNaming.ClassName);
2308
+ const prefixes = [
2309
+ ...unit.labels.map((label)=>new UnknownFormatNaming(label).ClassName),
2310
+ ...layout.wired ? [
2311
+ 'wire'
2312
+ ] : []
2313
+ ];
2314
+ const renames = [
2315
+ {
2316
+ pattern: new RegExp(`(?<![\\w$])(${prefixes.map(escapeRegExp).join('|')})?${escapeRegExp(oldCore)}(?![\\w$])`, 'g'),
2317
+ to: `$1${newCore}`
2318
+ },
2319
+ {
2320
+ pattern: new RegExp(word(lowerFirst(oldCore)), 'g'),
2321
+ to: lowerFirst(newCore)
2322
+ },
2323
+ {
2324
+ pattern: new RegExp(`(describe\\(\\s*['"\`])${escapeRegExp(oldNaming.withSpaces)}(?=[ '"\`])`, 'g'),
2325
+ to: `$1${newNaming.withSpaces}`,
2326
+ movedOnly: true
2327
+ }
2328
+ ];
2329
+ if ('aggregate' === unit.kind) renames.push({
2330
+ pattern: new RegExp(word(oldNaming.ClassName), 'g'),
2331
+ to: newNaming.ClassName
2332
+ }, {
2333
+ pattern: new RegExp(word(oldNaming.variableName), 'g'),
2334
+ to: newNaming.variableName,
2335
+ movedOnly: true
2336
+ });
2337
+ if ('entity' === unit.kind || 'value-object' === unit.kind) renames.push({
2338
+ pattern: new RegExp(word(oldNaming.variableName), 'g'),
2339
+ to: newNaming.variableName,
2340
+ movedOnly: true
2341
+ });
2342
+ const oldSection = new UnknownFormatNaming(plural(unit.name));
2343
+ const newSection = new UnknownFormatNaming(plural(target.name));
2344
+ const renamesSection = 'aggregate' === unit.kind && unit.name !== target.name;
2345
+ 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;
2346
+ const plan = stageModuleMove({
2347
+ projectRoot,
2348
+ stopAt: rootFolderPath,
2349
+ moves,
2350
+ movedPath,
2351
+ rename: (content, { moved })=>renames.reduce((result, { pattern, to, movedOnly })=>movedOnly && !moved ? result : result.replace(pattern, to), content),
2352
+ everyFile
2353
+ });
2354
+ if (leavesAggregate && oldAggregateFolder) {
2355
+ const indexFile = new File(node_path.join(oldAggregateFolder, 'index.ts'));
2356
+ const exportLine = /^export\s+\*\s+from\s+(['"])([^'"\n]+)\1;?\s*$/;
2357
+ indexFile.update(indexFile.data.split('\n').filter((line)=>{
2358
+ const specifier = line.match(exportLine)?.[2];
2359
+ return !specifier || node_path.resolve(node_path.dirname(indexFile.path), specifier) !== newMainFile.replace(codeExtension, '');
2360
+ }).join('\n'));
2361
+ if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
2362
+ for (const [file] of barrelImporters){
2363
+ const importer = new File(file);
2364
+ let content = importer.data;
2365
+ for (const match of content.matchAll(namedImports)){
2366
+ const [statement, typeOnly = '', names, quote, specifier] = match;
2367
+ if (!isOldBarrel(resolve(specifier, file)?.resolved)) continue;
2368
+ const items = names.split(',').map((item)=>item.trim()).filter((item)=>!!item);
2369
+ const own = new RegExp(`^(?:type\\s+)?${newNaming.ClassName}(?:\\s+as\\s+[\\w$]+)?$`);
2370
+ const moved = items.filter((item)=>own.test(item));
2371
+ if (!moved.length) continue;
2372
+ const rest = items.filter((item)=>!own.test(item));
2373
+ const direct = `import ${typeOnly}{ ${moved.join(', ')} } from ${quote}${projectRelative(file, newMainFile)}${quote}`;
2374
+ content = content.replace(statement, rest.length ? `import ${typeOnly}{ ${rest.join(', ')} } from ${quote}${specifier}${quote}\n${direct}` : direct);
2375
+ }
2376
+ importer.update(content);
2377
+ }
2378
+ }
2379
+ if (target.aggregate && (target.aggregate !== unit.aggregate || target.ownerPath !== unit.ownerPath)) {
2380
+ const kindFolder = 'entity' === unit.kind ? 'entities' : 'value-objects';
2381
+ const indexFile = new File(node_path.join(target.ownerPath, 'domain/aggregates', target.aggregate, 'index.ts'));
2382
+ indexFile.addLineIfMissing(`export * from './${kindFolder}/${target.name}.${unit.kind}'`);
2383
+ if (!plan.updated.includes(indexFile.path)) plan.updated.push(indexFile.path);
2384
+ }
2385
+ return plan;
2386
+ };
2387
+ const projectRelative = (fromFile, toFile)=>{
2388
+ const relative = toPosix(node_path.relative(node_path.dirname(fromFile), toFile.replace(codeExtension, '')));
2389
+ return relative.startsWith('.') ? relative : `./${relative}`;
2390
+ };
2391
+ const noAggregate = 'No aggregate';
2392
+ const moveBackendUnitUseCase = async (ownerFolder)=>{
2393
+ const root = new ProjectRoot().path;
2394
+ const rootFolderPath = node_path.join(root, ConfigFile.Instance.data.rootFolder);
2395
+ const sharedKernelPath = node_path.join(rootFolderPath, 'shared-kernel');
2396
+ const units = findBackendUnits(ownerFolder.path);
2397
+ if (!units.length) return void console.log('No modules generated by df-scaffold were found here.');
2398
+ const unit = await prompts_select({
2399
+ message: 'Module:',
2400
+ choices: Object.keys(kindLayouts).flatMap((kind)=>{
2401
+ const group = units.filter((x)=>x.kind === kind);
2402
+ return group.length ? [
2403
+ new Separator(`── ${kindLayouts[group[0].kind].title}`),
2404
+ ...group.map((value)=>({
2405
+ name: value.aggregate ? `${value.name} (${value.aggregate})` : value.name,
2406
+ value
2407
+ }))
2408
+ ] : [];
2409
+ }),
2410
+ pageSize: 20
2411
+ });
2412
+ const placeName = (ownerPath)=>ownerPath === sharedKernelPath ? 'Shared Kernel' : `Bounded Context: ${node_path.basename(ownerPath)}`;
2413
+ const contexts = new Folder(rootFolderPath).subitem([
2414
+ 'bounded-contexts'
2415
+ ]).content.subfolderNames.map((name)=>node_path.join(rootFolderPath, 'bounded-contexts', name));
2416
+ const places = [
2417
+ unit.ownerPath,
2418
+ ...contexts,
2419
+ ...kindLayouts[unit.kind].sharedKernel ? [
2420
+ sharedKernelPath
2421
+ ] : []
2422
+ ].filter((place, index, all)=>all.indexOf(place) === index);
2423
+ const ownerPath = await prompts_select({
2424
+ message: 'Move to:',
2425
+ choices: places.map((value)=>({
2426
+ name: value === unit.ownerPath ? `${placeName(value)} (stays)` : placeName(value),
2427
+ value
2428
+ }))
2429
+ });
2430
+ let aggregate;
2431
+ const aggregates = ownerPath === sharedKernelPath ? [] : aggregatesOf(ownerPath);
2432
+ if (('entity' === unit.kind || 'value-object' === unit.kind) && aggregates.length) {
2433
+ const picked = await prompts_select({
2434
+ message: 'Aggregate:',
2435
+ choices: [
2436
+ noAggregate,
2437
+ ...aggregates
2438
+ ],
2439
+ default: ownerPath === unit.ownerPath && unit.aggregate ? unit.aggregate : noAggregate
2440
+ });
2441
+ aggregate = picked === noAggregate ? void 0 : picked;
2442
+ }
2443
+ const target = (name)=>({
2444
+ ownerPath,
2445
+ aggregate,
2446
+ name: name.trim()
2447
+ });
2448
+ const name = await input({
2449
+ message: 'New name:',
2450
+ default: unit.name,
2451
+ validate: (value)=>validateBackendMove(unit, target(value), sharedKernelPath)
2452
+ });
2453
+ const result = moveBackendUnit(root, rootFolderPath, unit, target(name));
2454
+ if (result.violations) return void console.log([
2455
+ "Nothing was moved: these imports would cross a bounded context boundary.",
2456
+ ...result.violations.map(([from, to])=>` ${from} → ${to}`),
2457
+ 'Give the other context its own query or command, or move what it depends on first.'
2458
+ ].join('\n'));
2459
+ const relative = (file)=>node_path.relative(root, file);
2460
+ console.log([
2461
+ 'Files to move:',
2462
+ ...result.moves.map(([from, to])=>` ${relative(from)} → ${relative(to)}`),
2463
+ ...result.updated.length ? [
2464
+ 'Files with updated imports and names:',
2465
+ ...result.updated.map((file)=>` ${relative(file)}`)
2466
+ ] : []
2467
+ ].join('\n'));
2468
+ if (!await prompts_confirm({
2469
+ message: 'Apply?',
2470
+ default: true
2471
+ })) {
2472
+ discardPendingChanges();
2473
+ console.log('Cancelled: nothing was written.');
2474
+ }
2475
+ };
2476
+ const nestedName = (folders, fileBase)=>{
2477
+ const prefix = `${folders.join('-')}-`;
2478
+ const last = folders.length && fileBase.startsWith(prefix) ? fileBase.slice(prefix.length) : fileBase;
2479
+ return [
2480
+ ...folders,
2481
+ last
2482
+ ].join('/');
2483
+ };
2484
+ const declaredClassName = (filePath, suffix, name)=>{
2485
+ const content = node_fs.readFileSync(filePath, 'utf8');
2486
+ const declared = content.match(new RegExp(`export\\s+(?:const|function)\\s+(\\w+)${suffix}\\b`))?.[1];
2487
+ return declared ?? new NestedName(name).ClassName;
2488
+ };
2489
+ const findReactModules = (reactFolder, kind)=>{
2490
+ const modules = 'page' === kind ? walk(node_path.join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
2491
+ const folders = node_path.relative(node_path.join(reactFolder, 'pages'), node_path.dirname(file)).split(node_path.sep).filter((segment)=>!!segment);
2492
+ const fileBase = node_path.basename(file, '-page.tsx');
2493
+ const name = nestedName(folders, fileBase);
2494
+ return {
2495
+ kind,
2496
+ name,
2497
+ path: file,
2498
+ fileBase,
2499
+ ClassName: declaredClassName(file, 'Page', name)
2500
+ };
2501
+ }) : walk(node_path.join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
2502
+ const folder = node_path.dirname(file);
2503
+ const name = toPosix(node_path.relative(node_path.join(reactFolder, 'widgets'), folder));
2504
+ return {
2505
+ kind,
2506
+ name,
2507
+ path: folder,
2508
+ fileBase: node_path.basename(file, '-widget.tsx'),
2509
+ ClassName: declaredClassName(file, 'Widget', name)
2510
+ };
2511
+ });
2512
+ return modules.sort((a, b)=>a.name.localeCompare(b.name));
2513
+ };
2514
+ const targetPath = (reactFolder, module, rawName)=>{
2515
+ const { folders, folderName, fileName } = new NestedName(rawName);
2516
+ return 'page' === module.kind ? node_path.join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : node_path.join(reactFolder, 'widgets', ...folders, folderName);
2517
+ };
2518
+ const validateMove = (reactFolder, module, rawName)=>{
2519
+ const nameError = NestedName.validate(rawName);
2520
+ if (true !== nameError) return nameError;
2521
+ const target = targetPath(reactFolder, module, rawName);
2522
+ if (target !== module.path && node_fs.existsSync(target)) return `${node_path.relative(reactFolder, target)} already exists`;
2523
+ if (target.startsWith(`${module.path}${node_path.sep}`)) return 'A widget cannot be moved into itself';
2524
+ return true;
2525
+ };
2526
+ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
2527
+ const newName = new NestedName(rawName);
2528
+ const target = targetPath(reactFolder, module, rawName);
2529
+ const newClassName = newName.ClassName;
2530
+ const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
2531
+ const oldFolder = 'page' === module.kind ? node_path.dirname(module.path) : module.path;
2532
+ const newFolder = 'page' === module.kind ? node_path.dirname(target) : target;
2533
+ const ownsPath = (candidate)=>'page' === module.kind ? node_path.dirname(candidate) === oldFolder && new RegExp(`^${escapeRegExp(module.fileBase)}-page(?:\\.|$)`).test(node_path.basename(candidate)) : candidate === oldFolder || candidate.startsWith(`${oldFolder}${node_path.sep}`);
2534
+ const movedPath = (candidate)=>{
2535
+ if (!ownsPath(candidate)) return;
2536
+ const segments = node_path.relative(oldFolder, candidate).split(node_path.sep);
2537
+ const last = segments.length - 1;
2538
+ segments[last] = renameFile(segments[last]);
2539
+ return node_path.join(newFolder, ...segments);
2540
+ };
2541
+ const moduleFiles = 'page' === module.kind ? node_fs.readdirSync(oldFolder).map((name)=>node_path.join(oldFolder, name)).filter((file)=>node_fs.statSync(file).isFile() && ownsPath(file)) : walk(oldFolder);
2542
+ const moves = new Map(moduleFiles.map((file)=>[
2543
+ file,
2544
+ movedPath(file) ?? file
2545
+ ]));
2546
+ const suffixes = 'page' === module.kind ? 'Page' : 'Widget|UIModel';
2547
+ const classPattern = new RegExp(`(?<![\\w$])(use)?${escapeRegExp(module.ClassName)}(?=${suffixes})`, 'g');
2548
+ const oldTitle = `Widgets/${module.name.split('/').map((segment)=>new NestedName(segment).ClassName).join('/')}`;
2549
+ const titlePattern = new RegExp(`(['"\`])${escapeRegExp(oldTitle)}\\1`, 'g');
2550
+ const newTitle = [
2551
+ 'Widgets',
2552
+ ...newName.classNameSegments
2553
+ ].join('/');
2554
+ return stageModuleMove({
2555
+ projectRoot,
2556
+ stopAt: reactFolder,
2557
+ moves,
2558
+ movedPath,
2559
+ rename: (content, { moved })=>{
2560
+ const renamed = content.replace(classPattern, (_, use = '')=>`${use}${newClassName}`);
2561
+ return moved && 'widget' === module.kind ? renamed.replace(titlePattern, (_, quote)=>`${quote}${newTitle}${quote}`) : renamed;
2562
+ }
2563
+ });
2564
+ };
2108
2565
  const moveReactModuleUseCase = async (presentationReactFolder, kind)=>{
2109
2566
  const reactFolder = presentationReactFolder.path;
2110
2567
  const modules = findReactModules(reactFolder, kind);
@@ -2568,7 +3025,7 @@ export const wire${naming.ClassName}Command = envBranchedWire({
2568
3025
  await wireNewModuleDependencies(boundedContextFolder, wireFile);
2569
3026
  }
2570
3027
  };
2571
- const noAggregate = 'No aggregate';
3028
+ const scaffold_new_domain_object_noAggregate = 'No aggregate';
2572
3029
  const scaffoldNewDomainObject = async (boundedContextFolder, kind)=>{
2573
3030
  const name = await input({
2574
3031
  message: 'Name: '
@@ -2583,11 +3040,11 @@ const scaffoldNewDomainObject = async (boundedContextFolder, kind)=>{
2583
3040
  message: 'Aggregate:',
2584
3041
  choices: [
2585
3042
  ...aggregateNames,
2586
- noAggregate
3043
+ scaffold_new_domain_object_noAggregate
2587
3044
  ]
2588
- }) : noAggregate;
3045
+ }) : scaffold_new_domain_object_noAggregate;
2589
3046
  const kindFolderName = 'entity' === kind ? 'entities' : 'value-objects';
2590
- const folder = aggregate === noAggregate ? boundedContextFolder.subitem([
3047
+ const folder = aggregate === scaffold_new_domain_object_noAggregate ? boundedContextFolder.subitem([
2591
3048
  'domain',
2592
3049
  kindFolderName
2593
3050
  ]) : aggregatesFolder.subitem([
@@ -2602,7 +3059,7 @@ import { domainType } from '@domain-first/types'
2602
3059
  export class ${naming.ClassName} extends domainType() {
2603
3060
 
2604
3061
  }`.trim() : `export class ${naming.ClassName} {}`);
2605
- if (aggregate !== noAggregate) aggregatesFolder.subitem([
3062
+ if (aggregate !== scaffold_new_domain_object_noAggregate) aggregatesFolder.subitem([
2606
3063
  aggregate
2607
3064
  ]).file('index.ts').addLineIfMissing(`export * from './${kindFolderName}/${fileName}'`);
2608
3065
  const { testingLibrary } = ConfigFile.Instance.data;
@@ -3287,4 +3744,4 @@ export const use${ClassName}UIModel = (widgetProps: Omit<${ClassName}WidgetProps
3287
3744
  break;
3288
3745
  }
3289
3746
  };
3290
- export { addIntegration, initializeUseCase, moveReactModuleUseCase, printNextSteps, savePendingChanges, scaffoldNewAggregateUseCase, scaffoldNewApplicationPort, scaffoldNewApplicationService, scaffoldNewBoundedContextUseCase, scaffoldNewCommand, scaffoldNewDomainObject, scaffoldNewDomainService, scaffoldNewErrorUseCase, scaffoldNewHandlersRestEndpoint, scaffoldNewInfrastructureService, scaffoldNewPresentationService, scaffoldNewQuery, scaffoldNewUseCase, scaffoldReactPage, scaffoldReactSharedHook, scaffoldReactUIKitComponent, scaffoldReactWidget, wireDependency };
3747
+ export { addIntegration, initializeUseCase, moveBackendUnitUseCase, moveReactModuleUseCase, printNextSteps, savePendingChanges, scaffoldNewAggregateUseCase, scaffoldNewApplicationPort, scaffoldNewApplicationService, scaffoldNewBoundedContextUseCase, scaffoldNewCommand, scaffoldNewDomainObject, scaffoldNewDomainService, scaffoldNewErrorUseCase, scaffoldNewHandlersRestEndpoint, scaffoldNewInfrastructureService, scaffoldNewPresentationService, scaffoldNewQuery, scaffoldNewUseCase, scaffoldReactPage, scaffoldReactSharedHook, scaffoldReactUIKitComponent, scaffoldReactWidget, wireDependency };