@solid-stack/mason 1.0.21 → 1.0.23

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/bin.cjs CHANGED
@@ -4189,6 +4189,832 @@ async function handleImport(typeArg, nameArg, flags = {}) {
4189
4189
  );
4190
4190
  }
4191
4191
  }
4192
+ var DependencyRuleError = class extends Error {
4193
+ violations;
4194
+ isFailFast;
4195
+ constructor(message, violations, isFailFast = false) {
4196
+ super(message);
4197
+ this.name = "DependencyRuleError";
4198
+ this.violations = violations;
4199
+ this.isFailFast = isFailFast;
4200
+ }
4201
+ };
4202
+ function isTestFile2(filePath, projectRoot) {
4203
+ const norm = (projectRoot ? path2__default.default.relative(projectRoot, filePath) : filePath).replace(/\\/g, "/");
4204
+ const base = path2__default.default.basename(norm);
4205
+ return base.endsWith(".test.ts") || base.endsWith(".test.js") || base.endsWith(".spec.ts") || base.endsWith(".spec.js") || base.endsWith(".d.ts") || norm.includes("/__tests__/") || norm.startsWith("__tests__/") || /(?:^|\/)tests?\//.test(norm);
4206
+ }
4207
+ function scanDirFiles(dir, projectRoot) {
4208
+ if (!fs9__default.default.existsSync(dir)) return [];
4209
+ const entries = fs9__default.default.readdirSync(dir, { withFileTypes: true });
4210
+ const files = [];
4211
+ for (const entry of entries) {
4212
+ if (entry.name === "node_modules" || entry.name === "dist" || entry.name === "__tests__" || entry.name.startsWith(".")) {
4213
+ continue;
4214
+ }
4215
+ const fullPath = path2__default.default.join(dir, entry.name);
4216
+ if (entry.isDirectory()) {
4217
+ files.push(...scanDirFiles(fullPath, projectRoot));
4218
+ } else if (entry.isFile() && (entry.name.endsWith(".ts") || entry.name.endsWith(".js")) && !isTestFile2(fullPath, projectRoot)) {
4219
+ files.push(fullPath);
4220
+ }
4221
+ }
4222
+ return files;
4223
+ }
4224
+ function classifyFile(fullPath, projectRoot) {
4225
+ const rel = path2__default.default.relative(projectRoot, fullPath).replace(/\\/g, "/");
4226
+ const featureMatch = rel.match(/(?:^|\/)(?:src\/)?features\/([^/]+)\/([^/]+)(?:\/.*)?$/);
4227
+ if (!featureMatch || !featureMatch[1] || !featureMatch[2]) return {};
4228
+ const feature = featureMatch[1];
4229
+ const subfolder = featureMatch[2];
4230
+ let layer;
4231
+ if (subfolder === "domain" || subfolder === "errors") {
4232
+ layer = "domain";
4233
+ } else if (subfolder === "useCases" || subfolder === "usecases") {
4234
+ layer = "useCases";
4235
+ } else if (subfolder === "services") {
4236
+ layer = "services";
4237
+ } else if (subfolder === "infrastructure") {
4238
+ layer = "infrastructure";
4239
+ } else if (subfolder === "pxExpress" || subfolder === "presentation" || subfolder === "handlers" || subfolder.startsWith("px")) {
4240
+ layer = "presentation";
4241
+ }
4242
+ return { feature, layer };
4243
+ }
4244
+ function classifyTarget(specifier, sourceFileAbs, projectRoot) {
4245
+ if (specifier === "@solid-stack/di" || specifier.startsWith("@solid-stack/di/")) {
4246
+ return { isExternal: true, isDiFramework: true };
4247
+ }
4248
+ if (specifier.startsWith("node:") || ["crypto", "fs", "path", "http", "https", "url", "os", "child_process", "stream", "express", "cors", "dotenv"].includes(specifier)) {
4249
+ return { isExternal: true, isDiFramework: false };
4250
+ }
4251
+ let resolvedRel = null;
4252
+ if (specifier.startsWith(".")) {
4253
+ const abs = path2__default.default.resolve(path2__default.default.dirname(sourceFileAbs), specifier);
4254
+ resolvedRel = path2__default.default.relative(projectRoot, abs).replace(/\\/g, "/");
4255
+ } else if (specifier.startsWith("@/features/") || specifier.startsWith("~/features/")) {
4256
+ resolvedRel = specifier.replace(/^[@~]\//, "src/");
4257
+ } else if (specifier.startsWith("@features/")) {
4258
+ resolvedRel = "src/" + specifier.slice(1);
4259
+ } else if (specifier.startsWith("@/shared/") || specifier.startsWith("~/shared/")) {
4260
+ resolvedRel = specifier.replace(/^[@~]\//, "src/");
4261
+ } else if (specifier.startsWith("@shared/")) {
4262
+ resolvedRel = "src/" + specifier.slice(1);
4263
+ } else if (specifier.startsWith("@/") || specifier.startsWith("~/")) {
4264
+ resolvedRel = "src/" + specifier.slice(2);
4265
+ } else if (specifier.startsWith("features/") || specifier.startsWith("shared/")) {
4266
+ resolvedRel = specifier;
4267
+ }
4268
+ if (!resolvedRel) {
4269
+ return { isExternal: true, isDiFramework: false };
4270
+ }
4271
+ const featMatch = resolvedRel.match(/(?:^|\/)(?:src\/)?features\/([^/]+)\/([^/]+)(?:\/(.*))?$/);
4272
+ if (featMatch && featMatch[1] && featMatch[2]) {
4273
+ const targetFeature = featMatch[1];
4274
+ const targetSubfolder = featMatch[2];
4275
+ const rest = featMatch[3] || "";
4276
+ let targetLayer;
4277
+ if (targetSubfolder === "domain" || targetSubfolder === "errors") {
4278
+ targetLayer = "domain";
4279
+ } else if (targetSubfolder === "useCases" || targetSubfolder === "usecases") {
4280
+ targetLayer = "useCases";
4281
+ } else if (targetSubfolder === "services") {
4282
+ targetLayer = "services";
4283
+ } else if (targetSubfolder === "infrastructure") {
4284
+ targetLayer = "infrastructure";
4285
+ } else if (targetSubfolder === "pxExpress" || targetSubfolder === "presentation" || targetSubfolder === "handlers" || targetSubfolder.startsWith("px")) {
4286
+ targetLayer = "presentation";
4287
+ }
4288
+ const basePart = rest ? path2__default.default.basename(rest) : targetSubfolder;
4289
+ const targetFileName = basePart.replace(/\.(js|ts|mjs|cjs)$/, "");
4290
+ const isTargetPort = /^I[A-Z]/.test(targetFileName);
4291
+ const isTargetRepo = isTargetPort && targetFileName.includes("Repo");
4292
+ return {
4293
+ isExternal: false,
4294
+ isDiFramework: false,
4295
+ targetFeature,
4296
+ targetLayer,
4297
+ targetSubfolder,
4298
+ targetFileName,
4299
+ isTargetPort,
4300
+ isTargetRepo
4301
+ };
4302
+ }
4303
+ const sharedMatch = resolvedRel.match(/(?:^|\/)(?:src\/)?shared\/([^/]+)(?:\/(.*))?$/);
4304
+ if (sharedMatch) {
4305
+ const targetSharedModule = sharedMatch[1];
4306
+ const sharedRest = sharedMatch[2] || "";
4307
+ const isSharedRoot = !sharedRest.includes("/");
4308
+ const isSharedPorts = sharedRest.startsWith("ports/") || sharedRest === "ports";
4309
+ const isSharedInfra = sharedRest.startsWith("infrastructure/") || sharedRest === "infrastructure";
4310
+ const isSharedDomain = sharedRest.startsWith("domain/") || sharedRest === "domain";
4311
+ return {
4312
+ isExternal: false,
4313
+ isDiFramework: false,
4314
+ targetSharedModule,
4315
+ isSharedRoot,
4316
+ isSharedPorts,
4317
+ isSharedInfra,
4318
+ isSharedDomain
4319
+ };
4320
+ }
4321
+ return { isExternal: true, isDiFramework: false };
4322
+ }
4323
+ function extractImportStatements(content) {
4324
+ const statements = [];
4325
+ const lines = content.split(/\r?\n/);
4326
+ const regex = /(?:import\s+(?:type\s+)?(?:[\s\w*$,{}]+\s+from\s+)?|export\s+(?:type\s+)?(?:[\s\w*$,{}]+\s+from\s+)?|import\s*\(|require\s*\()\s*["']([^"']+)["']/g;
4327
+ let match;
4328
+ while ((match = regex.exec(content)) !== null) {
4329
+ const specifier = match[1];
4330
+ const charIndex = match.index;
4331
+ const lineNum = content.substring(0, charIndex).split("\n").length;
4332
+ const rawCode = lines[lineNum - 1]?.trim() || match[0].trim();
4333
+ statements.push({
4334
+ specifier,
4335
+ line: lineNum,
4336
+ rawCode
4337
+ });
4338
+ }
4339
+ return statements;
4340
+ }
4341
+ var FeatureDependencyGraph = class {
4342
+ edges = /* @__PURE__ */ new Map();
4343
+ addEdge(evidence) {
4344
+ const { fromFeature, toFeature } = evidence;
4345
+ if (fromFeature === toFeature) {
4346
+ return { createsCycle: false };
4347
+ }
4348
+ if (!this.edges.has(fromFeature)) {
4349
+ this.edges.set(fromFeature, /* @__PURE__ */ new Map());
4350
+ }
4351
+ this.edges.get(fromFeature).set(toFeature, evidence);
4352
+ const reverse = this.edges.get(toFeature)?.get(fromFeature);
4353
+ if (reverse) {
4354
+ return { createsCycle: true, directPartner: reverse, cycleChain: [fromFeature, toFeature, fromFeature] };
4355
+ }
4356
+ const cycle = this.findCycleFrom(fromFeature);
4357
+ if (cycle && cycle.length > 0) {
4358
+ return { createsCycle: true, cycleChain: cycle };
4359
+ }
4360
+ return { createsCycle: false };
4361
+ }
4362
+ getEdges() {
4363
+ const list = [];
4364
+ for (const [from, toMap] of this.edges.entries()) {
4365
+ for (const [to, ev] of toMap.entries()) {
4366
+ list.push({ from, to, evidence: ev });
4367
+ }
4368
+ }
4369
+ return list;
4370
+ }
4371
+ findDirectCycles() {
4372
+ const cycles = [];
4373
+ const checkedPairs = /* @__PURE__ */ new Set();
4374
+ for (const [from, toMap] of this.edges.entries()) {
4375
+ for (const [to, evAtoB] of toMap.entries()) {
4376
+ const pairKey = [from, to].sort().join("<->");
4377
+ if (checkedPairs.has(pairKey)) continue;
4378
+ const evBtoA = this.edges.get(to)?.get(from);
4379
+ if (evBtoA) {
4380
+ checkedPairs.add(pairKey);
4381
+ cycles.push({
4382
+ featureA: from,
4383
+ featureB: to,
4384
+ cycle: [from, to, from],
4385
+ evidenceAtoB: evAtoB,
4386
+ evidenceBtoA: evBtoA
4387
+ });
4388
+ }
4389
+ }
4390
+ }
4391
+ return cycles;
4392
+ }
4393
+ findCycleFrom(start) {
4394
+ const visited = /* @__PURE__ */ new Set();
4395
+ const inStack = /* @__PURE__ */ new Set();
4396
+ const parent = /* @__PURE__ */ new Map();
4397
+ const dfs = (curr) => {
4398
+ visited.add(curr);
4399
+ inStack.add(curr);
4400
+ const neighbors = this.edges.get(curr);
4401
+ if (neighbors) {
4402
+ for (const next of neighbors.keys()) {
4403
+ if (!visited.has(next)) {
4404
+ parent.set(next, curr);
4405
+ const cycle = dfs(next);
4406
+ if (cycle) return cycle;
4407
+ } else if (inStack.has(next)) {
4408
+ const cycle = [next];
4409
+ let p16 = curr;
4410
+ while (p16 !== next) {
4411
+ cycle.push(p16);
4412
+ p16 = parent.get(p16) || next;
4413
+ }
4414
+ cycle.push(next);
4415
+ cycle.reverse();
4416
+ return cycle;
4417
+ }
4418
+ }
4419
+ }
4420
+ inStack.delete(curr);
4421
+ return null;
4422
+ };
4423
+ return dfs(start);
4424
+ }
4425
+ };
4426
+ function discoverAllFeatures(projectRoot) {
4427
+ const featuresBase = resolveFeaturesDir(projectRoot);
4428
+ if (!fs9__default.default.existsSync(featuresBase)) return [];
4429
+ const entries = fs9__default.default.readdirSync(featuresBase, { withFileTypes: true });
4430
+ return entries.filter((e) => e.isDirectory() && !e.name.startsWith(".") && e.name !== "__tests__" && e.name !== "tests").map((e) => ({
4431
+ name: e.name,
4432
+ dir: path2__default.default.join(featuresBase, e.name)
4433
+ })).sort((a, b) => a.name.localeCompare(b.name));
4434
+ }
4435
+ function lintCodebase(options = {}) {
4436
+ const startTime = Date.now();
4437
+ const projectRoot = options.projectRoot || findProjectRoot(options.targetDir || process.cwd());
4438
+ const failFast = !options.complete;
4439
+ const features = discoverAllFeatures(projectRoot);
4440
+ const graph = new FeatureDependencyGraph();
4441
+ const allViolations = [];
4442
+ const results = [];
4443
+ const detectedCycles = [];
4444
+ const addViolation = (v) => {
4445
+ allViolations.push(v);
4446
+ const featureResult = results.find((r) => r.featureName === v.feature);
4447
+ if (featureResult) {
4448
+ featureResult.violations.push(v);
4449
+ featureResult.passed = false;
4450
+ }
4451
+ if (failFast) {
4452
+ const errorMsg = `Dependency rule violation detected in ${v.relativePath}:${v.line}:
4453
+ [${v.category}] ${v.advice}
4454
+ Code: ${v.code}`;
4455
+ throw new DependencyRuleError(errorMsg, [v], true);
4456
+ }
4457
+ };
4458
+ for (const feat of features) {
4459
+ results.push({
4460
+ featureName: feat.name,
4461
+ featureDir: feat.dir,
4462
+ scannedFilesCount: 0,
4463
+ passed: true,
4464
+ violations: [],
4465
+ layersChecked: ["domain", "useCases", "services", "infrastructure", "presentation"]
4466
+ });
4467
+ }
4468
+ for (const feat of features) {
4469
+ const featResult = results.find((r) => r.featureName === feat.name);
4470
+ const allFiles = scanDirFiles(feat.dir, projectRoot);
4471
+ featResult.scannedFilesCount = allFiles.length;
4472
+ for (const file of allFiles) {
4473
+ const relPath = path2__default.default.relative(projectRoot, file).replace(/\\/g, "/");
4474
+ const { layer } = classifyFile(file, projectRoot);
4475
+ if (!layer) continue;
4476
+ const content = fs9__default.default.readFileSync(file, "utf-8");
4477
+ const statements = extractImportStatements(content);
4478
+ if (layer === "domain") {
4479
+ const lines = content.split(/\r?\n/);
4480
+ for (let i = 0; i < lines.length; i++) {
4481
+ const lineText = lines[i].trim();
4482
+ if (lineText.includes("@MakeInjectable") || lineText.includes("public static deps =")) {
4483
+ addViolation({
4484
+ feature: feat.name,
4485
+ layer,
4486
+ file,
4487
+ relativePath: relPath,
4488
+ line: i + 1,
4489
+ category: "Domain Dependence Violation",
4490
+ code: lineText,
4491
+ ruleId: "D2_DI_DEPENDENCE",
4492
+ severity: "error",
4493
+ advice: "Domain layer must have zero DI dependence. Remove @MakeInjectable decorators and static deps declarations.",
4494
+ fixExample: {
4495
+ bad: lineText,
4496
+ good: "// Domain interfaces and value objects must remain plain TypeScript classes/interfaces."
4497
+ }
4498
+ });
4499
+ }
4500
+ }
4501
+ }
4502
+ for (const stmt of statements) {
4503
+ const target = classifyTarget(stmt.specifier, file, projectRoot);
4504
+ if (target.targetFeature && target.targetFeature !== feat.name) {
4505
+ const evidence = {
4506
+ fromFeature: feat.name,
4507
+ toFeature: target.targetFeature,
4508
+ file,
4509
+ relativePath: relPath,
4510
+ line: stmt.line,
4511
+ code: stmt.rawCode
4512
+ };
4513
+ const cycleResult = graph.addEdge(evidence);
4514
+ if (cycleResult.createsCycle) {
4515
+ const partner = cycleResult.directPartner;
4516
+ detectedCycles.push({
4517
+ featureA: feat.name,
4518
+ featureB: target.targetFeature,
4519
+ cycle: cycleResult.cycleChain,
4520
+ evidenceAtoB: evidence,
4521
+ evidenceBtoA: partner || evidence
4522
+ });
4523
+ addViolation({
4524
+ feature: feat.name,
4525
+ layer,
4526
+ file,
4527
+ relativePath: relPath,
4528
+ line: stmt.line,
4529
+ category: "Circular Feature Dependency Violation",
4530
+ code: stmt.rawCode,
4531
+ ruleId: "C1_CIRCULAR_FEATURE_DEPENDENCY",
4532
+ severity: "error",
4533
+ advice: `Circular feature dependency detected between '${feat.name}' and '${target.targetFeature}'. Dependency flow must be strictly one-way: for any two features, only one can know about the other exists. If '${feat.name}' needs to impose a side effect on '${target.targetFeature}' (or vice versa), it must do so via an event, never via a direct dependency.`,
4534
+ fixExample: {
4535
+ bad: stmt.rawCode,
4536
+ good: `// Emit a Domain/Application Event (e.g. publish '${feat.name}Changed') instead of depending on '${target.targetFeature}'.`
4537
+ }
4538
+ });
4539
+ }
4540
+ }
4541
+ if (layer === "domain") {
4542
+ if (target.targetLayer && ["useCases", "services", "infrastructure", "presentation"].includes(target.targetLayer)) {
4543
+ addViolation({
4544
+ feature: feat.name,
4545
+ layer,
4546
+ file,
4547
+ relativePath: relPath,
4548
+ line: stmt.line,
4549
+ category: "Domain Purity Violation",
4550
+ code: stmt.rawCode,
4551
+ ruleId: "D1_OUTER_IMPORT",
4552
+ severity: "error",
4553
+ advice: `Domain layer must not import from outer layers (${target.targetLayer}). Keep the domain core pure.`,
4554
+ fixExample: {
4555
+ bad: stmt.rawCode,
4556
+ good: "// Define interfaces, types, or value objects directly within the domain layer."
4557
+ }
4558
+ });
4559
+ }
4560
+ if (target.isDiFramework) {
4561
+ addViolation({
4562
+ feature: feat.name,
4563
+ layer,
4564
+ file,
4565
+ relativePath: relPath,
4566
+ line: stmt.line,
4567
+ category: "Domain Dependence Violation",
4568
+ code: stmt.rawCode,
4569
+ ruleId: "D2_DI_DEPENDENCE",
4570
+ severity: "error",
4571
+ advice: "Domain layer must have zero DI dependence. Domain interfaces and value objects are plain classes/types.",
4572
+ fixExample: {
4573
+ bad: stmt.rawCode,
4574
+ good: "// Remove @solid-stack/di import. Domain entities are pure TypeScript."
4575
+ }
4576
+ });
4577
+ }
4578
+ if (target.targetSharedModule && !target.isSharedDomain) {
4579
+ addViolation({
4580
+ feature: feat.name,
4581
+ layer,
4582
+ file,
4583
+ relativePath: relPath,
4584
+ line: stmt.line,
4585
+ category: "Domain Purity Violation",
4586
+ code: stmt.rawCode,
4587
+ ruleId: "D3_SHARED_NON_DOMAIN_IMPORT",
4588
+ severity: "error",
4589
+ advice: "Domain layer can only import pure value objects from shared/<module>/domain/*. Ports, infrastructure, and root classes must not be imported.",
4590
+ fixExample: {
4591
+ bad: stmt.rawCode,
4592
+ good: `import { ... } from "@/shared/${target.targetSharedModule}/domain/...";`
4593
+ }
4594
+ });
4595
+ }
4596
+ if (target.isExternal && !target.isDiFramework) {
4597
+ addViolation({
4598
+ feature: feat.name,
4599
+ layer,
4600
+ file,
4601
+ relativePath: relPath,
4602
+ line: stmt.line,
4603
+ category: "Domain Purity Violation",
4604
+ code: stmt.rawCode,
4605
+ ruleId: "D4_EXTERNAL_LIBRARY",
4606
+ severity: "error",
4607
+ advice: `Domain layer must be pure and must not depend on external runtime libraries ('${stmt.specifier}').`,
4608
+ fixExample: {
4609
+ bad: stmt.rawCode,
4610
+ good: "// Model pure business interfaces without external libraries."
4611
+ }
4612
+ });
4613
+ }
4614
+ } else if (layer === "useCases") {
4615
+ if (target.targetLayer === "useCases" && target.targetFeature === feat.name) {
4616
+ addViolation({
4617
+ feature: feat.name,
4618
+ layer,
4619
+ file,
4620
+ relativePath: relPath,
4621
+ line: stmt.line,
4622
+ category: "Use Case Intra-Feature Violation",
4623
+ code: stmt.rawCode,
4624
+ ruleId: "U1_INTRA_USE_CASE",
4625
+ severity: "error",
4626
+ advice: `Use cases cannot depend on other use cases of the same feature ('${feat.name}'). Extract shared business logic to a domain repository or domain service.`,
4627
+ fixExample: {
4628
+ bad: stmt.rawCode,
4629
+ good: "// Inject a domain interface or domain service instead of another use case."
4630
+ }
4631
+ });
4632
+ }
4633
+ if (target.targetLayer === "useCases" && target.targetFeature && target.targetFeature !== feat.name) {
4634
+ addViolation({
4635
+ feature: feat.name,
4636
+ layer,
4637
+ file,
4638
+ relativePath: relPath,
4639
+ line: stmt.line,
4640
+ category: "Use Case Cross-Feature Use Case Violation",
4641
+ code: stmt.rawCode,
4642
+ ruleId: "U2_CROSS_FEATURE_USE_CASE",
4643
+ severity: "error",
4644
+ advice: `Use cases cannot depend directly on use cases of foreign feature '${target.targetFeature}'. Treat features as separate microservices: define an interface in '${feat.name}/domain/' specifying what is needed, and implement it in '${feat.name}/infrastructure/'.`,
4645
+ fixExample: {
4646
+ bad: stmt.rawCode,
4647
+ good: `// Define an interface in ${feat.name}/domain/ and implement it in ${feat.name}/infrastructure/ using '${target.targetFileName}'.`
4648
+ }
4649
+ });
4650
+ }
4651
+ if (target.targetLayer === "infrastructure") {
4652
+ addViolation({
4653
+ feature: feat.name,
4654
+ layer,
4655
+ file,
4656
+ relativePath: relPath,
4657
+ line: stmt.line,
4658
+ category: "Use Case Layer Violation",
4659
+ code: stmt.rawCode,
4660
+ ruleId: "U3_DIRECT_INFRASTRUCTURE",
4661
+ severity: "error",
4662
+ advice: "Use cases cannot import concrete infrastructure directly. Depend on Domain Ports of the same feature via DI.",
4663
+ fixExample: {
4664
+ bad: stmt.rawCode,
4665
+ good: "// Depend on the domain interface port declared in static deps."
4666
+ }
4667
+ });
4668
+ }
4669
+ if (target.targetLayer === "domain" && target.targetFeature && target.targetFeature !== feat.name && target.isTargetPort) {
4670
+ addViolation({
4671
+ feature: feat.name,
4672
+ layer,
4673
+ file,
4674
+ relativePath: relPath,
4675
+ line: stmt.line,
4676
+ category: "Use Case Cross-Feature Port Violation",
4677
+ code: stmt.rawCode,
4678
+ ruleId: "U4_CROSS_FEATURE_PORT",
4679
+ severity: "error",
4680
+ advice: `Use cases cannot depend on domain interfaces/ports of foreign feature '${target.targetFeature}'. Define an interface in '${feat.name}/domain/' (consumer-driven port) and implement it in '${feat.name}/infrastructure/'.`,
4681
+ fixExample: {
4682
+ bad: stmt.rawCode,
4683
+ good: `// Define a local interface in ${feat.name}/domain/ and implement it in ${feat.name}/infrastructure/.`
4684
+ }
4685
+ });
4686
+ }
4687
+ if (target.targetLayer === "services" && target.targetFeature && target.targetFeature !== feat.name) {
4688
+ addViolation({
4689
+ feature: feat.name,
4690
+ layer,
4691
+ file,
4692
+ relativePath: relPath,
4693
+ line: stmt.line,
4694
+ category: "Use Case Layer Violation",
4695
+ code: stmt.rawCode,
4696
+ ruleId: "U5_CROSS_FEATURE_SERVICE",
4697
+ severity: "error",
4698
+ advice: `Use cases cannot depend on services of foreign feature '${target.targetFeature}'.`,
4699
+ fixExample: {
4700
+ bad: stmt.rawCode,
4701
+ good: `// Define an interface in ${feat.name}/domain/ and implement it in ${feat.name}/infrastructure/.`
4702
+ }
4703
+ });
4704
+ }
4705
+ if (target.targetSharedModule && (target.isSharedPorts || target.isSharedInfra)) {
4706
+ addViolation({
4707
+ feature: feat.name,
4708
+ layer,
4709
+ file,
4710
+ relativePath: relPath,
4711
+ line: stmt.line,
4712
+ category: "Shared Module Root Class Violation",
4713
+ code: stmt.rawCode,
4714
+ ruleId: "U6_SHARED_NON_ROOT",
4715
+ severity: "error",
4716
+ advice: `Use cases can only depend on root classes of shared modules. Never import from shared ports or infrastructure directly.`,
4717
+ fixExample: {
4718
+ bad: stmt.rawCode,
4719
+ good: `import { ... } from "@/shared/${target.targetSharedModule}/<RootClass>.js";`
4720
+ }
4721
+ });
4722
+ }
4723
+ } else if (layer === "services") {
4724
+ if (target.targetLayer === "useCases") {
4725
+ addViolation({
4726
+ feature: feat.name,
4727
+ layer,
4728
+ file,
4729
+ relativePath: relPath,
4730
+ line: stmt.line,
4731
+ category: "Service Intra-Feature Violation",
4732
+ code: stmt.rawCode,
4733
+ ruleId: "S1_USE_CASE_DEPENDENCY",
4734
+ severity: "error",
4735
+ advice: "Services cannot depend on use cases of any feature.",
4736
+ fixExample: {
4737
+ bad: stmt.rawCode,
4738
+ good: "// Inject domain repository ports directly instead of use cases."
4739
+ }
4740
+ });
4741
+ }
4742
+ if (target.targetLayer === "domain" && target.targetFeature && target.targetFeature !== feat.name && target.isTargetPort) {
4743
+ addViolation({
4744
+ feature: feat.name,
4745
+ layer,
4746
+ file,
4747
+ relativePath: relPath,
4748
+ line: stmt.line,
4749
+ category: "Service Cross-Feature Port Violation",
4750
+ code: stmt.rawCode,
4751
+ ruleId: "S2_CROSS_FEATURE_PORT",
4752
+ severity: "error",
4753
+ advice: `Services cannot depend on domain ports of foreign feature '${target.targetFeature}'.`,
4754
+ fixExample: {
4755
+ bad: stmt.rawCode,
4756
+ good: `// Define an interface in ${feat.name}/domain/ and implement it in ${feat.name}/infrastructure/.`
4757
+ }
4758
+ });
4759
+ }
4760
+ if (target.targetLayer === "infrastructure") {
4761
+ addViolation({
4762
+ feature: feat.name,
4763
+ layer,
4764
+ file,
4765
+ relativePath: relPath,
4766
+ line: stmt.line,
4767
+ category: "Service Layer Violation",
4768
+ code: stmt.rawCode,
4769
+ ruleId: "S3_DIRECT_INFRASTRUCTURE",
4770
+ severity: "error",
4771
+ advice: "Services cannot import concrete infrastructure directly. Depend on Domain Ports via DI.",
4772
+ fixExample: {
4773
+ bad: stmt.rawCode,
4774
+ good: "// Depend on the domain interface port declared in static deps."
4775
+ }
4776
+ });
4777
+ }
4778
+ if (target.targetSharedModule && (target.isSharedPorts || target.isSharedInfra)) {
4779
+ addViolation({
4780
+ feature: feat.name,
4781
+ layer,
4782
+ file,
4783
+ relativePath: relPath,
4784
+ line: stmt.line,
4785
+ category: "Shared Module Root Class Violation",
4786
+ code: stmt.rawCode,
4787
+ ruleId: "S4_SHARED_NON_ROOT",
4788
+ severity: "error",
4789
+ advice: "Services can only depend on root classes of shared modules. Never import from shared ports or infrastructure directly.",
4790
+ fixExample: {
4791
+ bad: stmt.rawCode,
4792
+ good: `import { ... } from "@/shared/${target.targetSharedModule}/<RootClass>.js";`
4793
+ }
4794
+ });
4795
+ }
4796
+ } else if (layer === "infrastructure") {
4797
+ if (target.targetLayer === "useCases" && target.targetFeature === feat.name) {
4798
+ addViolation({
4799
+ feature: feat.name,
4800
+ layer,
4801
+ file,
4802
+ relativePath: relPath,
4803
+ line: stmt.line,
4804
+ category: "Adapter Layer Violation",
4805
+ code: stmt.rawCode,
4806
+ ruleId: "I1_INTRA_USE_CASE",
4807
+ severity: "error",
4808
+ advice: `Infrastructure adapters cannot depend on use cases of the same feature ('${feat.name}'). Adapters implement domain ports.`,
4809
+ fixExample: {
4810
+ bad: stmt.rawCode,
4811
+ good: "// Adapters implement domain ports and should not invoke local application use cases."
4812
+ }
4813
+ });
4814
+ }
4815
+ if (target.targetSharedModule && (target.isSharedPorts || target.isSharedInfra)) {
4816
+ addViolation({
4817
+ feature: feat.name,
4818
+ layer,
4819
+ file,
4820
+ relativePath: relPath,
4821
+ line: stmt.line,
4822
+ category: "Shared Module Root Class Violation",
4823
+ code: stmt.rawCode,
4824
+ ruleId: "I2_SHARED_NON_ROOT",
4825
+ severity: "error",
4826
+ advice: "Infrastructure adapters can only depend on root classes of shared modules. Never import from shared ports or infrastructure directly.",
4827
+ fixExample: {
4828
+ bad: stmt.rawCode,
4829
+ good: `import { ... } from "@/shared/${target.targetSharedModule}/<RootClass>.js";`
4830
+ }
4831
+ });
4832
+ }
4833
+ } else if (layer === "presentation") {
4834
+ if (target.targetLayer === "infrastructure") {
4835
+ addViolation({
4836
+ feature: feat.name,
4837
+ layer,
4838
+ file,
4839
+ relativePath: relPath,
4840
+ line: stmt.line,
4841
+ category: "Presentation Layer Violation",
4842
+ code: stmt.rawCode,
4843
+ ruleId: "P1_DIRECT_INFRASTRUCTURE",
4844
+ severity: "error",
4845
+ advice: "Presentation handlers must not import infrastructure directly. Inject Use Cases via DI.",
4846
+ fixExample: {
4847
+ bad: stmt.rawCode,
4848
+ good: "// Inject the corresponding Use Case via static deps and invoke its execute() method."
4849
+ }
4850
+ });
4851
+ }
4852
+ if (target.targetLayer === "domain" && (target.isTargetRepo || target.isTargetPort)) {
4853
+ addViolation({
4854
+ feature: feat.name,
4855
+ layer,
4856
+ file,
4857
+ relativePath: relPath,
4858
+ line: stmt.line,
4859
+ category: "Presentation Layer Violation",
4860
+ code: stmt.rawCode,
4861
+ ruleId: "P2_DIRECT_REPOSITORY",
4862
+ severity: "error",
4863
+ advice: "Presentation handlers must not depend on domain repositories or ports directly. Inject Use Cases via DI.",
4864
+ fixExample: {
4865
+ bad: stmt.rawCode,
4866
+ good: "// Presentation layer must only orchestrate Use Cases."
4867
+ }
4868
+ });
4869
+ }
4870
+ if (target.targetSharedModule && (target.isSharedPorts || target.isSharedInfra)) {
4871
+ addViolation({
4872
+ feature: feat.name,
4873
+ layer,
4874
+ file,
4875
+ relativePath: relPath,
4876
+ line: stmt.line,
4877
+ category: "Shared Module Root Class Violation",
4878
+ code: stmt.rawCode,
4879
+ ruleId: "P3_SHARED_NON_ROOT",
4880
+ severity: "error",
4881
+ advice: "Presentation handlers can only depend on root classes of shared modules. Never import from shared ports or infrastructure directly.",
4882
+ fixExample: {
4883
+ bad: stmt.rawCode,
4884
+ good: `import { ... } from "@/shared/${target.targetSharedModule}/<RootClass>.js";`
4885
+ }
4886
+ });
4887
+ }
4888
+ }
4889
+ }
4890
+ }
4891
+ }
4892
+ const directCycles = graph.findDirectCycles();
4893
+ for (const c of directCycles) {
4894
+ const existing = detectedCycles.find(
4895
+ (dc) => dc.featureA === c.featureA && dc.featureB === c.featureB || dc.featureA === c.featureB && dc.featureB === c.featureA
4896
+ );
4897
+ if (!existing) {
4898
+ detectedCycles.push(c);
4899
+ addViolation({
4900
+ feature: c.featureA,
4901
+ file: c.evidenceAtoB.file,
4902
+ relativePath: c.evidenceAtoB.relativePath,
4903
+ line: c.evidenceAtoB.line,
4904
+ category: "Circular Feature Dependency Violation",
4905
+ code: c.evidenceAtoB.code,
4906
+ ruleId: "C1_CIRCULAR_FEATURE_DEPENDENCY",
4907
+ severity: "error",
4908
+ advice: `Circular feature dependency detected between '${c.featureA}' and '${c.featureB}'. Dependency flow must be strictly one-way: for any two features, only one can know about the other exists. If the unaware feature needs to impose a side effect on the other, it must do so via an event, never via a direct dependency.`
4909
+ });
4910
+ }
4911
+ }
4912
+ const durationMs = Date.now() - startTime;
4913
+ const cleanFeatures = results.filter((r) => r.passed).length;
4914
+ const violatedFeatures = results.filter((r) => !r.passed).length;
4915
+ const summary = {
4916
+ totalFeatures: results.length,
4917
+ cleanFeatures,
4918
+ violatedFeatures,
4919
+ totalViolations: allViolations.length,
4920
+ durationMs,
4921
+ results,
4922
+ allViolations,
4923
+ circularDependencies: detectedCycles
4924
+ };
4925
+ if (allViolations.length > 0 && options.throwOnError !== false) {
4926
+ const errorHeader = `Dependency rule audit failed with ${allViolations.length} violation(s) across ${violatedFeatures} feature(s):`;
4927
+ const compiledDetails = allViolations.map(
4928
+ (v, i) => `${i + 1}. [${v.category}] ${v.relativePath}:${v.line}
4929
+ Rule: ${v.ruleId}
4930
+ Code: ${v.code}
4931
+ Advice: ${v.advice}`
4932
+ ).join("\n\n");
4933
+ throw new DependencyRuleError(`${errorHeader}
4934
+
4935
+ ${compiledDetails}
4936
+ `, allViolations, false);
4937
+ }
4938
+ return summary;
4939
+ }
4940
+
4941
+ // src/commands/lint.ts
4942
+ function formatViolation(v) {
4943
+ const lines = [];
4944
+ lines.push(pc14__default.default.underline(pc14__default.default.cyan(v.relativePath)) + pc14__default.default.dim(":") + pc14__default.default.yellow(String(v.line)));
4945
+ const gutter = `${String(v.line).padStart(4, " ")} | `;
4946
+ lines.push(pc14__default.default.dim(gutter) + v.code);
4947
+ const categoryShort = v.category.replace(" Violation", "");
4948
+ lines.push(
4949
+ " " + pc14__default.default.red(pc14__default.default.bold("\u2716")) + " " + pc14__default.default.red(`[${categoryShort}]`) + " " + v.advice
4950
+ );
4951
+ if (v.fixExample?.good) {
4952
+ lines.push(" " + pc14__default.default.dim("\u2192") + " " + pc14__default.default.dim(v.fixExample.good));
4953
+ }
4954
+ return lines.join("\n");
4955
+ }
4956
+ async function handleLint(flags = {}) {
4957
+ const complete = Boolean(flags.complete);
4958
+ const quiet = Boolean(flags.quiet);
4959
+ const options = {
4960
+ complete,
4961
+ quiet,
4962
+ targetDir: flags.targetDir || flags.target,
4963
+ projectRoot: flags.projectRoot,
4964
+ fixHint: flags.fixHint !== false,
4965
+ throwOnError: false
4966
+ };
4967
+ try {
4968
+ const summary = lintCodebase(options);
4969
+ if (summary.totalViolations > 0) {
4970
+ if (!quiet) {
4971
+ console.log("");
4972
+ for (const v of summary.allViolations) {
4973
+ console.log(formatViolation(v));
4974
+ console.log("");
4975
+ }
4976
+ console.log(
4977
+ pc14__default.default.red(
4978
+ `\u2716 Dependency rules check failed with ${summary.totalViolations} error${summary.totalViolations > 1 ? "s" : ""} across ${summary.violatedFeatures} feature${summary.violatedFeatures > 1 ? "s" : ""} (${summary.totalFeatures} features scanned).`
4979
+ )
4980
+ );
4981
+ console.log("");
4982
+ }
4983
+ const errorHeader = `Dependency rule audit failed with ${summary.totalViolations} violation(s) across ${summary.violatedFeatures} feature(s):`;
4984
+ const compiledDetails = summary.allViolations.map(
4985
+ (v, i) => `${i + 1}. [${v.category}] ${v.relativePath}:${v.line}
4986
+ Code: ${v.code}
4987
+ Advice: ${v.advice}`
4988
+ ).join("\n\n");
4989
+ throw new DependencyRuleError(`${errorHeader}
4990
+
4991
+ ${compiledDetails}
4992
+ `, summary.allViolations, false);
4993
+ }
4994
+ if (!quiet) {
4995
+ console.log(
4996
+ pc14__default.default.green(
4997
+ `\u2714 Dependency rules verified across ${summary.totalFeatures} feature${summary.totalFeatures === 1 ? "" : "s"}.`
4998
+ )
4999
+ );
5000
+ }
5001
+ return summary;
5002
+ } catch (err) {
5003
+ if (err instanceof DependencyRuleError && err.isFailFast) {
5004
+ if (!quiet) {
5005
+ console.log("");
5006
+ const v = err.violations[0];
5007
+ if (v) {
5008
+ console.log(formatViolation(v));
5009
+ console.log("");
5010
+ }
5011
+ console.log(pc14__default.default.red(`\u2716 Dependency rules check failed (1 error).`));
5012
+ console.log("");
5013
+ }
5014
+ }
5015
+ throw err;
5016
+ }
5017
+ }
4192
5018
 
4193
5019
  // src/cli.ts
4194
5020
  function createCli() {
@@ -4262,14 +5088,21 @@ function createCli() {
4262
5088
  value: "import",
4263
5089
  label: "Import from registry",
4264
5090
  hint: "Download and link pre-built shared modules or features from the registry"
5091
+ },
5092
+ {
5093
+ value: "lint",
5094
+ label: "Lint dependency rules",
5095
+ hint: "Scan codebase and verify Clean Architecture dependency rules"
4265
5096
  }
4266
5097
  ]
4267
5098
  })
4268
5099
  );
4269
5100
  if (choice === "create") {
4270
5101
  await handleCreate(void 0, void 0, flags);
4271
- } else {
5102
+ } else if (choice === "import") {
4272
5103
  await handleImport(void 0, void 0, flags);
5104
+ } else if (choice === "lint") {
5105
+ await handleLint(flags);
4273
5106
  }
4274
5107
  } catch (err) {
4275
5108
  handleCliError(err);
@@ -4295,6 +5128,28 @@ function createCli() {
4295
5128
  handleCliError(err);
4296
5129
  }
4297
5130
  });
