Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System.Xml.Linq;
using SimpleModule.Cli.Infrastructure;

namespace SimpleModule.Cli.Commands.Doctor.Checks;

public sealed class ContractsIsolationCheck : IDoctorCheck
{
public IEnumerable<CheckResult> Run(SolutionContext solution)
{
foreach (var module in solution.ExistingModules)
{
var contractsCsproj = Path.Combine(
solution.GetModuleContractsPath(module),
$"{module}.Contracts.csproj"
);

if (!File.Exists(contractsCsproj))
{
yield return new CheckResult(
$"{module}.Contracts isolation",
CheckStatus.Warning,
$"{module}.Contracts.csproj not found"
);
continue;
}

var doc = XDocument.Load(contractsCsproj);
var nonCoreRefs = doc.Root!
.Descendants("ProjectReference")
.Select(pr => pr.Attribute("Include")?.Value ?? "")
.Where(r => !r.Contains("Core", StringComparison.OrdinalIgnoreCase)
&& !r.Contains("Contracts", StringComparison.OrdinalIgnoreCase))
.ToList();

yield return nonCoreRefs.Count == 0
? new CheckResult($"{module}.Contracts isolation", CheckStatus.Pass, "references Core only")
: new CheckResult($"{module}.Contracts isolation", CheckStatus.Fail,
$"references non-Core projects: {string.Join(", ", nonCoreRefs.Select(Path.GetFileNameWithoutExtension))}");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,33 +40,6 @@ public IEnumerable<CheckResult> Run(SolutionContext solution)
$"{module}.csproj not found"
);
}

var contractsCsproj = Path.Combine(
solution.GetModuleContractsPath(module),
$"{module}.Contracts.csproj"
);
if (File.Exists(contractsCsproj))
{
var doc = XDocument.Load(contractsCsproj);
var refs = doc.Root!.Descendants("ProjectReference")
.Select(pr => pr.Attribute("Include")?.Value ?? "")
.ToList();

var onlyRefsCore = refs.All(r =>
r.Contains("Core", StringComparison.OrdinalIgnoreCase)
);
yield return onlyRefsCore
? new CheckResult(
$"{module}.Contracts refs",
CheckStatus.Pass,
"references Core only"
)
: new CheckResult(
$"{module}.Contracts refs",
CheckStatus.Warning,
"contracts project references more than just Core"
);
}
}

// Generator check
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using SimpleModule.Cli.Infrastructure;

namespace SimpleModule.Cli.Commands.Doctor.Checks;

public sealed class ModuleAttributeCheck : IDoctorCheck
{
public IEnumerable<CheckResult> Run(SolutionContext solution)
{
foreach (var module in solution.ExistingModules)
{
var moduleClassPath = Path.Combine(solution.GetModuleProjectPath(module), $"{module}Module.cs");

if (!File.Exists(moduleClassPath))
{
yield return new CheckResult($"{module} [Module] attribute", CheckStatus.Warning,
$"{module}Module.cs not found — skipping attribute check");
continue;
}

var content = File.ReadAllText(moduleClassPath);
var hasAttribute = content.Contains("[Module(", StringComparison.Ordinal);
var hasRoutePrefix = content.Contains("RoutePrefix", StringComparison.Ordinal);

yield return (hasAttribute && hasRoutePrefix)
? new CheckResult($"{module} [Module] attribute", CheckStatus.Pass, "[Module] attribute with RoutePrefix present")
: new CheckResult($"{module} [Module] attribute", CheckStatus.Fail,
hasAttribute ? "[Module] attribute present but RoutePrefix is missing"
: $"{module}Module.cs missing [Module] attribute");
}
}
}
50 changes: 50 additions & 0 deletions cli/SimpleModule.Cli/Commands/Doctor/Checks/NpmWorkspaceCheck.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using System.Text.RegularExpressions;
using SimpleModule.Cli.Infrastructure;

namespace SimpleModule.Cli.Commands.Doctor.Checks;

