@domain-first/project-structure 4.1.0 → 4.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -31,6 +31,106 @@ const external_node_path_namespaceObject = require("node:path");
31
31
  var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
32
32
  const external_zod_namespaceObject = require("zod");
33
33
  var external_zod_default = /*#__PURE__*/ __webpack_require__.n(external_zod_namespaceObject);
34
+ const moduleKinds = [
35
+ 'repositories',
36
+ 'domain-services',
37
+ 'application-ports',
38
+ 'application-services',
39
+ 'use-cases',
40
+ 'execution-commands',
41
+ 'execution-queries',
42
+ 'orchestration-commands',
43
+ 'orchestration-queries',
44
+ 'infrastructure-services',
45
+ 'presentation-services'
46
+ ];
47
+ const domain = [
48
+ 'repositories',
49
+ 'domain-services'
50
+ ];
51
+ const commandsAndQueries = [
52
+ 'execution-commands',
53
+ 'execution-queries',
54
+ 'orchestration-commands',
55
+ 'orchestration-queries'
56
+ ];
57
+ const infrastructure = [
58
+ ...domain,
59
+ 'application-ports',
60
+ 'infrastructure-services'
61
+ ];
62
+ const defaultDependencies = {
63
+ 'domain-services': domain,
64
+ repositories: [
65
+ 'domain-services',
66
+ 'application-ports',
67
+ 'infrastructure-services'
68
+ ],
69
+ 'application-ports': infrastructure,
70
+ 'application-services': [
71
+ ...domain,
72
+ 'application-ports',
73
+ ...commandsAndQueries
74
+ ],
75
+ 'use-cases': [
76
+ ...domain,
77
+ 'application-ports',
78
+ 'application-services',
79
+ ...commandsAndQueries
80
+ ],
81
+ 'execution-commands': infrastructure,
82
+ 'execution-queries': infrastructure,
83
+ 'orchestration-commands': [
84
+ ...domain,
85
+ 'execution-commands',
86
+ 'execution-queries'
87
+ ],
88
+ 'orchestration-queries': [
89
+ ...domain,
90
+ 'execution-queries'
91
+ ],
92
+ 'infrastructure-services': infrastructure,
93
+ 'presentation-services': [
94
+ 'application-ports',
95
+ 'application-services',
96
+ 'use-cases',
97
+ ...commandsAndQueries,
98
+ 'presentation-services'
99
+ ]
100
+ };
101
+ const kindSchema = external_zod_default()["enum"](moduleKinds);
102
+ const dependencyRulesSchema = external_zod_default().partialRecord(kindSchema, external_zod_default().union([
103
+ external_zod_default().array(kindSchema),
104
+ external_zod_default().object({
105
+ add: external_zod_default().array(kindSchema).optional(),
106
+ remove: external_zod_default().array(kindSchema).optional()
107
+ })
108
+ ]));
109
+ const resolveDependencyRules = (config = {})=>{
110
+ const entries = moduleKinds.map((kind)=>{
111
+ const override = config[kind];
112
+ if (Array.isArray(override)) return [
113
+ kind,
114
+ new Set(override)
115
+ ];
116
+ const kinds = new Set([
117
+ ...defaultDependencies[kind],
118
+ ...override?.add ?? []
119
+ ]);
120
+ for (const removed of override?.remove ?? [])kinds.delete(removed);
121
+ return [
122
+ kind,
123
+ kinds
124
+ ];
125
+ });
126
+ return Object.fromEntries(entries);
127
+ };
128
+ const defaultDependencyRules = resolveDependencyRules();
129
+ const isModuleKind = (value)=>moduleKinds.includes(value);
130
+ const wiredModuleKind = (wiringKind, typeFile)=>{
131
+ const kind = 'commands' === wiringKind || 'queries' === wiringKind ? `${'execution' === external_node_path_default().basename(external_node_path_default().dirname(typeFile)) ? 'execution' : 'orchestration'}-${wiringKind}` : wiringKind;
132
+ return isModuleKind(kind) ? kind : void 0;
133
+ };
34
134
  const external_node_fs_namespaceObject = require("node:fs");
35
135
  var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
36
136
  const pendingFiles = new Map();
