@sdxc/kit 2026.10.21 → 2026.10.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.
Files changed (104) hide show
  1. package/README.md +84 -4
  2. package/changelog.jsonl +86 -0
  3. package/config.schema.json +154 -0
  4. package/dist/architecture/complexity.d.ts +73 -0
  5. package/dist/architecture/complexity.js +185 -0
  6. package/dist/architecture/crap.d.ts +62 -0
  7. package/dist/architecture/crap.js +121 -0
  8. package/dist/architecture/graph.d.ts +55 -0
  9. package/dist/architecture/graph.js +194 -0
  10. package/dist/architecture/layers.d.ts +29 -0
  11. package/dist/architecture/layers.js +81 -0
  12. package/dist/architecture/mermaid.d.ts +20 -0
  13. package/dist/architecture/mermaid.js +51 -0
  14. package/dist/cli.js +9 -0
  15. package/dist/commands/create.js +4 -3
  16. package/dist/commands/deploy.js +10 -9
  17. package/dist/commands/destroy.d.ts +1 -1
  18. package/dist/commands/diagram.d.ts +17 -0
  19. package/dist/commands/diagram.js +45 -0
  20. package/dist/commands/fix.d.ts +69 -0
  21. package/dist/commands/fix.js +102 -0
  22. package/dist/commands/make.d.ts +71 -2
  23. package/dist/commands/make.js +46 -0
  24. package/dist/commands/run.d.ts +15 -11
  25. package/dist/commands/run.js +21 -16
  26. package/dist/commands/scaffold.d.ts +1 -1
  27. package/dist/commands/setup.d.ts +26 -0
  28. package/dist/commands/setup.js +33 -0
  29. package/dist/config.d.ts +52 -0
  30. package/dist/config.js +88 -1
  31. package/dist/contract.d.ts +52 -3
  32. package/dist/contract.js +124 -2
  33. package/dist/dependencies.js +7 -1
  34. package/dist/deploy/plan.d.ts +5 -0
  35. package/dist/deploy/plan.js +10 -0
  36. package/dist/destroy.js +13 -6
  37. package/dist/diagram.d.ts +32 -0
  38. package/dist/diagram.js +47 -0
  39. package/dist/doctor/checks.d.ts +2 -1
  40. package/dist/doctor/checks.js +24 -1
  41. package/dist/doctor/complexity.d.ts +13 -0
  42. package/dist/doctor/complexity.js +52 -0
  43. package/dist/doctor/crap.d.ts +14 -0
  44. package/dist/doctor/crap.js +67 -0
  45. package/dist/doctor/dependencies.d.ts +13 -0
  46. package/dist/doctor/dependencies.js +42 -0
  47. package/dist/doctor/duplication.d.ts +19 -0
  48. package/dist/doctor/duplication.js +106 -0
  49. package/dist/doctor/fan-out.d.ts +12 -0
  50. package/dist/doctor/fan-out.js +42 -0
  51. package/dist/doctor/feature-scatter.d.ts +15 -0
  52. package/dist/doctor/feature-scatter.js +84 -0
  53. package/dist/doctor/module-size.d.ts +13 -0
  54. package/dist/doctor/module-size.js +50 -0
  55. package/dist/doctor/mutation.d.ts +20 -0
  56. package/dist/doctor/mutation.js +97 -0
  57. package/dist/doctor/orphans.d.ts +13 -0
  58. package/dist/doctor/orphans.js +50 -0
  59. package/dist/doctor/project.js +8 -5
  60. package/dist/doctor/result-throws.d.ts +17 -0
  61. package/dist/doctor/result-throws.js +72 -0
  62. package/dist/doctor/test-ratio.d.ts +12 -0
  63. package/dist/doctor/test-ratio.js +31 -0
  64. package/dist/fix/commands.d.ts +37 -0
  65. package/dist/fix/commands.js +63 -0
  66. package/dist/fix/emails.d.ts +21 -0
  67. package/dist/fix/emails.js +159 -0
  68. package/dist/fix/env.d.ts +29 -0
  69. package/dist/fix/env.js +58 -0
  70. package/dist/fix/index.d.ts +11 -0
  71. package/dist/fix/index.js +11 -0
  72. package/dist/fix/models.d.ts +20 -0
  73. package/dist/fix/models.js +95 -0
  74. package/dist/lock.js +12 -2
  75. package/dist/make/binding.d.ts +42 -0
  76. package/dist/make/binding.js +237 -0
  77. package/dist/make/imports.js +7 -5
  78. package/dist/make/schema-diff.js +8 -1
  79. package/dist/models.js +7 -7
  80. package/dist/routes/modules.js +8 -5
  81. package/dist/routes/parse.js +8 -7
  82. package/dist/routes/routers.js +9 -5
  83. package/dist/setup/auth.d.ts +12 -0
  84. package/dist/setup/auth.js +209 -0
  85. package/dist/setup/billing.d.ts +11 -0
  86. package/dist/setup/billing.js +116 -0
  87. package/dist/setup/catalog.d.ts +25 -0
  88. package/dist/setup/catalog.js +34 -0
  89. package/dist/setup/credit.d.ts +13 -0
  90. package/dist/setup/credit.js +21 -0
  91. package/dist/setup/flags.d.ts +11 -0
  92. package/dist/setup/flags.js +62 -0
  93. package/dist/setup/index.d.ts +25 -0
  94. package/dist/setup/index.js +53 -0
  95. package/dist/setup/plan.d.ts +38 -0
  96. package/dist/setup/plan.js +62 -0
  97. package/dist/testing.js +3 -3
  98. package/dist/ui/layout.js +1 -1
  99. package/dist/ui/registry.d.ts +2 -2
  100. package/dist/upgrade/project.d.ts +2 -2
  101. package/dist/upgrade/prompt.js +7 -5
  102. package/package.json +10 -7
  103. package/registry/ui/attachment.json +2 -2
  104. package/templates/app/AGENTS.md +14 -1
