@domain-first/project-structure 4.0.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,197 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, input, select as prompts_select } from "@inquirer/prompts";
3
+ import { styleText } from "node:util";
3
4
  import node_path from "node:path";
4
- import zod from "zod";
5
5
  import node_fs from "node:fs";
6
- import { styleText } from "node:util";
7
- import { createRequire } from "node:module";
8
- const pendingFiles = new Map();
9
- const pendingFolders = new Set();
10
- const pendingMoves = new Map();
11
- const pendingDeletions = new Map();
12
- const filesToOverwrite = ()=>[
13
- ...pendingFiles
14
- ].filter(([filePath, { replacesFile }])=>replacesFile && node_fs.existsSync(filePath)).map(([filePath])=>filePath);
15
- const discardPendingChanges = ()=>{
16
- pendingFolders.clear();
17
- pendingFiles.clear();
18
- pendingMoves.clear();
19
- pendingDeletions.clear();
20
- };
21
- const removeEmptyFolders = (folderPath, stopAt)=>{
22
- let current = folderPath;
23
- while(current.startsWith(`${stopAt}${node_path.sep}`) && node_fs.existsSync(current) && !node_fs.readdirSync(current).length){
24
- node_fs.rmdirSync(current);
25
- current = node_path.dirname(current);
26
- }
27
- };
28
- const writePendingChanges = ()=>{
29
- for (const folderPath of pendingFolders)node_fs.mkdirSync(folderPath, {
30
- recursive: true
31
- });
32
- for (const [filePath, { content }] of pendingFiles){
33
- node_fs.mkdirSync(node_path.dirname(filePath), {
34
- recursive: true
35
- });
36
- node_fs.writeFileSync(filePath, content, 'utf8');
37
- }
38
- for (const [targetPath, { sourcePath }] of pendingMoves){
39
- node_fs.mkdirSync(node_path.dirname(targetPath), {
40
- recursive: true
41
- });
42
- node_fs.renameSync(sourcePath, targetPath);
43
- }
44
- for (const filePath of pendingDeletions.keys())node_fs.rmSync(filePath, {
45
- force: true
46
- });
47
- for (const [filePath, stopAt] of pendingDeletions)removeEmptyFolders(node_path.dirname(filePath), stopAt);
48
- for (const { sourcePath, stopAt } of pendingMoves.values())removeEmptyFolders(node_path.dirname(sourcePath), stopAt);
49
- discardPendingChanges();
50
- };
51
- class FileSystemItem {
52
- path;
53
- constructor(path){
54
- this.path = path;
55
- }
56
- subitem = (relativePath)=>new this.constructor(node_path.resolve(this.path, ...relativePath));
57
- get exists() {
58
- return node_fs.existsSync(this.path);
59
- }
60
- }
61
- class Folder extends FileSystemItem {
62
- createIfNotExisted = ()=>{
63
- pendingFolders.add(this.path);
64
- };
65
- get content() {
66
- if (!this.exists) return {
67
- subfolderNames: [],
68
- fileNames: []
69
- };
70
- const content = node_fs.readdirSync(this.path, {
71
- withFileTypes: true
72
- });
73
- return {
74
- subfolderNames: content.filter((x)=>x.isDirectory()).map((x)=>x.name),
75
- fileNames: content.filter((x)=>!x.isDirectory()).map((x)=>node_path.parse(x.name).name)
76
- };
77
- }
78
- get name() {
79
- return node_path.basename(this.path);
80
- }
81
- createFile = (name, content)=>{
82
- this.createIfNotExisted();
83
- const file = new File(this.path).subitem([
84
- name
85
- ]);
86
- file.data = content;
87
- return file;
88
- };
89
- file = (name)=>{
90
- this.createIfNotExisted();
91
- const file = new File(this.path).subitem([
92
- name
93
- ]);
94
- return file;
95
- };
96
- }
97
- class File extends FileSystemItem {
98
- get exists() {
99
- return pendingFiles.has(this.path) || pendingMoves.has(this.path) || node_fs.existsSync(this.path) && !pendingDeletions.has(this.path);
100
- }
101
- delete = (stopAt)=>{
102
- pendingDeletions.set(this.path, stopAt);
103
- };
104
- moveTo = (targetPath, stopAt)=>{
105
- pendingMoves.set(targetPath, {
106
- sourcePath: this.path,
107
- stopAt
108
- });
109
- };
110
- get data() {
111
- const pendingFile = pendingFiles.get(this.path);
112
- if (pendingFile) return pendingFile.content;
113
- if (!this.exists) throw new Error('File does not exist');
114
- return node_fs.readFileSync(this.path, 'utf-8');
115
- }
116
- set data(content) {
117
- pendingFiles.set(this.path, {
118
- content,
119
- replacesFile: true
120
- });
121
- }
122
- update = (content)=>{
123
- pendingFiles.set(this.path, {
124
- content,
125
- replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
126
- });
127
- };
128
- addLine = (newLine, separator = '\n')=>{
129
- const content = this.exists ? this.data : '';
130
- pendingFiles.set(this.path, {
131
- content: [
132
- content.trim(),
133
- newLine.trim()
134
- ].filter((x)=>!!x).join(separator),
135
- replacesFile: pendingFiles.get(this.path)?.replacesFile ?? false
136
- });
137
- };
138
- addLineIfMissing = (newLine, separator = '\n')=>{
139
- const alreadyAdded = this.exists && this.data.split('\n').some((line)=>line.trim() === newLine.trim());
140
- if (!alreadyAdded) this.addLine(newLine, separator);
141
- };
142
- }
143
- class ProjectRoot {
144
- path;
145
- constructor(){
146
- let dir = process.cwd();
147
- while(dir !== node_path.parse(dir).root){
148
- if (node_fs.existsSync(node_path.join(dir, 'package.json'))) {
149
- this.path = dir;
150
- return;
151
- }
152
- dir = node_path.dirname(dir);
153
- }
154
- throw new Error('No package.json was found');
155
- }
156
- }
157
- const configFileName = 'domain-first.project-structure.config.json';
158
- const configSchema = zod.object({
159
- rootFolder: zod.string(),
160
- domainFirstPackages: zod.array(zod["enum"]([
161
- '@domain-first/types',
162
- '@domain-first/errors',
163
- '@domain-first/handlers',
164
- '@domain-first/wire',
165
- '@domain-first/handlers-rest'
166
- ])),
167
- defaultPersistenceLayerImplementation: zod.string(),
168
- withInMemoryDb: zod.boolean().optional(),
169
- useReact: zod.boolean(),
170
- storybookFramework: zod.string().optional(),
171
- testingLibrary: zod.string().optional()
172
- });
173
- class ConfigFile {
174
- data;
175
- constructor(){
176
- const filePath = ConfigFile.path;
177
- const file = new File(filePath);
178
- const configObject = JSON.parse(file.data);
179
- this.data = configSchema.parse(configObject);
180
- }
181
- static get Instance() {
182
- return new ConfigFile();
183
- }
184
- static get path() {
185
- const { path: root } = new ProjectRoot();
186
- return node_path.resolve(root, configFileName);
187
- }
188
- static get exists() {
189
- return new File(ConfigFile.path).exists;
190
- }
191
- static write = (config)=>{
192
- new File(ConfigFile.path).data = JSON.stringify(config, null, '\t');
193
- };
194
- }
6
+ import { addImport, availableDependencies, discardPendingChanges, findWiredModules, UnknownFormatNaming, Folder, writePendingChanges, stripJsonComments, readWiredModule, addClassMember, addWireDependencies, addConstructorParameters, filesToOverwrite, ConfigFile, relativeImport, wireDependencies, File, ProjectRoot, implementationType as wiring_implementationType, compilerOption, isSuggestedFor } from "./201.js";
195
7
  const printNextSteps = (nextSteps)=>{
196
8
  const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
197
9
  const commands = nextSteps.filter(isCommand);
@@ -247,67 +59,6 @@ const missingDomainFirstPackages = ()=>{
247
59
  `npm i ${missing.join(' ')}`
248
60
  ] : [];
249
61
  };