@@ -182,6 +282,14 @@ class ProjectRoot {
182
282
  throw new Error('No package.json was found');
183
283
  }
184
284
  }
285
+ const lintChecks = [
286
+ 'context-isolation',
287
+ 'shared-layer',
288
+ 'layers',
289
+ 'dependencies',
290
+ 'react',
291
+ 'clock'
292
+ ];
185
293
  const configFileName = 'domain-first.project-structure.config.json';
186
294
  const configSchema = external_zod_default().object({
187
295
  rootFolder: external_zod_default().string(),
@@ -196,7 +304,11 @@ const configSchema = external_zod_default().object({
196
304
  withInMemoryDb: external_zod_default().boolean().optional(),
197
305
  useReact: external_zod_default().boolean(),
198
306
  storybookFramework: external_zod_default().string().optional(),
199
- testingLibrary: external_zod_default().string().optional()
307
+ testingLibrary: external_zod_default().string().optional(),
308
+ rules: external_zod_default().object({
309
+ dependencies: dependencyRulesSchema.optional(),
310
+ lint: external_zod_default().partialRecord(external_zod_default()["enum"](lintChecks), external_zod_default().boolean()).optional()
311
+ }).optional()
200
312
  });
201
313
  class ConfigFile {
202
314
  data;
@@ -220,6 +332,7 @@ class ConfigFile {
220
332
  new File(ConfigFile.path).data = JSON.stringify(config, null, '\t');
221
333
  };
222
334
  }
335
+ const configuredDependencyRules = ()=>resolveDependencyRules(ConfigFile.exists ? ConfigFile.Instance.data.rules?.dependencies : void 0);
223
336
  const external_node_util_namespaceObject = require("node:util");
224
337
  const printNextSteps = (nextSteps)=>{
225
338
  const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
@@ -1462,25 +1575,18 @@ const findWiredModules = (contextPath)=>{
1462
1575
  walk(external_node_path_default().join(contextPath, 'wiring'));
1463
1576
  return result.sort((a, b)=>a.typeName.localeCompare(b.typeName));
1464
1577
  };
1465
- const isCommandOrQuery = (module)=>'commands' === module.kind || 'queries' === module.kind;
1466
- const isExecution = (module)=>isCommandOrQuery(module) && 'execution' === external_node_path_default().basename(external_node_path_default().dirname(module.typeFile));
1467
- const commandOrQueryRule = (candidate, consumer)=>isExecution(consumer) ? !isCommandOrQuery(candidate) : 'application' !== candidate.layer || isExecution(candidate) && ('commands' === consumer.kind || 'queries' === candidate.kind);
1468
- const layerRules = {
1469
- infrastructure: (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind
1470
- };
1471
- const kindRules = {
1472
- 'application-services': (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind,
1473
- 'use-cases': (candidate)=>'use-cases' !== candidate.kind,
1474
- repositories: (candidate)=>'repositories' !== candidate.kind,
1475
- commands: commandOrQueryRule,
1476
- queries: commandOrQueryRule
1477
- };
1578
+ const moduleKindOf = (module)=>wiredModuleKind(module.kind, module.typeFile);
1579
+ const layerRule = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && ('infrastructure' !== consumer.implementationsLayer || 'application' !== candidate.layer || 'application-ports' === candidate.kind);
1478
1580
  const wiring_implementationType = (consumer, implementation)=>consumer.branched ? external_node_path_default().basename(external_node_path_default().dirname(implementation.file)) : void 0;
1479
1581
  const isSuggestedFor = (candidate, implementation)=>'infrastructure' === candidate.layer && `-${external_node_path_default().basename(candidate.typeFile, '.ts')}-`.includes(`-${implementation}-`);
1480
- const canDependOn = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && (layerRules[consumer.implementationsLayer]?.(candidate) ?? true) && (kindRules[consumer.kind]?.(candidate, consumer) ?? true);
1481
- const availableDependencies = (consumer, implementation, candidates)=>{
1582
+ const canDependOn = (consumer, candidate, rules = defaultDependencyRules)=>{
1583
+ const consumerKind = moduleKindOf(consumer);
1584
+ const candidateKind = moduleKindOf(candidate);
1585
+ return consumerKind && candidateKind ? rules[consumerKind].has(candidateKind) : layerRule(consumer, candidate);
1586
+ };
1587
+ const availableDependencies = (consumer, implementation, candidates, rules = configuredDependencyRules())=>{
1482
1588
  const wired = wiredDependencyNames(new File(consumer.wireFile).data, implementation.className);
1483
- return candidates.filter((candidate)=>candidate.wireFile !== consumer.wireFile && canDependOn(consumer, candidate) && !wired.includes(candidate.wireName));
1589
+ return candidates.filter((candidate)=>candidate.wireFile !== consumer.wireFile && canDependOn(consumer, candidate, rules) && !wired.includes(candidate.wireName));
1484
1590
  };
1485
1591
  const relativeImport = (fromFile, toFile)=>{
1486
1592
  const relativePath = external_node_path_default().relative(external_node_path_default().dirname(fromFile), toFile).replace(/\.ts$/, '').split(external_node_path_default().sep).join('/');
@@ -2024,11 +2130,8 @@ const scaffoldRestEndpointGenerator = (sharedFolder, { withNextAdapter = false }
2024
2130
  return `
2025
2131
  import {
2026
2132
  ${withNextAdapter ? '' : ' type Adapter,\n'} type EndpointGenerator,
2027
- type ErrorMapping,
2028
2133
  createEndpoint,
2029
- httpStatus,
2030
- InputMappingError,
2031
- RequestParsingError
2134
+ invalidRequest
2032
2135
  } from '@domain-first/handlers-rest'
2033
2136
  ${withNextAdapter ? "import { nextAdapter } from '@domain-first/handlers-next'" : `
2034
2137
  /**
@@ -2037,24 +2140,9 @@ ${withNextAdapter ? "import { nextAdapter } from '@domain-first/handlers-next'"
2037
2140
  const adapter = undefined as unknown as Adapter<any[], any>`}
2038
2141
 
2039
2142
  export class ${className} {
2040
- /**
2041
- * Default errors of a client request, to spread into a generator's
2042
- * own error mappings.
2043
- */
2044
- private get defaultClientRequestErrors(): ErrorMapping[] {
2045
- return [
2046
- httpStatus(400, {
2047
- code: 'INVALID_REQUEST',
2048
- description: 'Invalid request',
2049
- message: (error) => error.message,
2050
- match: [RequestParsingError, InputMappingError]
2051
- })
2052
- ]
2053
- }
2054
-
2055
2143
  get withoutGuards(): EndpointGenerator {
2056
2144
  return createEndpoint({
2057
- errors: this.defaultClientRequestErrors
2145
+ errors: [invalidRequest()]
2058
2146
  })(${adapter}) as EndpointGenerator
2059
2147
  }
2060
2148
  }
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import { Separator, checkbox as prompts_checkbox, confirm as prompts_confirm, in
3
3
  import { styleText } from "node:util";
4
4
  import node_path from "node:path";
5
5
  import node_fs from "node:fs";
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 "./533.js";
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";
7
7
  const printNextSteps = (nextSteps)=>{
8
8
  const isCommand = (line)=>/^\s*(?:npm (?:i|install)|npx playwright install)\b/.test(line);
9
9
  const commands = nextSteps.filter(isCommand);
@@ -1429,11 +1429,8 @@ const scaffoldRestEndpointGenerator = (sharedFolder, { withNextAdapter = false }
1429
1429
  return `
1430
1430
  import {
1431
1431
  ${withNextAdapter ? '' : ' type Adapter,\n'} type EndpointGenerator,
1432
- type ErrorMapping,
1433
1432
  createEndpoint,
1434
- httpStatus,
1435
- InputMappingError,
1436
- RequestParsingError
1433
+ invalidRequest
1437
1434
  } from '@domain-first/handlers-rest'
1438
1435
  ${withNextAdapter ? "import { nextAdapter } from '@domain-first/handlers-next'" : `
1439
1436
  /**
@@ -1442,24 +1439,9 @@ ${withNextAdapter ? "import { nextAdapter } from '@domain-first/handlers-next'"
1442
1439
  const adapter = undefined as unknown as Adapter<any[], any>`}
1443
1440
 
1444
1441
  export class ${className} {
1445
- /**
1446
- * Default errors of a client request, to spread into a generator's
1447
- * own error mappings.
1448
- */
1449
- private get defaultClientRequestErrors(): ErrorMapping[] {
1450
- return [
1451
- httpStatus(400, {
1452
- code: 'INVALID_REQUEST',
1453
- description: 'Invalid request',
1454
- message: (error) => error.message,
1455
- match: [RequestParsingError, InputMappingError]
1456
- })
1457
- ]
1458
- }
1459
-
1460
1442
  get withoutGuards(): EndpointGenerator {
1461
1443
  return createEndpoint({
1462
- errors: this.defaultClientRequestErrors
1444
+ errors: [invalidRequest()]
1463
1445
  })(${adapter}) as EndpointGenerator
1464
1446
  }
1465
1447
  }
package/dist/lint.cjs CHANGED
@@ -31,6 +31,131 @@ const external_node_path_namespaceObject = require("node:path");
31
31
  var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
32
32
  const external_zod_namespaceObject = require("zod");
33
33
  var external_zod_default = /*#__PURE__*/ __webpack_require__.n(external_zod_namespaceObject);
34
+ const moduleKinds = [
35
+ 'repositories',
36
+ 'domain-services',
37
+ 'application-ports',
38
+ 'application-services',
39
+ 'use-cases',
40
+ 'execution-commands',
41
+ 'execution-queries',
42
+ 'orchestration-commands',
43
+ 'orchestration-queries',
44
+ 'infrastructure-services',
45
+ 'presentation-services'
46
+ ];
47
+ const domain = [
48
+ 'repositories',
49
+ 'domain-services'
50
+ ];
51
+ const commandsAndQueries = [
52
+ 'execution-commands',
53
+ 'execution-queries',
54
+ 'orchestration-commands',
55
+ 'orchestration-queries'
56
+ ];
57
+ const infrastructure = [
58
+ ...domain,
59
+ 'application-ports',
60
+ 'infrastructure-services'
61
+ ];
62
+ const defaultDependencies = {
63
+ 'domain-services': domain,
64
+ repositories: [
65
+ 'domain-services',
66
+ 'application-ports',
67
+ 'infrastructure-services'
68
+ ],
69
+ 'application-ports': infrastructure,
70
+ 'application-services': [
71
+ ...domain,
72
+ 'application-ports',
73
+ ...commandsAndQueries
74
+ ],
75
+ 'use-cases': [
76
+ ...domain,
77
+ 'application-ports',
78
+ 'application-services',
79
+ ...commandsAndQueries
80
+ ],
81
+ 'execution-commands': infrastructure,
82
+ 'execution-queries': infrastructure,
83
+ 'orchestration-commands': [
84
+ ...domain,
85
+ 'execution-commands',
86
+ 'execution-queries'
87
+ ],
88
+ 'orchestration-queries': [
89
+ ...domain,
90
+ 'execution-queries'
91
+ ],
92
+ 'infrastructure-services': infrastructure,
93
+ 'presentation-services': [
94
+ 'application-ports',
95
+ 'application-services',
96
+ 'use-cases',
97
+ ...commandsAndQueries,
98
+ 'presentation-services'
99
+ ]
100
+ };
101
+ const kindSchema = external_zod_default()["enum"](moduleKinds);
102
+ const dependencyRulesSchema = external_zod_default().partialRecord(kindSchema, external_zod_default().union([
103
+ external_zod_default().array(kindSchema),
104
+ external_zod_default().object({
105
+ add: external_zod_default().array(kindSchema).optional(),
106
+ remove: external_zod_default().array(kindSchema).optional()
107
+ })
108
+ ]));
109
+ const resolveDependencyRules = (config = {})=>{
110
+ const entries = moduleKinds.map((kind)=>{
111
+ const override = config[kind];
112
+ if (Array.isArray(override)) return [
113
+ kind,
114
+ new Set(override)
115
+ ];
116
+ const kinds = new Set([
117
+ ...defaultDependencies[kind],
118
+ ...override?.add ?? []
119
+ ]);
120
+ for (const removed of override?.remove ?? [])kinds.delete(removed);
121
+ return [
122
+ kind,
123
+ kinds
124
+ ];
125
+ });
126
+ return Object.fromEntries(entries);
127
+ };
128
+ const defaultDependencyRules = resolveDependencyRules();
129
+ const isModuleKind = (value)=>moduleKinds.includes(value);
130
+ const wiredModuleKind = (wiringKind, typeFile)=>{
131
+ const kind = 'commands' === wiringKind || 'queries' === wiringKind ? `${'execution' === external_node_path_default().basename(external_node_path_default().dirname(typeFile)) ? 'execution' : 'orchestration'}-${wiringKind}` : wiringKind;
132
+ return isModuleKind(kind) ? kind : void 0;
133
+ };
134
+ const fileModuleKind = (segments)=>{
135
+ const [layer, folder, mode] = segments;
136
+ const file = segments.at(-1) ?? '';
137
+ if (/^index(\.tsx?)?$/.test(file)) return;
138
+ if ('domain' === layer) {
139
+ if ('services' === folder) return 'domain-services';
140
+ return 'aggregates' === folder && /-repository(\.tsx?)?$/.test(file) ? 'repositories' : void 0;
141
+ }
142
+ if ('application' === layer) {
143
+ if ('commands' === folder || 'queries' === folder) return 'execution' === mode || 'orchestration' === mode ? `${mode}-${folder}` : void 0;
144
+ return ({
145
+ ports: 'application-ports',
146
+ services: 'application-services',
147
+ 'use-cases': 'use-cases'
148
+ })[folder];
149
+ }
150
+ if ('infrastructure' === layer) return ({
151
+ repositories: 'repositories',
152
+ commands: 'execution-commands',
153
+ queries: 'execution-queries',
154
+ 'application-adapters': 'application-ports',
155
+ services: 'infrastructure-services'
156
+ })[folder];
157
+ return 'presentation' === layer && 'services' === folder ? 'presentation-services' : void 0;
158
+ };
34
159
  const external_node_fs_namespaceObject = require("node:fs");
35
160
  var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
36
161
  const pendingFiles = new Map();
@@ -107,6 +232,14 @@ class ProjectRoot {
107
232
  throw new Error('No package.json was found');
108
233
  }
109
234
  }
235
+ const lintChecks = [
236
+ 'context-isolation',
237
+ 'shared-layer',
238
+ 'layers',
239
+ 'dependencies',
240
+ 'react',
241
+ 'clock'
242
+ ];
110
243
  const configFileName = 'domain-first.project-structure.config.json';
111
244
  const configSchema = external_zod_default().object({
112
245
  rootFolder: external_zod_default().string(),
@@ -121,7 +254,11 @@ const configSchema = external_zod_default().object({
121
254
  withInMemoryDb: external_zod_default().boolean().optional(),
122
255
  useReact: external_zod_default().boolean(),
123
256
  storybookFramework: external_zod_default().string().optional(),
124
- testingLibrary: external_zod_default().string().optional()
257
+ testingLibrary: external_zod_default().string().optional(),
258
+ rules: external_zod_default().object({
259
+ dependencies: dependencyRulesSchema.optional(),
260
+ lint: external_zod_default().partialRecord(external_zod_default()["enum"](lintChecks), external_zod_default().boolean()).optional()
261
+ }).optional()
125
262
  });
126
263
  class ConfigFile {
127
264
  data;
@@ -145,6 +282,7 @@ class ConfigFile {
145
282
  new file_system_File(ConfigFile.path).data = JSON.stringify(config, null, '\t');
146
283
  };
147
284
  }
285
+ const config_file_configuredDependencyRules = ()=>resolveDependencyRules(ConfigFile.exists ? ConfigFile.Instance.data.rules?.dependencies : void 0);
148
286
  const external_node_module_namespaceObject = require("node:module");
149
287
  const stripJsonComments = (source)=>source.replace(/("(?:\\.|[^"\\])*")|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, (_, text)=>text ? text : '').replace(/,(\s*[}\]])/g, '$1');
150
288
  const resolveExtends = (fromFile, target)=>{
@@ -342,20 +480,13 @@ const findWiredModules = (contextPath)=>{
342
480
  walk(external_node_path_default().join(contextPath, 'wiring'));
343
481
  return result.sort((a, b)=>a.typeName.localeCompare(b.typeName));
344
482
  };
345
- const isCommandOrQuery = (module)=>'commands' === module.kind || 'queries' === module.kind;
346
- const isExecution = (module)=>isCommandOrQuery(module) && 'execution' === external_node_path_default().basename(external_node_path_default().dirname(module.typeFile));
347
- const commandOrQueryRule = (candidate, consumer)=>isExecution(consumer) ? !isCommandOrQuery(candidate) : 'application' !== candidate.layer || isExecution(candidate) && ('commands' === consumer.kind || 'queries' === candidate.kind);
348
- const layerRules = {
349
- infrastructure: (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind
350
- };
351
- const kindRules = {
352
- 'application-services': (candidate)=>'application' !== candidate.layer || 'application-ports' === candidate.kind,
353
- 'use-cases': (candidate)=>'use-cases' !== candidate.kind,
354
- repositories: (candidate)=>'repositories' !== candidate.kind,
355
- commands: commandOrQueryRule,
356
- queries: commandOrQueryRule
483
+ const moduleKindOf = (module)=>wiredModuleKind(module.kind, module.typeFile);
484
+ const wiring_layerRule = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && ('infrastructure' !== consumer.implementationsLayer || 'application' !== candidate.layer || 'application-ports' === candidate.kind);
485
+ const canDependOn = (consumer, candidate, rules = defaultDependencyRules)=>{
486
+ const consumerKind = moduleKindOf(consumer);
487
+ const candidateKind = moduleKindOf(candidate);
488
+ return consumerKind && candidateKind ? rules[consumerKind].has(candidateKind) : wiring_layerRule(consumer, candidate);
357
489
  };
358
- const canDependOn = (consumer, candidate)=>visibleLayers[consumer.implementationsLayer].includes(candidate.layer) && (layerRules[consumer.implementationsLayer]?.(candidate) ?? true) && (kindRules[consumer.kind]?.(candidate, consumer) ?? true);
359
490
  const codeOnly = (source)=>{
360
491
  let result = '';
361
492
  let index = 0;
@@ -501,12 +632,9 @@ const layerImportRules = {
501
632
  rule: 'presentation imports infrastructure (only wiring knows concrete classes):'
502
633
  }
503
634
  };
504
- const isKindFile = (segments, kind)=>Boolean(segments && [
505
- 'application',
506
- 'infrastructure',
507
- 'wiring'
508
- ].includes(segments[0]) && segments[1] === kind);
509
- const importViolations = (projectRoot, rootFolder)=>{
635
+ const baseName = (file)=>external_node_path_default().basename(file).replace(/\.[^.]+$/, '');
636
+ const isOwnContract = (file, target)=>baseName(file).endsWith(`-${baseName(target)}`);
637
+ const importViolations = (projectRoot, rootFolder, rules)=>{
510
638
  const root = external_node_path_default().resolve(projectRoot, rootFolder);
511
639
  const contextsFolder = external_node_path_default().join(root, 'bounded-contexts');
512
640
  const sharedFolder = external_node_path_default().join(root, 'shared');
@@ -554,7 +682,8 @@ const importViolations = (projectRoot, rootFolder)=>{
554
682
  const source = external_node_fs_default().readFileSync(file, 'utf8');
555
683
  const from = locate(file);
556
684
  const ownContext = inside(contextsFolder, file)?.[0];
557
- const report = (rule, imported)=>violations.push({
685
+ const report = (check, rule, imported)=>violations.push({
686
+ check,
558
687
  rule,
559
688
  file,
560
689
  line: imported.line,
@@ -566,10 +695,10 @@ const importViolations = (projectRoot, rootFolder)=>{
566
695
  const to = locate(target);
567
696
  const targetContext = inside(contextsFolder, target)?.[0];
568
697
  if (ownContext) {
569
- if (targetContext && targetContext !== ownContext) report(`[${ownContext}] imports another context:`, imported);
698
+ if (targetContext && targetContext !== ownContext) report('context-isolation', `[${ownContext}] imports another context:`, imported);
570
699
  } else if (inside(sharedFolder, file)) {
571
700
  const allowed = !to || 'shared' === to.owner || 'domain' === to.segments[0] && 'errors' === to.segments[1] || file === inMemoryDbFile && isDomainModel(to.segments, target);
572
- if (!allowed) report('[shared] imports a bounded context outside its domain/errors (and domain models for the in-memory DB):', imported);
701
+ if (!allowed) report('shared-layer', '[shared] imports a bounded context outside its domain/errors (and domain models for the in-memory DB):', imported);
573
702
  } else if (inside(uiKitFolder, file) || inside(hooksFolder, file)) {
574
703
  const [area] = inside(reactFolder, target) ?? [];
575
704
  const forbidden = inside(uiKitFolder, file) ? [
@@ -580,20 +709,26 @@ const importViolations = (projectRoot, rootFolder)=>{
580
709
  'widgets',
581
710
  'pages'
582
711
  ];
583
- if (targetContext || forbidden.includes(area)) report(inside(uiKitFolder, file) ? '[presentation/react/ui-kit] imports a bounded context, widget or page:' : '[presentation/react/hooks] a shared hook imports a bounded context, UI-kit, widget or page:', imported);
584
- } else if (targetContext && !(imported.typeOnly && to?.segments[0] === 'presentation' && 'rest' === to.segments[1])) report('[presentation/react] imports a context other than `import type` from presentation/rest:', imported);
712
+ if (targetContext || forbidden.includes(area)) report('react', inside(uiKitFolder, file) ? '[presentation/react/ui-kit] imports a bounded context, widget or page:' : '[presentation/react/hooks] a shared hook imports a bounded context, UI-kit, widget or page:', imported);
713
+ } else if (targetContext && !(imported.typeOnly && to?.segments[0] === 'presentation' && 'rest' === to.segments[1])) report('react', '[presentation/react] imports a context other than `import type` from presentation/rest:', imported);
585
714
  const ownWidget = widgetOf(file);
586
715
  const targetWidget = widgetOf(target);
587
- if (ownWidget && targetWidget && targetWidget !== ownWidget) report('[presentation/react/widgets] a widget imports another widget:', imported);
716
+ if (ownWidget && targetWidget && targetWidget !== ownWidget) report('react', '[presentation/react/widgets] a widget imports another widget:', imported);
588
717
  if (!from || !to) continue;
589
- if (to.owner === from.owner && isKindFile(from.segments, 'queries') && isKindFile(to.segments, 'commands')) report(`[${from.owner}] a query imports a command (queries only read):`, imported);
718
+ if (isSpec(file)) continue;
719
+ const fromKind = fileModuleKind(from.segments);
720
+ const toKind = fileModuleKind(to.segments);
721
+ if (fromKind && toKind) {
722
+ if (!rules[fromKind].has(toKind) && !(fromKind === toKind && isOwnContract(file, target))) report('dependencies', `[${from.owner}] ${fromKind} may not use ${toKind} (dependency rules):`, imported);
723
+ if ('infrastructure' !== to.segments[0]) continue;
724
+ }
590
725
  const layerRule = layerImportRules[from.segments[0]];
591
- if (layerRule && !isSpec(file) && !layerRule.allows(to.segments)) report(`[${from.owner}] ${layerRule.rule}`, imported);
726
+ if (layerRule && !layerRule.allows(to.segments)) report('layers', `[${from.owner}] ${layerRule.rule}`, imported);
592
727
  }
593
728
  }
594
729
  return violations;
595
730
  };
596
- const wiringViolations = (projectRoot, rootFolder)=>{
731
+ const wiringViolations = (projectRoot, rootFolder, rules)=>{
597
732
  const root = external_node_path_default().resolve(projectRoot, rootFolder);
598
733
  const sharedFolder = external_node_path_default().join(root, 'shared');
599
734
  const contextsFolder = external_node_path_default().join(root, 'bounded-contexts');
@@ -631,13 +766,14 @@ const wiringViolations = (projectRoot, rootFolder)=>{
631
766
  const listStart = source.search(new RegExp(`wireClass\\(\\s*${implementation.className}\\b`));
632
767
  for (const dependency of dependencies){
633
768
  const candidate = visible.get(dependency);
634
- if (!candidate || canDependOn(consumer, candidate)) continue;
769
+ if (!candidate || canDependOn(consumer, candidate, rules)) continue;
635
770
  const index = source.indexOf(dependency, listStart);
636
771
  violations.push({
637
- rule: `[${name}] wiring: a dependency the CLI never offers (layer or kind rules):`,
772
+ check: 'dependencies',
773
+ rule: `[${name}] wiring: a dependency the dependency rules don't allow:`,
638
774
  file: consumer.wireFile,
639
775
  line: lineAt(source, index),
640
- text: `${implementation.className} ← ${candidate.typeName} (${candidate.kind})`
776
+ text: `${implementation.className} (${moduleKindOf(consumer) ?? consumer.kind}) ← ${candidate.typeName} (${moduleKindOf(candidate) ?? candidate.kind})`
641
777
  });
642
778
  }
643
779
  }
@@ -659,6 +795,7 @@ const clockViolations = (projectRoot, rootFolder)=>{
659
795
  return [
660
796
  ...source.matchAll(/\bnew\s+Date\s*\(\s*\)|\bDate\.now\s*\(/g)
661
797
  ].map((match)=>({
798
+ check: 'clock',
662
799
  rule: 'domain or application reads the current time directly (use the clock port):',
663
800
  file,
664
801
  line: lineAt(source, match.index),
@@ -666,11 +803,11 @@ const clockViolations = (projectRoot, rootFolder)=>{
666
803
  }));
667
804
  });
668
805
  };
669
- const lintProject = (projectRoot, rootFolder)=>[
670
- ...importViolations(projectRoot, rootFolder),
671
- ...wiringViolations(projectRoot, rootFolder),
806
+ const lintProject = (projectRoot, rootFolder, { rules = defaultDependencyRules, checks = {} } = {})=>[
807
+ ...importViolations(projectRoot, rootFolder, rules),
808
+ ...wiringViolations(projectRoot, rootFolder, rules),
672
809
  ...clockViolations(projectRoot, rootFolder)
673
- ];
810
+ ].filter((x)=>false !== checks[x.check]);
674
811
  const formatViolations = (violations, projectRoot)=>{
675
812
  const groups = new Map();
676
813
  for (const { rule, file, line, text } of violations)groups.set(rule, [
@@ -687,9 +824,10 @@ const formatViolations = (violations, projectRoot)=>{
687
824
  const help = `Usage: df-lint [rootFolder]
688
825
 
689
826
  Reports what breaks the Domain-First rules in the project:
690
- bounded context isolation, layers, wiring dependencies, React modules,
691
- queries using commands, and reading the time without the clock port.
692
- rootFolder defaults to the one in domain-first.project-structure.config.json.
827
+ bounded context isolation, layers, dependency rules (imports and wiring),
828
+ React modules, and reading the time without the clock port.
829
+ rootFolder defaults to the one in domain-first.project-structure.config.json,
830
+ whose optional \`rules\` change the dependency rules and turn checks off.
693
831
  Exits with 1 when something is found.
694
832
 
695
833
  Options:
@@ -709,8 +847,12 @@ if (values.help) {
709
847
  process.exit(0);
710
848
  }
711
849
  const lint_projectRoot = new ProjectRoot().path;
712
- const lint_rootFolder = positionals[0] ?? (ConfigFile.exists ? ConfigFile.Instance.data.rootFolder : 'src');
713
- const lint_violations = lintProject(lint_projectRoot, lint_rootFolder);
850
+ const lint_config = ConfigFile.exists ? ConfigFile.Instance.data : void 0;
851
+ const lint_rootFolder = positionals[0] ?? lint_config?.rootFolder ?? 'src';
852
+ const lint_violations = lintProject(lint_projectRoot, lint_rootFolder, {
853
+ rules: config_file_configuredDependencyRules(),
854
+ checks: lint_config?.rules?.lint
855
+ });
714
856
  if (lint_violations.length) {
715
857
  console.log(formatViolations(lint_violations, lint_projectRoot));
716
858
  console.log(`\n${lint_violations.length} problem(s) found.`);