package/dist/contract.js CHANGED
@@ -10,10 +10,14 @@ import { argument, command, commands, flag, prompt } from "@sdxc/cli";
10
10
  import * as s from "remix/data-schema";
11
11
  import { BUILTIN_TEMPLATES, DEFAULT_TEMPLATE } from "./create/templates.js";
12
12
  import { DEPLOY_STEPS } from "./deploy/plan.js";
13
+ import { BINDING_KINDS } from "./make/binding.js";
13
14
  import { ACTION_NAMES, DESTROY_KINDS, KINDS, MODEL_COMPANIONS, SCAFFOLD_PIECES, } from "./make/kinds.js";
14
15
  import { DEFAULT_TAGS } from "./notes.js";
15
16
  import { ROUTE_SORTS } from "./routes/filter.js";
16
17
  import { FIELD_TYPE_NAMES } from "./scaffold/fields.js";
18
+ import { SETUP_FEATURES } from "./setup/catalog.js";
19
+ /** Feature names `sdxc setup` accepts, as a non-empty tuple for the argument schema. */
20
+ const SETUP_FEATURE_NAMES = SETUP_FEATURES.map((feature) => feature.name);
17
21
  /** Route methods `make controller --method` accepts; `form` declares a GET page with a POST action. */
18
22
  export const METHODS = ["get", "post", "put", "patch", "delete", "form"];
19
23
  /** Every kind `sdxc make` writes, in the order its help lists them. */
@@ -155,7 +159,7 @@ export const SDXC_COMMANDS = commands({
155
159
  ],
156
160
  }),
