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