5131
+ cli.command(
5132
+ "lint [target]",
5133
+ "Scan codebase and verify Clean Architecture dependency rules"
5134
+ ).option(
5135
+ "-c, --complete",
5136
+ "Scan entire codebase without failing fast, compiling all errors at the end"
5137
+ ).option("-q, --quiet", "Suppress non-error output").example("mason lint").example("mason lint --complete").example("mason lint ./src").action(async (target, flags = {}) => {
5138
+ try {
5139
+ await handleLint({
5140
+ ...flags,
5141
+ targetDir: target || flags.target || flags.dest
5142
+ });
5143
+ } catch (err) {
5144
+ if (err instanceof DependencyRuleError) {
5145
+ if (process.env.VITEST) {
5146
+ throw err;
5147
+ }
5148
+ process.exit(1);
5149
+ }
5150
+ handleCliError(err);
5151
+ }
5152
+ });
4298
5153
  const createSubtypes = [
4299
5154
  "feature",
4300
5155
  "shared",
@@ -4327,6 +5182,9 @@ function handleCliError(err) {
4327
5182
  }
4328
5183
  const message = err instanceof Error ? err.message : String(err);
4329
5184
  p14__namespace.log.error(pc14__default.default.red(`Error: ${message}`));
5185
+ if (process.env.VITEST) {
5186
+ throw err;
5187
+ }
4330
5188
  process.exit(1);
4331
5189
  }
4332
5190
  async function runCli(argv = process.argv) {