157
161
  doctor: command({
158
- description: "Lint release drift, secrets, migrations, app layout and project checks",
162
+ description: "Lint release drift, secrets, migrations, app layout, complexity and project checks",
159
163
  flags: {
160
164
  json: flag.boolean("json", { description: "Print the report as JSON for an agent" }),
161
165
  only: flag
@@ -169,6 +173,25 @@ export const SDXC_COMMANDS = commands({
169
173
  },
170
174
  examples: ["doctor", "doctor --json", "doctor --only pins,remix", "doctor --skip ui"],
171
175
  }),
176
+ fix: commands({
177
+ description: "Apply doctor repairs the kit can make safely",
178
+ flags: { dryRun: DRY_RUN_FLAG },
179
+ env: command({
180
+ description: "Append missing bindings.secret() keys to .env.example",
181
+ flags: { dryRun: DRY_RUN_FLAG },
182
+ examples: ["fix env", "fix env --dry-run"],
183
+ }),
184
+ models: command({
185
+ description: "Register unmapped createModel modules in app/models/index.ts",
186
+ flags: { dryRun: DRY_RUN_FLAG },
187
+ examples: ["fix models", "fix models --dry-run"],
188
+ }),
189
+ emails: command({
190
+ description: "Map unmapped emails in app/initializers/mail.ts",
191
+ flags: { dryRun: DRY_RUN_FLAG },
192
+ examples: ["fix emails", "fix emails --dry-run"],
193
+ }),
194
+ }),
172
195
  init: command({
173
196
  description: "Write .config/sdxc.jsonc with every default spelled out",
174
197
  flags: { dryRun: flag.boolean("dry-run", { description: "Print it and write nothing" }) },
@@ -409,6 +432,65 @@ export const SDXC_COMMANDS = commands({
409
432
  }),
410
433
  },
411
434
  }),
435
+ secret: command({
436
+ description: "Declare a bindings.secret() in cloudflare.config.ts and append .env.example",
437
+ tasks: true,
438
+ arguments: {
439
+ name: argument(nonEmpty("Name it"), {
440
+ valueName: "NAME",
441
+ description: "The binding key, SCREAMING_SNAKE or kebab-case",
442
+ prompt: prompt.text({
443
+ message: "What should the secret be called?",
444
+ placeholder: "API_KEY",
445
+ }),
446
+ }),
447
+ },
448
+ flags: { dryRun: DRY_RUN_FLAG, force: FORCE_FLAG },
449
+ examples: ["make secret API_KEY", "make secret api-key --dry-run"],
450
+ }),
451
+ binding: command({
452
+ description: "Declare a Cloudflare binding in cloudflare.config.ts",
453
+ tasks: true,
454
+ arguments: {
455
+ kind: argument(s.enum_(BINDING_KINDS), {
456
+ description: `The bindings helper: ${BINDING_KINDS.join(", ")}`,
457
+ }),
458
+ name: argument(nonEmpty("Name it"), {
459
+ valueName: "NAME",
460
+ description: "The binding key, SCREAMING_SNAKE or kebab-case",
461
+ }),
462
+ },
463
+ flags: { dryRun: DRY_RUN_FLAG, force: FORCE_FLAG },
464
+ examples: ["make binding kv CACHE", "make binding secret API_KEY"],
465
+ }),
466
+ do: command({
467
+ description: "Write a Durable Object class, re-export it from bootstrap/worker.ts, and declare its binding",
468
+ tasks: true,
469
+ arguments: {
470
+ name: argument(nonEmpty("Name it"), {
471
+ description: "The class name, such as Feed or geo-fetch",
472
+ prompt: prompt.text({
473
+ message: "What should the Durable Object be called?",
474
+ placeholder: "Feed",
475
+ }),
476
+ }),
477
+ },
478
+ flags: {
479
+ role: flag.string("role", {
480
+ valueName: "role",
481
+ schema: s.enum_(["model", "service"]),
482
+ default: "service",
483
+ description: "app/models when it owns stored state, app/services otherwise (default: service)",
484
+ }),
485
+ binding: flag.string("binding", {
486
+ valueName: "NAME",
487
+ description: "The env binding key (default: derived from the class name)",
488
+ }),
489
+ dryRun: DRY_RUN_FLAG,
490
+ force: FORCE_FLAG,
491
+ },
492
+ examples: ["make do Feed --role model", "make do geo-fetch --binding GEO_FETCH"],
493
+ }),
412
494
  }),