250
- const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
251
- const resolveExtends = (fromFile, target)=>{
252
- if (target.startsWith('.') || node_path.isAbsolute(target)) {
253
- const resolved = node_path.resolve(node_path.dirname(fromFile), target);
254
- return resolved.endsWith('.json') ? resolved : `${resolved}.json`;
255
- }
256
- const require = createRequire(fromFile);
257
- for (const candidate of [
258
- target,
259
- `${target}/tsconfig.json`
260
- ])try {
261
- return require.resolve(candidate);
262
- } catch {}
263
- };
264
- const compilerOption = (configFile, name, seen = new Set())=>{
265
- if (seen.has(configFile) || !node_fs.existsSync(configFile)) return null;
266
- seen.add(configFile);
267
- let config;
268
- try {
269
- config = JSON.parse(stripJsonComments(node_fs.readFileSync(configFile, 'utf8')));
270
- } catch {
271
- return null;
272
- }
273
- if (config.compilerOptions && name in config.compilerOptions) return config.compilerOptions[name];
274
- const parents = [
275
- config.extends ?? []
276
- ].flat().reverse();
277
- for (const parent of parents){
278
- const parentFile = resolveExtends(configFile, parent);
279
- const value = parentFile ? compilerOption(parentFile, name, seen) : null;
280
- if (void 0 !== value) return value;
281
- }
282
- };
283
- class UnknownFormatNaming {
284
- rawSource;
285
- camelCase;
286
- PascalCase;
287
- constructor(rawSource){
288
- this.rawSource = rawSource;
289
- const source = rawSource.trim();
290
- if (!source.includes('-')) {
291
- this.camelCase = source.substring(0, 1).toLowerCase() + source.substring(1);
292
- this.PascalCase = source.substring(0, 1).toUpperCase() + source.substring(1);
293
- }
294
- const words = source.split('-').filter((word)=>!!word);
295
- this.camelCase = words.map((word, index)=>0 === index ? word.toLowerCase() : word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
296
- this.PascalCase = words.map((word)=>word[0].toUpperCase() + word.slice(1).toLowerCase()).join('');
297
- }
298
- get fileName() {
299
- return this.rawSource;
300
- }
301
- get variableName() {
302
- return this.camelCase;
303
- }
304
- get ClassName() {
305
- return this.PascalCase;
306
- }
307
- get withSpaces() {
308
- return this.fileName.replaceAll('-', ' ');
309
- }
310
- }
311
62
  const splitSegments = (rawSource)=>rawSource.split(/[\\/]/).map((segment)=>segment.trim()).filter((segment)=>!!segment);
312
63
  class NestedName {
313
64
  folders;
@@ -1297,326 +1048,10 @@ const addIntegration = async ()=>{
1297
1048
  const nextSteps = await integration.run();
1298
1049
  if (await savePendingChanges()) printNextSteps(nextSteps);
1299
1050
  };
1300
- const wiring_layers = [
1301
- 'domain',
1302
- 'application',
1303
- 'infrastructure',
1304
- 'presentation'
1305
- ];
1306
- const visibleLayers = {
1307
- domain: [
1308
- 'domain'
1309
- ],
1310
- application: [
1311
- 'domain',
1312
- 'application'
1313
- ],
1314
- infrastructure: [
1315
- 'domain',
1316
- 'application',
1317
- 'infrastructure'
1318
- ],
1319
- presentation: [
1320
- 'application',
1321
- 'presentation'
1322
- ]
1323
- };
1324
- const branchedTypeFiles = {
1325
- repositories: (fileBase)=>[
1326
- 'domain',
1327
- 'aggregates',
1328
- fileBase.replace(/-repository$/, ''),
1329
- `${fileBase}.ts`
1330
- ],
1331
- commands: (fileBase)=>[
1332
- 'application',
1333
- 'commands',
1334
- 'execution',
1335
- `${fileBase}.ts`
1336
- ],
1337
- queries: (fileBase)=>[
1338
- 'application',
1339
- 'queries',
1340
- 'execution',
1341
- `${fileBase}.ts`
1342
- ],
1343
- 'application-ports': (fileBase)=>[
1344
- 'application',
1345
- 'ports',
1346
- `${fileBase}.ts`
1347
- ]
1348
- };
1349
- const layerOf = (file, contextPath)=>{
1350
- const [firstSegment] = node_path.relative(contextPath, file).split(node_path.sep);
1351
- return wiring_layers.find((layer)=>layer === firstSegment);
1352
- };
1353
- const namedImports = (source, fromFile)=>{
1354
- const result = new Map();
1355
- for (const [, names, importPath] of source.matchAll(/import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g))for (const name of names.split(',')){
1356
- const cleanName = name.replace(/^\s*type\s+/, '').trim();
1357
- if (cleanName) result.set(cleanName, `${node_path.resolve(node_path.dirname(fromFile), importPath)}.ts`);
1358
- }
1359
- return result;
1360
- };
1361
- const isEndpointWire = (wiringRelativePath)=>wiringRelativePath.startsWith([
1362
- 'presentation',
1363
- 'rest'
1364
- ].join(node_path.sep));
1365
- const wireClassDefinitions = (source)=>[
1366
- ...codeOnly(source).matchAll(/(?:export\s+)?const\s+(\w+)\s*=\s*(?:\w+\(\s*)*wireClass\(\s*(\w+)\s*,/g)
1367
- ].map(([, wireName, className])=>({
1368
- wireName,
1369
- className
1370
- }));
1371
- const wiredClassNames = (source, wireName, initializerStart, branched)=>{
1372
- const definitions = wireClassDefinitions(source);
1373
- if (!branched) return definitions.filter((x)=>x.wireName === wireName).map((x)=>x.className);
1374
- const openIndex = source.indexOf('(', initializerStart);
1375
- const branches = codeOnly(source).slice(openIndex, closingIndex(source, openIndex));
1376
- const referenced = new Set(branches.match(/\w+/g));
1377
- return definitions.filter((x)=>referenced.has(x.wireName)).map((x)=>x.className);
1378
- };
1379
- const readWiredModule = (wireFile, contextPath)=>{
1380
- const wiringRelativePath = node_path.relative(node_path.join(contextPath, 'wiring'), wireFile);
1381
- if (isEndpointWire(wiringRelativePath)) return;
1382
- const source = new File(wireFile).data;
1383
- const wireName = `wire${new UnknownFormatNaming(node_path.basename(wireFile, '.ts').replace(/^wire-/, '')).ClassName}`;
1384
- const exportMatch = new RegExp(`export\\s+const\\s+${wireName}\\s*=\\s*`).exec(source);
1385
- if (!exportMatch) return;
1386
- const branched = source.slice(exportMatch.index + exportMatch[0].length).startsWith('envBranchedWire(');
1387
- const imports = namedImports(source, wireFile);
1388
- const implementations = wiredClassNames(source, wireName, exportMatch.index + exportMatch[0].length, branched).flatMap((className)=>{
1389
- const file = imports.get(className);
1390
- return file ? [
1391
- {
1392
- className,
1393
- file
1394
- }
1395
- ] : [];
1396
- });
1397
- if (!implementations.length) return;
1398
- const typeName = wireName.slice(4);
1399
- const [wiringFolder] = wiringRelativePath.split(node_path.sep);
1400
- const typeFileSegments = branchedTypeFiles[wiringFolder]?.(node_path.basename(wireFile, '.ts').replace(/^wire-/, ''));
1401
- const typeFile = branched ? typeFileSegments && node_path.join(contextPath, ...typeFileSegments) : implementations[0].file;
1402
- const layer = typeFile && layerOf(typeFile, contextPath);
1403
- const implementationsLayer = layerOf(implementations[0].file, contextPath);
1404
- if (!typeFile || !layer || !implementationsLayer) return;
1405
- return {
1406
- wireName,
1407
- typeName,
1408
- wireFile,
1409
- typeFile,
1410
- layer,
1411
- implementations,
1412
- branched,
1413
- implementationsLayer,
1414
- kind: wiringFolder
1415
- };
1416
- };
1417
- const findWiredModules = (contextPath)=>{
1418
- const result = [];
1419
- const walk = (folderPath)=>{
1420
- if (!node_fs.existsSync(folderPath)) return;
1421
- for (const entry of node_fs.readdirSync(folderPath, {
1422
- withFileTypes: true
1423
- })){
1424
- const entryPath = node_path.join(folderPath, entry.name);
1425
- if (entry.isDirectory()) walk(entryPath);
1426
- else if (/^wire-.*(?<!\.spec)\.ts$/.test(entry.name)) {
1427
- const wiredModule = readWiredModule(entryPath, contextPath);
1428
- if (wiredModule) result.push(wiredModule);
1429
- }
1430
- }
1431
- };
1432
- walk(node_path.join(contextPath, 'wiring'));
1433
- return result.sort((a, b)=>a.typeName.localeCompare(b.typeName));
1434
- };
1435
- const isCommandOrQuery = (module)=>'commands' === module.kind || 'queries' === module.kind;
1436
- const isExecution = (module)=>isCommandOrQuery(module) && 'execution' === node_path.basename(node_path.dirname(module.typeFile));
1437
- const commandOrQueryRule = (candidate, consumer)=>isExecution(consumer) ? !isCommandOrQuery(candidate) : 'application' !== candidate.layer || isExecution(candidate);
1438
- const layerRules = {
1439
- infrastructure: (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind
1440
- };
1441
- const kindRules = {
1442
- 'application-services': (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind,
1443
- 'use-cases': (candidate)=>'use-cases' !== candidate.kind,
1444
- repositories: (candidate)=>'repositories' !== candidate.kind,
1445
- commands: commandOrQueryRule,
1446
- queries: commandOrQueryRule
1447
- };
1448
- const wiring_implementationType = (consumer, implementation)=>consumer.branched ? node_path.basename(node_path.dirname(implementation.file)) : void 0;
1449
- const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && `-${node_path.basename(candidate.typeFile, '.ts')}-`.includes(`-${implementation}-`);
1450
- const canDependOn = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && (layerRules[consumer.implementationsLayer]?.(candidate) ?? true) && (kindRules[consumer.kind]?.(candidate, consumer) ?? true);
1451
- const availableDependencies = (consumer, implementation, candidates)=>{
1452
- const wired = wiredDependencyNames(new File(consumer.wireFile).data, implementation.className);
1453
- return candidates.filter((candidate)=>candidate.wireFile !== consumer.wireFile && canDependOn(consumer, candidate) && !wired.includes(candidate.wireName));
1454
- };
1455
- const relativeImport = (fromFile, toFile)=>{
1456
- const relativePath = node_path.relative(node_path.dirname(fromFile), toFile).replace(/\.ts$/, '').split(node_path.sep).join('/');
1457
- return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
1458
- };
1459
- const codeOnly = (source)=>{
1460
- let result = '';
1461
- let index = 0;
1462
- const blank = (text)=>text.replace(/[^\n]/g, ' ');
1463
- while(index < source.length){
1464
- const pair = source.slice(index, index + 2);
1465
- const char = source[index];
1466
- let end = index + 1;
1467
- if ('//' === pair) {
1468
- const lineEnd = source.indexOf('\n', index);
1469
- end = -1 === lineEnd ? source.length : lineEnd;
1470
- result += blank(source.slice(index, end));
1471
- } else if ('/*' === pair) {
1472
- const commentEnd = source.indexOf('*/', index + 2);
1473
- end = -1 === commentEnd ? source.length : commentEnd + 2;
1474
- result += blank(source.slice(index, end));
1475
- } else if ('=>' === pair) {
1476
- end = index + 2;
1477
- result += ' ';
1478
- } else if ("'" === char || '"' === char || '`' === char) {
1479
- while(end < source.length && source[end] !== char)end += '\\' === source[end] ? 2 : 1;
1480
- end = Math.min(end + 1, source.length);
1481
- result += char + blank(source.slice(index + 1, end - 1));
1482
- result += end - 1 > index ? source[end - 1] : '';
1483
- } else result += char;
1484
- index = end;
1485
- }
1486
- return result;
1487
- };
1488
- const addImport = (source, importLine)=>{
1489
- if (source.split('\n').some((line)=>line.trim() === importLine)) return source;
1490
- const lastImport = [
1491
- ...codeOnly(source).matchAll(/^import\s(?:[^'"]*?from\s*)?['"][^'"]*['"]/gm)
1492
- ].at(-1);
1493
- if (!lastImport) return `${importLine}\n\n${source}`;
1494
- const importEnd = lastImport.index + lastImport[0].length;
1495
- const lineEnd = source.indexOf('\n', importEnd);
1496
- const insertAt = -1 === lineEnd ? source.length : lineEnd;
1497
- return `${source.slice(0, insertAt)}\n${importLine}${source.slice(insertAt)}`;
1498
- };
1499
- const brackets = {
1500
- '(': ')',
1501
- '[': ']',
1502
- '{': '}',
1503
- '<': '>'
1504
- };
1505
- const closingIndex = (source, openIndex)=>{
1506
- const code = codeOnly(source);
1507
- let depth = 0;
1508
- for(let index = openIndex; index < code.length; index++){
1509
- const char = code[index];
1510
- if (char === code[openIndex]) depth++;
1511
- else if (char === brackets[code[openIndex]]) {
1512
- depth--;
1513
- if (0 === depth) return index;
1514
- }
1515
- }
1516
- return -1;
1517
- };
1518
- const splitTopLevel = (content)=>{
1519
- const code = codeOnly(content);
1520
- const items = [];
1521
- let depth = 0;
1522
- let itemStart = 0;
1523
- for(let index = 0; index <= code.length; index++){
1524
- const char = code[index];
1525
- if (void 0 !== char && char in brackets) depth++;
1526
- else if (Object.values(brackets).includes(char)) depth--;
1527
- if (index === code.length || ',' === char && 0 === depth) {
1528
- const item = content.slice(itemStart, index);
1529
- const itemCode = code.slice(itemStart, index);
1530
- const first = itemCode.search(/\S/);
1531
- const last = itemCode.search(/\S\s*$/);
1532
- if (-1 !== first) items.push(item.slice(first, last + 1));
1533
- itemStart = index + 1;
1534
- }
1535
- }
1536
- return items;
1537
- };
1538
- const appendItems = (content, items)=>{
1539
- const code = codeOnly(content);
1540
- const lastCode = code.search(/\S\s*$/);
1541
- if (-1 === lastCode) return items.join(', ');
1542
- const trailingComma = ',' === code[lastCode];
1543
- if (!content.includes('\n')) {
1544
- const added = trailingComma ? ` ${items.join(', ')},` : `, ${items.join(', ')}`;
1545
- return content.slice(0, lastCode + 1) + added + content.slice(lastCode + 1);
1546
- }
1547
- const indent = content.match(/\n([ \t]*)\S/)?.[1] ?? '';
1548
- const withComma = trailingComma ? content : `${content.slice(0, lastCode + 1)},${content.slice(lastCode + 1)}`;
1549
- const lineEndIndex = withComma.indexOf('\n', lastCode + 1);
1550
- const lineEnd = -1 === lineEndIndex ? withComma.length : lineEndIndex;
1551
- const added = trailingComma ? items.map((x)=>`\n${indent}${x},`).join('') : items.map((x)=>`\n${indent}${x}`).join(',');
1552
- return withComma.slice(0, lineEnd) + added + withComma.slice(lineEnd);
1553
- };
1554
- const addConstructorParameters = (source, className, parameters)=>{
1555
- const classMatch = new RegExp(`class\\s+${className}\\b[^{]*\\{`).exec(codeOnly(source));
1556
- if (!classMatch) throw new Error(`Class ${className} not found`);
1557
- const bodyStart = classMatch.index + classMatch[0].length;
1558
- const bodyEnd = closingIndex(source, bodyStart - 1);
1559
- const body = source.slice(bodyStart, bodyEnd);
1560
- const constructorIndex = codeOnly(body).search(/\bconstructor\s*\(/);
1561
- const renderParameters = (allParameters, indent)=>1 === allParameters.length ? allParameters[0] : `\n${allParameters.map((x)=>`${indent} ${x}`).join(',\n')}\n${indent}`;
1562
- if (-1 === constructorIndex) {
1563
- const constructorBody = /\bextends\b/.test(classMatch[0]) ? '{\n super()\n }' : '{}';
1564
- const constructorLine = ` constructor(${renderParameters(parameters, ' ')}) ${constructorBody}`;
1565
- const newBody = body.trim() ? `\n${constructorLine}\n${body.replace(/^\s*\n/, '\n')}` : `\n${constructorLine}\n`;
1566
- return source.slice(0, bodyStart) + newBody + source.slice(bodyEnd);
1567
- }
1568
- const openIndex = bodyStart + body.indexOf('(', constructorIndex);
1569
- const closeIndex = closingIndex(source, openIndex);
1570
- const content = source.slice(openIndex + 1, closeIndex);
1571
- if (content.includes('\n')) return source.slice(0, openIndex + 1) + appendItems(content, parameters) + source.slice(closeIndex);
1572
- const lineStart = source.lastIndexOf('\n', openIndex) + 1;
1573
- const indent = source.slice(lineStart).match(/^\s*/)?.[0] ?? '';
1574
- return source.slice(0, openIndex + 1) + renderParameters([
1575
- ...splitTopLevel(content),
1576
- ...parameters
1577
- ], indent) + source.slice(closeIndex);
1578
- };
1579
- const addClassMember = (source, className, member)=>{
1580
- const classMatch = new RegExp(`class\\s+${className}\\b[^{]*\\{`).exec(codeOnly(source));
1581
- if (!classMatch) throw new Error(`Class ${className} not found`);
1582
- const bodyStart = classMatch.index + classMatch[0].length;
1583
- const bodyEnd = closingIndex(source, bodyStart - 1);
1584
- const body = source.slice(bodyStart, bodyEnd).trimEnd();
1585
- const separator = body.trim() ? '\n\n' : '\n';
1586
- return `${source.slice(0, bodyStart)}${body}${separator} ${member}\n${source.slice(bodyEnd)}`;
1587
- };
1588
- const wireListRange = (source, className)=>{
1589
- const match = new RegExp(`wireClass\\(\\s*${className}\\s*,\\s*\\[`).exec(codeOnly(source));
1590
- if (!match) throw new Error(`wireClass(${className}, [...]) not found`);
1591
- const openIndex = match.index + match[0].length - 1;
1592
- return {
1593
- openIndex,
1594
- closeIndex: closingIndex(source, openIndex)
1595
- };
1596
- };
1597
- const wiredDependencyNames = (source, className)=>{
1598
- const { openIndex, closeIndex } = wireListRange(source, className);
1599
- return splitTopLevel(source.slice(openIndex + 1, closeIndex));
1600
- };
1601
- const addWireDependencies = (source, className, wireNames)=>{
1602
- const { openIndex, closeIndex } = wireListRange(source, className);
1603
- return source.slice(0, openIndex + 1) + appendItems(source.slice(openIndex + 1, closeIndex), wireNames) + source.slice(closeIndex);
1604
- };
1605
- const parameterName = (typeName)=>typeName.substring(0, 1).toLowerCase() + typeName.substring(1);
1606
- const wireDependencies = (consumer, implementation, dependencies)=>{
1607
- const wireFile = new File(consumer.wireFile);
1608
- let wireSource = wireFile.data;
1609
- for (const dependency of dependencies)wireSource = addImport(wireSource, `import { ${dependency.wireName} } from '${relativeImport(consumer.wireFile, dependency.wireFile)}'`);
1610
- wireFile.update(addWireDependencies(wireSource, implementation.className, dependencies.map((x)=>x.wireName)));
1611
- const classFile = new File(implementation.file);
1612
- let classSource = classFile.data;
1613
- for (const dependency of dependencies)classSource = addImport(classSource, `import type { ${dependency.typeName} } from '${relativeImport(implementation.file, dependency.typeFile)}'`);
1614
- classFile.update(addConstructorParameters(classSource, implementation.className, dependencies.map((x)=>`private readonly ${parameterName(x.typeName)}: ${x.typeName}`)));
1615
- };
1616
1051
  const inMemoryImplementationType = 'in-memory';
1617
1052
  const in_memory_db_className = 'InMemoryDbInfrastructureService';
1618
- const in_memory_db_wireName = 'wireInMemoryDbInfrastructureService';
1619
- const in_memory_db_parameterName = 'inMemoryDbInfrastructureService';
1053
+ const wireName = 'wireInMemoryDbInfrastructureService';
1054
+ const parameterName = 'inMemoryDbInfrastructureService';
1620
1055
  const inMemoryDbService = `type Entry = {
1621
1056
  id: unknown;
1622
1057
  item: any;
@@ -1796,22 +1231,22 @@ const inMemoryDbTypeImport = (fromFile)=>`import type { ${in_memory_db_className
1796
1231
  const inMemoryDbSectionMembers = (field, derived)=>`
1797
1232
  private readonly data: ${in_memory_db_className}['${field}']
1798
1233
 
1799
- constructor(${in_memory_db_parameterName}: ${in_memory_db_className}) {
1800
- ${derived ? 'super()\n ' : ''}this.data = ${in_memory_db_parameterName}.${field}
1234
+ constructor(${parameterName}: ${in_memory_db_className}) {
1235
+ ${derived ? 'super()\n ' : ''}this.data = ${parameterName}.${field}
1801
1236
  }
1802
1237
  `.trim();
1803
1238
  const keepInMemoryDbSection = (classFile, field)=>{
1804
1239
  classFile.update(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)).replace('constructor() {}', inMemoryDbSectionMembers(field, false)));
1805
1240
  };
1806
- const isInMemoryDb = (module)=>module.wireName === in_memory_db_wireName;
1241
+ const isInMemoryDb = (module)=>module.wireName === wireName;
1807
1242
  const injectInMemoryDb = (classFile, implementationName)=>{
1808
1243
  classFile.update(addConstructorParameters(addImport(classFile.data, inMemoryDbTypeImport(classFile.path)), implementationName, [
1809
- `private readonly ${in_memory_db_parameterName}: ${in_memory_db_className}`
1244
+ `private readonly ${parameterName}: ${in_memory_db_className}`
1810
1245
  ]));
1811
1246
  };
1812
1247
  const wireInMemoryDb = (consumerWireFile, implementationName)=>{
1813
- consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${in_memory_db_wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
1814
- in_memory_db_wireName
1248
+ consumerWireFile.update(addWireDependencies(addImport(consumerWireFile.data, `import { ${wireName} } from '${relativeImport(consumerWireFile.path, in_memory_db_wireFile().path)}'`), implementationName, [
1249
+ wireName
1815
1250
  ]));
1816
1251
  };
1817
1252
  const passInMemoryDb = (specFile, implementationName)=>{
@@ -2154,13 +1589,13 @@ const ignoredFolders = new Set([
2154
1589
  ]);
2155
1590
  const codeExtension = /\.(?:tsx?|mts|cts|jsx?|mjs|cjs|mdx)$/;
2156
1591
  const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
2157
- const react_module_move_walk = (folder)=>{
1592
+ const walk = (folder)=>{
2158
1593
  if (!node_fs.existsSync(folder)) return [];
2159
1594
  return node_fs.readdirSync(folder, {
2160
1595
  withFileTypes: true
2161
1596
  }).flatMap((entry)=>{
2162
1597
  const entryPath = node_path.join(folder, entry.name);
2163
- if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : react_module_move_walk(entryPath);
1598
+ if (entry.isDirectory()) return ignoredFolders.has(entry.name) ? [] : walk(entryPath);
2164
1599
  return entry.isFile() ? [
2165
1600
  entryPath
2166
1601
  ] : [];
@@ -2181,7 +1616,7 @@ const declaredClassName = (filePath, suffix, name)=>{
2181
1616
  return declared ?? new NestedName(name).ClassName;
2182
1617
  };
2183
1618
  const findReactModules = (reactFolder, kind)=>{
2184
- const modules = 'page' === kind ? react_module_move_walk(node_path.join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
1619
+ const modules = 'page' === kind ? walk(node_path.join(reactFolder, 'pages')).filter((file)=>file.endsWith('-page.tsx')).map((file)=>{
2185
1620
  const folders = node_path.relative(node_path.join(reactFolder, 'pages'), node_path.dirname(file)).split(node_path.sep).filter((segment)=>!!segment);
2186
1621
  const fileBase = node_path.basename(file, '-page.tsx');
2187
1622
  const name = nestedName(folders, fileBase);
@@ -2192,7 +1627,7 @@ const findReactModules = (reactFolder, kind)=>{
2192
1627
  fileBase,
2193
1628
  ClassName: declaredClassName(file, 'Page', name)
2194
1629
  };
2195
- }) : react_module_move_walk(node_path.join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
1630
+ }) : walk(node_path.join(reactFolder, 'widgets')).filter((file)=>file.endsWith('-widget.tsx')).map((file)=>{
2196
1631
  const folder = node_path.dirname(file);
2197
1632
  const name = toPosix(node_path.relative(node_path.join(reactFolder, 'widgets'), folder));
2198
1633
  return {
@@ -2205,14 +1640,14 @@ const findReactModules = (reactFolder, kind)=>{
2205
1640
  });
2206
1641
  return modules.sort((a, b)=>a.name.localeCompare(b.name));
2207
1642
  };
2208
- const react_module_move_targetPath = (reactFolder, module, rawName)=>{
1643
+ const targetPath = (reactFolder, module, rawName)=>{
2209
1644
  const { folders, folderName, fileName } = new NestedName(rawName);
2210
1645
  return 'page' === module.kind ? node_path.join(reactFolder, 'pages', ...folders, `${fileName}-page.tsx`) : node_path.join(reactFolder, 'widgets', ...folders, folderName);
2211
1646
  };
2212
1647
  const validateMove = (reactFolder, module, rawName)=>{
2213
1648
  const nameError = NestedName.validate(rawName);
2214
1649
  if (true !== nameError) return nameError;
2215
- const target = react_module_move_targetPath(reactFolder, module, rawName);
1650
+ const target = targetPath(reactFolder, module, rawName);
2216
1651
  if (target !== module.path && node_fs.existsSync(target)) return `${node_path.relative(reactFolder, target)} already exists`;
2217
1652
  if (target.startsWith(`${module.path}${node_path.sep}`)) return 'A widget cannot be moved into itself';
2218
1653
  return true;
@@ -2244,7 +1679,7 @@ const importPaths = (file)=>{
2244
1679
  };
2245
1680
  const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
2246
1681
  const newName = new NestedName(rawName);
2247
- const target = react_module_move_targetPath(reactFolder, module, rawName);
1682
+ const target = targetPath(reactFolder, module, rawName);
2248
1683
  const newClassName = newName.ClassName;
2249
1684
  const renameFile = (name)=>name.replace(new RegExp(`^(use-)?${escapeRegExp(module.fileBase)}(?=[-.])`), (_, use = '')=>`${use}${newName.fileName}`);
2250
1685
  const oldFolder = 'page' === module.kind ? node_path.dirname(module.path) : module.path;
@@ -2257,7 +1692,7 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
2257
1692
  segments[last] = renameFile(segments[last]);
2258
1693
  return node_path.join(newFolder, ...segments);
2259
1694
  };
2260
- 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)) : react_module_move_walk(oldFolder);
1695
+ 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);
2261
1696
  const moves = new Map(moduleFiles.map((file)=>[
2262
1697
  file,
2263
1698
  movedPath(file) ?? file
@@ -2288,7 +1723,7 @@ const moveReactModule = (projectRoot, reactFolder, module, rawName)=>{
2288
1723
  'Widgets',
2289
1724
  ...newName.classNameSegments
2290
1725
  ].join('/');
2291
- const codeFiles = new Map(react_module_move_walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
1726
+ const codeFiles = new Map(walk(projectRoot).filter((file)=>codeExtension.test(file)).map((file)=>[
2292
1727
  file,
2293
1728
  node_fs.readFileSync(file, 'utf8')
2294
1729
  ]));