public sealed partial class NpmWorkspaceCheck : IDoctorCheck
{
[GeneratedRegex(@"""workspaces""\s*:\s*\[([^\]]*)\]", RegexOptions.Singleline)]
private static partial Regex WorkspacesPattern();

public IEnumerable<CheckResult> Run(SolutionContext solution)
{
var rootPackageJson = Path.Combine(solution.RootPath, "package.json");

if (!File.Exists(rootPackageJson))
{
foreach (var module in solution.ExistingModules)
yield return new CheckResult($"NpmWorkspace -> {module}", CheckStatus.Warning,
"root package.json not found — cannot verify workspaces");
yield break;
}

var content = File.ReadAllText(rootPackageJson);
var match = WorkspacesPattern().Match(content);
var workspaceGlobs = match.Success
? match.Groups[1].Value
.Split(',')
.Select(g => g.Trim().Trim('"'))
.Where(g => !string.IsNullOrWhiteSpace(g))
.ToList()
: [];

foreach (var module in solution.ExistingModules)
{
var modulePath = $"src/modules/{module}/src/{module}";
var isCovered = workspaceGlobs.Any(glob => GlobCoversPath(glob, modulePath));

yield return isCovered
? new CheckResult($"NpmWorkspace -> {module}", CheckStatus.Pass, "covered by workspace glob")
: new CheckResult($"NpmWorkspace -> {module}", CheckStatus.Fail,
$"'{modulePath}' not covered by any workspace glob in root package.json");
}
}

private static bool GlobCoversPath(string glob, string path)
{
var pattern = "^" + Regex.Escape(glob).Replace(@"\*", "[^/]+", StringComparison.Ordinal) + "$";
return Regex.IsMatch(path, pattern, RegexOptions.IgnoreCase);
}
}
46 changes: 46 additions & 0 deletions cli/SimpleModule.Cli/Commands/Doctor/Checks/PackageJsonCheck.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using SimpleModule.Cli.Infrastructure;

namespace SimpleModule.Cli.Commands.Doctor.Checks;

public sealed class PackageJsonCheck : IDoctorCheck
{
private static readonly string[] RequiredPeerDeps = ["react", "@inertiajs/react"];

public IEnumerable<CheckResult> Run(SolutionContext solution)
{
foreach (var module in solution.ExistingModules)
{
var packageJsonPath = Path.Combine(solution.GetModuleProjectPath(module), "package.json");

if (!File.Exists(packageJsonPath))
{
yield return new CheckResult($"{module} package.json", CheckStatus.Warning, "package.json not found");
continue;
}

var content = File.ReadAllText(packageJsonPath);
var peerDepsStart = content.IndexOf("\"peerDependencies\"", StringComparison.Ordinal);

var missingFromPeerDeps = RequiredPeerDeps
.Where(dep =>
{
if (peerDepsStart < 0) return true;
var searchFrom = peerDepsStart;
var idx = content.IndexOf($"\"{dep}\"", searchFrom, StringComparison.Ordinal);
return idx < 0;
})
.ToList();

if (missingFromPeerDeps.Count == 0)
{
yield return new CheckResult($"{module} package.json", CheckStatus.Pass,
"React and @inertiajs/react declared as peerDependencies");
}
else
{
yield return new CheckResult($"{module} package.json", CheckStatus.Warning,
$"missing from peerDependencies: {string.Join(", ", missingFromPeerDeps)}");
}
}
}
}
51 changes: 51 additions & 0 deletions cli/SimpleModule.Cli/Commands/Doctor/Checks/PagesRegistryCheck.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using System.Text.RegularExpressions;
using SimpleModule.Cli.Infrastructure;

namespace SimpleModule.Cli.Commands.Doctor.Checks;

public sealed partial class PagesRegistryCheck : IDoctorCheck
{
[GeneratedRegex(@"Inertia\.Render\s*\(\s*""([^""]+)""")]
private static partial Regex InertiaRenderPattern();

[GeneratedRegex(@"""([^""]+)""\s*:\s*(?:\(\s*\)|(?:async\s*)?\(\s*\)\s*=>|import)")]
private static partial Regex PagesKeyPattern();

public IEnumerable<CheckResult> Run(SolutionContext solution)
{
foreach (var module in solution.ExistingModules)
{
var moduleDir = solution.GetModuleProjectPath(module);
if (!Directory.Exists(moduleDir))
continue;

var csFiles = Directory.GetFiles(moduleDir, "*.cs", SearchOption.AllDirectories);
var inertiaComponents = csFiles
.SelectMany(f => InertiaRenderPattern().Matches(File.ReadAllText(f)))
.Select(m => m.Groups[1].Value)
.Distinct()
.ToList();

if (inertiaComponents.Count == 0)
continue;

var indexPath = solution.GetModulePagesIndexPath(module);
var registeredKeys = new HashSet<string>(StringComparer.Ordinal);

if (File.Exists(indexPath))
{
var indexContent = File.ReadAllText(indexPath);
foreach (Match m in PagesKeyPattern().Matches(indexContent))
registeredKeys.Add(m.Groups[1].Value);
}

foreach (var component in inertiaComponents)
{
yield return registeredKeys.Contains(component)
? new CheckResult($"Pages -> {component}", CheckStatus.Pass, "registered in Pages/index.ts")
: new CheckResult($"Pages -> {component}", CheckStatus.Fail,
$"'{component}' used in Inertia.Render but missing from Pages/index.ts");
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using SimpleModule.Cli.Infrastructure;

namespace SimpleModule.Cli.Commands.Doctor.Checks;

public sealed class ViewEndpointNamingCheck : IDoctorCheck
{
public IEnumerable<CheckResult> Run(SolutionContext solution)
{
foreach (var module in solution.ExistingModules)
{
var endpointsDir = Path.Combine(solution.GetModuleProjectPath(module), "Endpoints", module);
if (!Directory.Exists(endpointsDir))
continue;

foreach (var file in Directory.GetFiles(endpointsDir, "*.cs"))
{
var fileName = Path.GetFileNameWithoutExtension(file);
if (fileName.EndsWith("Validator", StringComparison.Ordinal))
continue;

yield return fileName.EndsWith("Endpoint", StringComparison.Ordinal)
? new CheckResult($"{module}/{fileName}", CheckStatus.Pass, "follows Endpoint naming convention")
: new CheckResult($"{module}/{fileName}", CheckStatus.Warning,
$"'{fileName}' does not end with 'Endpoint' — rename to '{fileName}Endpoint'");
}
}
}
}
42 changes: 42 additions & 0 deletions cli/SimpleModule.Cli/Commands/Doctor/Checks/ViteConfigCheck.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using SimpleModule.Cli.Infrastructure;

namespace SimpleModule.Cli.Commands.Doctor.Checks;

public sealed class ViteConfigCheck : IDoctorCheck
{
private static readonly string[] RequiredExternals = ["react", "react-dom", "@inertiajs/react"];

public IEnumerable<CheckResult> Run(SolutionContext solution)
{
foreach (var module in solution.ExistingModules)
{
var viteConfigPath = Path.Combine(solution.GetModuleProjectPath(module), "vite.config.ts");

if (!File.Exists(viteConfigPath))
{
yield return new CheckResult($"{module} vite.config.ts", CheckStatus.Warning,
"vite.config.ts not found — module won't build as a library");
continue;
}

var content = File.ReadAllText(viteConfigPath);
var hasLibMode = content.Contains("lib:", StringComparison.Ordinal);
var missingExternals = RequiredExternals
.Where(e => !content.Contains(e, StringComparison.Ordinal))
.ToList();

if (hasLibMode && missingExternals.Count == 0)
{
yield return new CheckResult($"{module} vite.config.ts", CheckStatus.Pass,
"library mode configured with correct externals");
}
else
{
var issues = new List<string>();
if (!hasLibMode) issues.Add("missing lib mode");
if (missingExternals.Count > 0) issues.Add($"missing externals: {string.Join(", ", missingExternals)}");
yield return new CheckResult($"{module} vite.config.ts", CheckStatus.Warning, string.Join("; ", issues));
}
}
}
}
42 changes: 41 additions & 1 deletion cli/SimpleModule.Cli/Commands/Doctor/DoctorCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,14 @@ public override int Execute(CommandContext context, DoctorSettings settings)
new ProjectReferenceCheck(),
new SlnxEntriesCheck(),
new CsprojConventionCheck(),
new ContractsIsolationCheck(),
new ModulePatternCheck(),
new ModuleAttributeCheck(),
new ViewEndpointNamingCheck(),
new PagesRegistryCheck(),
new ViteConfigCheck(),
new PackageJsonCheck(),
new NpmWorkspaceCheck(),
];

var results = new List<CheckResult>();
Expand Down Expand Up @@ -80,7 +87,7 @@ public override int Execute(CommandContext context, DoctorSettings settings)
if (!settings.Fix)
{
AnsiConsole.MarkupLine(
"[dim]Run with --fix to auto-fix missing slnx entries and project references.[/]"
"[dim]Run with --fix to auto-fix missing slnx entries, project references, Pages registry entries, and npm workspace globs.[/]"
);
}

Expand Down Expand Up @@ -127,6 +134,39 @@ private static void AutoFix(SolutionContext solution, List<CheckResult> results)
$"[green] Fixed: added {moduleName} reference to API csproj[/]"
);
}

// Fix missing Pages/index.ts entries
if (result.Name.StartsWith("Pages -> ", StringComparison.Ordinal))
{
var componentKey = result.Name["Pages -> ".Length..];
var slashIndex = componentKey.IndexOf('/', StringComparison.Ordinal);
var moduleName = slashIndex >= 0
? componentKey[..slashIndex]
: componentKey;
var featureName = slashIndex >= 0
? componentKey[(slashIndex + 1)..]
: componentKey;
var indexPath = solution.GetModulePagesIndexPath(moduleName);
PagesRegistryFixer.AddEntry(indexPath, componentKey, $"../Views/{featureName}");
AnsiConsole.MarkupLine($"[green] Fixed: added '{componentKey}' to Pages/index.ts[/]");
}

// Fix missing npm workspace entries
if (result.Name.StartsWith("NpmWorkspace -> ", StringComparison.Ordinal))
{
var moduleName = result.Name["NpmWorkspace -> ".Length..];
var rootPackageJson = Path.Combine(solution.RootPath, "package.json");
if (File.Exists(rootPackageJson))
{
NpmWorkspaceFixer.AddWorkspaceGlob(
rootPackageJson,
$"src/modules/{moduleName}/src/*"
);
AnsiConsole.MarkupLine(
$"[green] Fixed: added {moduleName} workspace glob to package.json[/]"
);
}
}
}

AnsiConsole.MarkupLine("");
Expand Down
Loading
Loading