413
495
  middleware: command({
414
496
  description: "Print each router's global middleware and every chain in app/http/middleware",
@@ -493,7 +575,7 @@ export const SDXC_COMMANDS = commands({
493
575
  ],
494
576
  }),
495
577
  run: command({
496
- description: "Run the project's own command line, bootstrap/cli.ts, with its runtime",
578
+ description: "Run the project's own command line (run.entry, default bootstrap/cli.ts)",
497
579
  arguments: {
498
580
  args: argument.rest({
499
581
  valueName: "command",
@@ -552,11 +634,51 @@ export const SDXC_COMMANDS = commands({
552
634
  flags: { json: flag.boolean("json", { description: "Print the schedule as JSON" }) },
553
635
  examples: ["schedule", "schedule --json"],
554
636
  }),
637
+ setup: command({
638
+ description: "Install a multi-file feature (auth, billing, flags); lists known features with no name",
639
+ arguments: {
640
+ feature: argument(s.enum_(SETUP_FEATURE_NAMES), {
641
+ optional: true,
642
+ description: "The feature to install; lists the catalog when left out",
643
+ }),
644
+ },
645
+ flags: {
646
+ provider: flag.string("provider", {
647
+ valueName: "provider",
648
+ description: "Backend for features that vary (auth: r3-auth; billing: polar)",
649
+ }),
650
+ yes: flag.boolean("yes", {
651
+ short: "y",
652
+ description: "Write the plan; without it the plan is printed and nothing changes",
653
+ }),
654
+ dryRun: DRY_RUN_FLAG,
655
+ },
656
+ examples: [
657
+ "setup",
658
+ "setup auth",
659
+ "setup auth --provider r3-auth -y",
660
+ "setup billing --provider polar --dry-run",
661
+ "setup flags -y",
662
+ ],
663
+ }),
555
664
  stats: command({
556
665
  description: "Count lines of code per kind of code the app layout names, and the test ratio",
557
666
  flags: { json: flag.boolean("json", { description: "Print the counts as JSON" }) },
558
667
  examples: ["stats", "stats --json"],
559
668
  }),
669
+ diagram: command({
670
+ description: "Draw the project's layer architecture as Mermaid, or as SVG through @sdxc/diagram",
671
+ flags: {
672
+ json: flag.boolean("json", {
673
+ description: "Print the import graph as JSON instead of Mermaid",
674
+ }),
675
+ svg: flag.string("svg", {
676
+ valueName: "path",
677
+ description: "Write an SVG drawing to this path (relative to the project root) via @sdxc/diagram",
678
+ }),
679
+ },
680
+ examples: ["diagram", "diagram --json", "diagram --svg architecture.svg"],
681
+ }),
560
682
  ui: commands({
561
683
  description: "Copy @sdxc/ui components into the project and keep imports on the copies",
562
684
  list: command({ description: "Every component, marking copies that are edited or behind" }),
@@ -74,7 +74,13 @@ export async function missingDependencies(root, files, signal) {
74
74
  let dependencies = { ...section(manifest.data.dependencies) };
75
75
  for (let [name, version] of versions.data)
76
76
  dependencies[name] = version;
77
- manifest.data.dependencies = Object.fromEntries(Object.entries(dependencies).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
77
+ manifest.data.dependencies = Object.fromEntries(Object.entries(dependencies).sort(([a], [b]) => {
78
+ if (a < b)
79
+ return -1;
80
+ if (a > b)
81
+ return 1;
82
+ return 0;
83
+ }));
78
84
  let indent = /^[ \t]+/m.exec(before.data)?.[0] ?? "\t";
79
85
  return success({
80
86
  path: "package.json",
@@ -43,6 +43,11 @@ export declare function parsePending(stdout: string): string[];
43
43
  export declare function isUnknown(error: Error, kind: "command" | "flag"): boolean;
44
44
  /** Whether the migration step applies anything once the plan is confirmed. */
45
45
  export declare function migrates(step: MigrationStep): boolean;
46
+ /**
47
+ * The child output a failed `db migrate --remote --pending` left behind, so the deploy
48
+ * failure names wrangler/cf's reason instead of only the exit code.
49
+ */
50
+ export declare function execDetail(error: Error): string;
46
51
  /** The plan as the terminal shows it, one fact per line and one line per pending migration. */
47
52
  export declare function formatPlan(plan: Plan): string;
48
53
  /** Where production stands when the app's `deploy` fails after the migration step. */
@@ -32,6 +32,16 @@ export function isUnknown(error, kind) {
32
32
  export function migrates(step) {
33
33
  return step.status === "unlisted" || (step.status === "pending" && step.names.length > 0);
34
34
  }
35
+ /**
36
+ * The child output a failed `db migrate --remote --pending` left behind, so the deploy
37
+ * failure names wrangler/cf's reason instead of only the exit code.
38
+ */
39
+ export function execDetail(error) {
40
+ if (!(error instanceof ExecError))
41
+ return error.message;
42
+ let detail = error.stderr.trim() || error.stdout.trim();
43
+ return detail === "" ? error.message : `${error.message}\n${detail}`;
44
+ }
35
45
  /** The plan as the terminal shows it, one fact per line and one line per pending migration. */
36
46
  export function formatPlan(plan) {
37
47
  let lines = [
package/dist/destroy.js CHANGED
@@ -10,6 +10,7 @@
10
10
  import { readFile, stat } from "node:fs/promises";
11
11
  import { join, posix } from "node:path";
12
12
  import { findStatements, removeProperty, removeStatements, tokenize } from "@sdxc/codemod";
13
+ import { iife } from "@sdxc/iife";
13
14
  import { failure, isFailure, success, wrap } from "@sdxc/result";
14
15
  import { listFiles } from "./doctor/files.js";
15
16
  import { exists, folderOf, specPathOf } from "./make/generate.js";
@@ -36,11 +37,13 @@ function specifiers(file, from) {
36
37
  }
37
38
  /** The project file a specifier written in `from` names, or `null` for a package. */
38
39
  async function resolveModule(root, from, specifier) {
39
- let base = specifier.startsWith("~/")
40
- ? specifier.slice(2)
41
- : specifier.startsWith(".")
42
- ? posix.normalize(posix.join(posix.dirname(from), specifier))
43
- : null;
40
+ let base = iife(() => {
41
+ if (specifier.startsWith("~/"))
42
+ return specifier.slice(2);
43
+ if (specifier.startsWith("."))
44
+ return posix.normalize(posix.join(posix.dirname(from), specifier));
45
+ return null;
46
+ });
44
47
  if (base === null)
45
48
  return null;
46
49
  let bare = base.replace(/\.[cm]?js$/, "");
@@ -95,7 +98,11 @@ async function unmap(root, kind, file, resource, edits, notes) {
95
98
  declared = [local, ...path].join(".");
96
99
  let imported = new RegExp(`import\\s+${local}\\s+from\\s+"([^"]+)"`).exec(source)?.[1];
97
100
  let module = imported === undefined ? null : await resolveModule(root, initializer, imported);
98
- let call = kind === "mcp" ? (resource ? "resources" : "tools") : DECLARATION_CALLS[kind];
101
+ let call = iife(() => {
102
+ if (kind === "mcp")
103
+ return resource ? "resources" : "tools";
104
+ return DECLARATION_CALLS[kind];
105
+ });
99
106
  if (module === null || call === undefined || path.length === 0)
100
107
  continue;
101
108
  let declarations = await current(root, edits, module);
@@ -0,0 +1,32 @@
1
+ /**
2
+ * `sdxc diagram`: the project's layer import graph as Mermaid, optionally drawn to SVG through
3
+ * `@sdxc/diagram`, so an agent can read the architecture without opening every file.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ import type { Result } from "@sdxc/result";
9
+ import type { ProjectGraph } from "./architecture/graph.js";
10
+ /** What the command prints or writes. */
11
+ export interface DiagramResult {
12
+ /** Mermaid flowchart source. */
13
+ mermaid: string;
14
+ /** The graph behind the diagram, for `--json`. */
15
+ graph: ProjectGraph;
16
+ /** Absolute path of a written SVG, when one was requested. */
17
+ svgPath: string | null;
18
+ }
19
+ /** Options for {@link buildDiagram}. */
20
+ export interface DiagramOptions {
21
+ /** When set, render SVG with `@sdxc/diagram` and write it to this path (relative to root). */
22
+ svg?: string;
23
+ /** Accessible name for the SVG title. */
24
+ title?: string;
25
+ }
26
+ /**
27
+ * Builds the architecture diagram for the project at `root`. With `svg`, writes the drawing and
28
+ * returns its path; without it, only the Mermaid text is produced.
29
+ */
30
+ export declare function buildDiagram(root: string, options?: DiagramOptions): Promise<Result<DiagramResult, Error>>;
31
+ /** Human-readable summary of the graph for a terminal without Mermaid rendering. */
32
+ export declare function formatDiagramSummary(graph: ProjectGraph): string;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * `sdxc diagram`: the project's layer import graph as Mermaid, optionally drawn to SVG through
3
+ * `@sdxc/diagram`, so an agent can read the architecture without opening every file.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ import { writeFile } from "node:fs/promises";
9
+ import { join } from "node:path";
10
+ import { toSVG } from "@sdxc/diagram";
11
+ import { failure, isFailure, success, wrap } from "@sdxc/result";
12
+ import { projectGraph } from "./architecture/graph.js";
13
+ import { toMermaid } from "./architecture/mermaid.js";
14
+ /**
15
+ * Builds the architecture diagram for the project at `root`. With `svg`, writes the drawing and
16
+ * returns its path; without it, only the Mermaid text is produced.
17
+ */
18
+ export async function buildDiagram(root, options = {}) {
19
+ let graph = await projectGraph(root);
20
+ let mermaid = toMermaid(graph, { title: options.title });
21
+ if (!options.svg) {
22
+ return success({ mermaid, graph, svgPath: null });
23
+ }
24
+ let drawn = toSVG(mermaid, { alt: options.title ?? "Architecture" });
25
+ if (isFailure(drawn)) {
26
+ return failure(new Error(drawn.error.message));
27
+ }
28
+ let svgPath = join(root, options.svg);
29
+ let written = await wrap(() => writeFile(svgPath, drawn.data));
30
+ if (isFailure(written))
31
+ return failure(written.error);
32
+ return success({ mermaid, graph, svgPath });
33
+ }
34
+ /** Human-readable summary of the graph for a terminal without Mermaid rendering. */
35
+ export function formatDiagramSummary(graph) {
36
+ let lines = [
37
+ `Modules: ${graph.modules.length}`,
38
+ `Imports: ${graph.edges.length}`,
39
+ `Layer edges: ${graph.layers.length}`,
40
+ `Dependency-rule breaches: ${graph.violations.length}`,
41
+ `Import cycles: ${graph.cycles.length}`,
42
+ "",
43
+ toMermaid(graph).trimEnd(),
44
+ "",
45
+ ];
46
+ return lines.join("\n");
47
+ }
@@ -9,7 +9,8 @@
9
9
  import type { Check, CheckReport } from "./check.js";
10
10
  /**
11
11
  * Every built-in check: release drift, the install and the `remix` peer first, then the
12
- * Worker's secrets and types, then the app's own code, layout to copied components.
12
+ * Worker's secrets and types, then the app's own code, layout and quality metrics, then
13
+ * copied components.
13
14
  */
14
15
  export declare const CHECKS: readonly Check[];
15
16
  /** Whether any check failed, which makes `sdxc doctor` exit 1. */
@@ -6,21 +6,33 @@
6
6
  * @author [Sergio Xalambrí](https://sergiodxa.com)
7
7
  * @copyright Sergio Xalambrí 2026
8
8
  */
9
+ import { complexityCheck } from "./complexity.js";
10
+ import { crapCheck } from "./crap.js";
11
+ import { dependenciesCheck } from "./dependencies.js";
12
+ import { duplicationCheck } from "./duplication.js";
9
13
  import { emailsCheck } from "./emails.js";
10
14
  import { envCheck } from "./env.js";
15
+ import { fanOutCheck } from "./fan-out.js";
16
+ import { featureScatterCheck } from "./feature-scatter.js";
11
17
  import { installedCheck } from "./installed.js";
12
18
  import { jsdocCheck } from "./jsdoc.js";
13
19
  import { layoutCheck } from "./layout.js";
14
20
  import { migrationsCheck } from "./migrations.js";
15
21
  import { modelsCheck } from "./models.js";
22
+ import { moduleSizeCheck } from "./module-size.js";
23
+ import { mutationCheck } from "./mutation.js";
24
+ import { orphansCheck } from "./orphans.js";
16
25
  import { pinsCheck } from "./pins.js";
17
26
  import { remixCheck } from "./remix.js";
27
+ import { resultThrowsCheck } from "./result-throws.js";
18
28
  import { routesCheck } from "./routes.js";
29
+ import { testRatioCheck } from "./test-ratio.js";
19
30
  import { typegenCheck } from "./typegen.js";
20
31
  import { uiCheck } from "./ui.js";
21
32
  /**
22
33
  * Every built-in check: release drift, the install and the `remix` peer first, then the
23
- * Worker's secrets and types, then the app's own code, layout to copied components.
34
+ * Worker's secrets and types, then the app's own code, layout and quality metrics, then
35
+ * copied components.
24
36
  */
25
37
  export const CHECKS = [
26
38
  pinsCheck,
@@ -34,6 +46,17 @@ export const CHECKS = [
34
46
  modelsCheck,
35
47
  emailsCheck,
36
48
  jsdocCheck,
49
+ complexityCheck,
50
+ moduleSizeCheck,
51
+ dependenciesCheck,
52
+ fanOutCheck,
53
+ orphansCheck,
54
+ featureScatterCheck,
55
+ duplicationCheck,
56
+ resultThrowsCheck,
57
+ testRatioCheck,
58
+ crapCheck,
59
+ mutationCheck,
37
60
  uiCheck,
38
61
  ];
39
62
  /** Whether any check failed, which makes `sdxc doctor` exit 1. */
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The `complexity` check: every function's cyclomatic complexity stays at or under the
3
+ * configured maximum (default 4), so agent-written branches stay small enough to test and
4
+ * review. Oxlint's `complexity` rule is left off; this check is project-aware and configurable.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import type { Check } from "./check.js";
10
+ /**
11
+ * Warns on each function whose cyclomatic complexity exceeds `doctor.complexity.max`.
12
+ */
13
+ export declare const complexityCheck: Check;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * The `complexity` check: every function's cyclomatic complexity stays at or under the
3
+ * configured maximum (default 4), so agent-written branches stay small enough to test and
4
+ * review. Oxlint's `complexity` rule is left off; this check is project-aware and configurable.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import { readFile } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+ import { isFailure, wrap } from "@sdxc/result";
12
+ import { measureComplexity } from "../architecture/complexity.js";
13
+ import { PROJECT_FOLDERS } from "../stats.js";
14
+ import { passed, skipped } from "./check.js";
15
+ import { isAppSource, listFiles } from "./files.js";
16
+ /**
17
+ * Warns on each function whose cyclomatic complexity exceeds `doctor.complexity.max`.
18
+ */
19
+ export const complexityCheck = {
20
+ name: "complexity",
21
+ async run(context) {
22
+ let max = context.config.doctor.complexity.max;
23
+ let findings = [];
24
+ let files = 0;
25
+ for (let folder of PROJECT_FOLDERS) {
26
+ for (let file of (await listFiles(context.root, folder)).filter(isAppSource)) {
27
+ files += 1;
28
+ let source = await wrap(() => readFile(join(context.root, file), "utf8"));
29
+ if (isFailure(source))
30
+ continue;
31
+ for (let fn of measureComplexity(file, source.data)) {
32
+ if (fn.complexity <= max)
33
+ continue;
34
+ findings.push(`${file}:${fn.line}: ${fn.name} has complexity ${fn.complexity} (max ${max})`);
35
+ }
36
+ }
37
+ }
38
+ if (files === 0)
39
+ return skipped("No app source to measure complexity");
40
+ if (findings.length === 0) {
41
+ return passed(`Every function stays at cyclomatic complexity ${max} or below`);
42
+ }
43
+ return {
44
+ status: "warn",
45
+ message: findings.length === 1
46
+ ? "Found 1 function above the cyclomatic complexity limit"
47
+ : `Found ${findings.length} functions above the cyclomatic complexity limit`,
48
+ findings,
49
+ fix: `Split each function so its decision points stay at ${max} or fewer, or raise doctor.complexity.max in .config/sdxc.jsonc`,
50
+ };
51
+ },
52
+ };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The `crap` check: CRAP scores from cyclomatic complexity and Istanbul coverage stay at or
3
+ * under the configured maximum (default 12). Without a coverage report the check skips, since a
4
+ * score without coverage would only restate complexity.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import type { Check } from "./check.js";
10
+ /**
11
+ * Warns on each function whose CRAP score exceeds `doctor.crap.max` when coverage data is
12
+ * present at `doctor.crap.coverage`.
13
+ */
14
+ export declare const crapCheck: Check;
@@ -0,0 +1,67 @@
1
+ /**
2
+ * The `crap` check: CRAP scores from cyclomatic complexity and Istanbul coverage stay at or
3
+ * under the configured maximum (default 12). Without a coverage report the check skips, since a
4
+ * score without coverage would only restate complexity.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import { readFile } from "node:fs/promises";
10
+ import { join } from "node:path";
11
+ import { isFailure, wrap } from "@sdxc/result";
12
+ import { measureComplexity } from "../architecture/complexity.js";
13
+ import { coverageExists, loadCoverage, scoreFunctions } from "../architecture/crap.js";
14
+ import { PROJECT_FOLDERS } from "../stats.js";
15
+ import { passed, skipped } from "./check.js";
16
+ import { isAppSource, listFiles } from "./files.js";
17
+ /**
18
+ * Warns on each function whose CRAP score exceeds `doctor.crap.max` when coverage data is
19
+ * present at `doctor.crap.coverage`.
20
+ */
21
+ export const crapCheck = {
22
+ name: "crap",
23
+ async run(context) {
24
+ let { max, coverage: coverageFile } = context.config.doctor.crap;
25
+ if (!(await coverageExists(context.root, coverageFile))) {
26
+ return skipped(`No coverage at ${coverageFile}; run tests with coverage then re-run doctor`);
27
+ }
28
+ let coverage = await loadCoverage(context.root, coverageFile);
29
+ let findings = [];
30
+ let scored = 0;
31
+ for (let folder of PROJECT_FOLDERS) {
32
+ for (let file of (await listFiles(context.root, folder)).filter(isAppSource)) {
33
+ let source = await wrap(() => readFile(join(context.root, file), "utf8"));
34
+ if (isFailure(source))
35
+ continue;
36
+ let functions = measureComplexity(file, source.data);
37
+ for (let entry of scoreFunctions(file, functions, coverage)) {
38
+ if (entry.crap === null)
39
+ continue;
40
+ scored += 1;
41
+ if (entry.crap <= max)
42
+ continue;
43
+ let pct = entry.coverage === null ? "?" : `${Math.round(entry.coverage * 100)}%`;
44
+ findings.push(`${entry.file}:${entry.line}: ${entry.name} CRAP ${formatCrap(entry.crap)} (cc ${entry.complexity}, cov ${pct}, max ${max})`);
45
+ }
46
+ }
47
+ }
48
+ if (scored === 0) {
49
+ return skipped(`Coverage at ${coverageFile} matches no app functions; generate coverage for app source`);
50
+ }
51
+ if (findings.length === 0) {
52
+ return passed(`Every scored function stays at CRAP ${max} or below`);
53
+ }
54
+ return {
55
+ status: "warn",
56
+ message: findings.length === 1
57
+ ? "Found 1 function above the CRAP limit"
58
+ : `Found ${findings.length} functions above the CRAP limit`,
59
+ findings,
60
+ fix: `Lower complexity, raise coverage, or raise doctor.crap.max in .config/sdxc.jsonc`,
61
+ };
62
+ },
63
+ };
64
+ /** One decimal place when the score is not an integer. */
65
+ function formatCrap(value) {
66
+ return Number.isInteger(value) ? String(value) : value.toFixed(1);
67
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The `dependencies` check: import cycles and Clean Architecture breaches against the app-layout
3
+ * layers — models stay inward of services and http, resources stay outward of delivery code.
4
+ * Oxlint has no project-wide dependency-rule or cycle check for this layout.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import type { Check } from "./check.js";
10
+ /**
11
+ * Warns on each import cycle and each edge that points from an inner layer to an outer one.
12
+ */
13
+ export declare const dependenciesCheck: Check;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The `dependencies` check: import cycles and Clean Architecture breaches against the app-layout
3
+ * layers — models stay inward of services and http, resources stay outward of delivery code.
4
+ * Oxlint has no project-wide dependency-rule or cycle check for this layout.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import { projectGraph } from "../architecture/graph.js";
10
+ import { layerOf } from "../architecture/layers.js";
11
+ import { passed, skipped } from "./check.js";
12
+ /**
13
+ * Warns on each import cycle and each edge that points from an inner layer to an outer one.
14
+ */
15
+ export const dependenciesCheck = {
16
+ name: "dependencies",
17
+ async run(context) {
18
+ let graph = await projectGraph(context.root);
19
+ if (graph.modules.length === 0)
20
+ return skipped("No app source to check dependencies");
21
+ let findings = [];
22
+ for (let cycle of graph.cycles) {
23
+ findings.push(`cycle: ${cycle.join(" -> ")} -> ${cycle[0]}`);
24
+ }
25
+ for (let edge of graph.violations) {
26
+ let from = layerOf(edge.from) ?? "?";
27
+ let to = layerOf(edge.to) ?? "?";
28
+ findings.push(`${edge.from} (${from}) imports ${edge.to} (${to}); dependencies must point inward`);
29
+ }
30
+ if (findings.length === 0) {
31
+ return passed("No import cycles; every layer edge points inward");
32
+ }
33
+ return {
34
+ status: "warn",
35
+ message: findings.length === 1
36
+ ? "Found 1 dependency structure problem"
37
+ : `Found ${findings.length} dependency structure problems`,
38
+ findings,
39
+ fix: "Break each cycle with an interface or extract shared code inward; move imports so outer layers depend on inner ones (models innermost). sdxc diagram shows the graph",
40
+ };
41
+ },
42
+ };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The `duplication` check: identical blocks of at least `doctor.duplication.minLines` code
3
+ * lines (blank and comments stripped) appear in more than one module, so agents extract shared
4
+ * helpers instead of pasting.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import type { Check } from "./check.js";
10
+ /**
11
+ * Warns when the same normalised code block of `minLines` or more appears in two places.
12
+ */
13
+ export declare const duplicationCheck: Check;
14
+ /** Sliding windows of `minLines` consecutive code lines, keyed by their joined text. */
15
+ export declare function codeBlocks(file: string, source: string, minLines: number): Array<{
16
+ key: string;
17
+ file: string;
18
+ line: number;
19
+ }>;