@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
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The `test-ratio` check: the code-to-test ratio from `sdxc stats` stays at or above
3
+ * `doctor.testRatio.min` (default 0.3 → `1:0.3`), so agents keep writing tests with the code.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ import { projectStats } from "../stats.js";
9
+ import { passed, skipped } from "./check.js";
10
+ /**
11
+ * Warns when `tests / code` is below the configured minimum. A project with no app code skips.
12
+ */
13
+ export const testRatioCheck = {
14
+ name: "test-ratio",
15
+ async run(context) {
16
+ let min = context.config.doctor.testRatio.min;
17
+ let stats = await projectStats(context.root);
18
+ if (stats.code === 0)
19
+ return skipped("No app code to compare with tests");
20
+ let ratio = stats.tests / stats.code;
21
+ if (ratio >= min) {
22
+ return passed(`Code to test ratio is 1:${ratio.toFixed(1)} (min 1:${min.toFixed(1)})`);
23
+ }
24
+ return {
25
+ status: "warn",
26
+ message: `Code to test ratio is 1:${ratio.toFixed(1)}, below 1:${min.toFixed(1)}`,
27
+ findings: [`code ${stats.code}, tests ${stats.tests}`],
28
+ fix: `Add tests beside the code, or lower doctor.testRatio.min in .config/sdxc.jsonc`,
29
+ };
30
+ },
31
+ };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Command-shaped `sdxc fix` repairs: re-run `typegen`, `ui update`, package install and
3
+ * `upgrade` when those are already the doctor check's `fix`, without new mutation logic.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ import type { AnyCommandContext } from "@sdxc/cli";
9
+ import type { Result } from "@sdxc/result";
10
+ import type { Config } from "../config.js";
11
+ import type { CheckReport } from "../doctor/check.js";
12
+ import type { PackageManager } from "../package-manager.js";
13
+ import type { Manifest } from "../upgrade/project.js";
14
+ /** What one command-shaped fix ran or would run. */
15
+ export interface CommandFix {
16
+ check: string;
17
+ command: string[];
18
+ }
19
+ /** Context `fix` needs to exec and print. */
20
+ export type FixContext = Pick<AnyCommandContext, "stdout" | "exec">;
21
+ /**
22
+ * Re-runs the command-shaped doctor checks and executes each repairable `fix`. Under
23
+ * `dryRun` it prints the commands and changes nothing.
24
+ */
25
+ export declare function fixCommands(ctx: FixContext, options: {
26
+ root: string;
27
+ packageRoot: string;
28
+ manager: PackageManager;
29
+ config: Config;
30
+ manifest: Manifest;
31
+ dryRun: boolean;
32
+ }): Promise<Result<CommandFix[], Error>>;
33
+ /**
34
+ * Turns a doctor `fix` string into an argv the project can run. Only command-shaped fixes
35
+ * are accepted; prose instructions return `null`.
36
+ */
37
+ export declare function parseFixCommand(report: CheckReport, manager: PackageManager, bin: string): string[] | null;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Command-shaped `sdxc fix` repairs: re-run `typegen`, `ui update`, package install and
3
+ * `upgrade` when those are already the doctor check's `fix`, without new mutation logic.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ import { join } from "node:path";
9
+ import { failure, isFailure, success } from "@sdxc/result";
10
+ import { createDoctorContext, runChecks } from "../doctor/check.js";
11
+ import { CHECKS } from "../doctor/checks.js";
12
+ /**
13
+ * Re-runs the command-shaped doctor checks and executes each repairable `fix`. Under
14
+ * `dryRun` it prints the commands and changes nothing.
15
+ */
16
+ export async function fixCommands(ctx, options) {
17
+ let context = createDoctorContext({
18
+ root: options.root,
19
+ manifest: options.manifest,
20
+ config: options.config,
21
+ manager: options.manager,
22
+ packageRoot: options.packageRoot,
23
+ });
24
+ let names = new Set(["typegen", "ui", "installed", "pins", "remix"]);
25
+ let reports = await runChecks(CHECKS.filter((check) => names.has(check.name)), context);
26
+ let bin = join(options.packageRoot, "src/bin.ts");
27
+ let fixes = [];
28
+ for (let report of reports) {
29
+ if (report.status !== "warn" && report.status !== "fail")
30
+ continue;
31
+ if (report.fix === null)
32
+ continue;
33
+ let command = parseFixCommand(report, options.manager, bin);
34
+ if (command === null)
35
+ continue;
36
+ fixes.push({ check: report.name, command });
37
+ if (options.dryRun) {
38
+ ctx.stdout(`would run ${command.join(" ")}\n`);
39
+ continue;
40
+ }
41
+ ctx.stdout(`running ${command.join(" ")}\n`);
42
+ let ran = await ctx.exec(command, { cwd: options.root, stdio: "inherit" });
43
+ if (isFailure(ran)) {
44
+ return failure(new Error(`${command.join(" ")} failed`));
45
+ }
46
+ }
47
+ return success(fixes);
48
+ }
49
+ /**
50
+ * Turns a doctor `fix` string into an argv the project can run. Only command-shaped fixes
51
+ * are accepted; prose instructions return `null`.
52
+ */
53
+ export function parseFixCommand(report, manager, bin) {
54
+ let fix = report.fix;
55
+ if (fix === null)
56
+ return null;
57
+ if (fix === manager.install.join(" "))
58
+ return [...manager.install];
59
+ if (fix.startsWith("sdxc ")) {
60
+ return ["bun", bin, ...fix.slice("sdxc ".length).split(/\s+/).filter(Boolean)];
61
+ }
62
+ return null;
63
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * `sdxc fix emails`: maps every email `app/emails/index.ts` declares that
3
+ * `app/initializers/mail.ts` leaves unmapped, through the same codemod `sdxc make email` uses.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ import type { Result } from "@sdxc/result";
9
+ /** One mapping the fix applies. */
10
+ export interface EmailFix {
11
+ name: string;
12
+ template: string;
13
+ diffs: string[];
14
+ }
15
+ /**
16
+ * Maps each unmapped declared email onto its template under `app/emails/`. Refuses a name with
17
+ * no template file, or whose declaration cannot be placed automatically.
18
+ */
19
+ export declare function fixEmails(root: string, options: {
20
+ dryRun: boolean;
21
+ }): Promise<Result<EmailFix[], Error>>;
@@ -0,0 +1,159 @@
1
+ /**
2
+ * `sdxc fix emails`: maps every email `app/emails/index.ts` declares that
3
+ * `app/initializers/mail.ts` leaves unmapped, through the same codemod `sdxc make email` uses.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ import { access, readFile, writeFile } from "node:fs/promises";
9
+ import { join } from "node:path";
10
+ import { findModuleReferences, tokenize } from "@sdxc/codemod";
11
+ import { failure, isFailure, success, wrap } from "@sdxc/result";
12
+ import { unifiedDiff } from "../diff.js";
13
+ import { EMAILS_INDEX, MAIL_INITIALIZER } from "../doctor/emails.js";
14
+ import { declare } from "../make/declare.js";
15
+ import { parseName } from "../make/names.js";
16
+ import { Reader } from "../routes/parse.js";
17
+ /** Extensions a template specifier without one may resolve to. */
18
+ const EXTENSIONS = [".tsx", ".ts", "/index.tsx", "/index.ts"];
19
+ /**
20
+ * Maps each unmapped declared email onto its template under `app/emails/`. Refuses a name with
21
+ * no template file, or whose declaration cannot be placed automatically.
22
+ */
23
+ export async function fixEmails(root, options) {
24
+ let unmapped = await unmappedEmails(root);
25
+ if (isFailure(unmapped))
26
+ return unmapped;
27
+ if (unmapped.data.length === 0)
28
+ return success([]);
29
+ let fixed = [];
30
+ for (let name of unmapped.data) {
31
+ let template = await resolveTemplate(root, name);
32
+ if (template === null) {
33
+ return failure(new Error(`No template under app/emails/ for declared email ${name}; write one with sdxc make email`));
34
+ }
35
+ let parsed = parseName(name.replaceAll(".", "/"));
36
+ if (isFailure(parsed))
37
+ return parsed;
38
+ let declared = await declare({
39
+ kind: "email",
40
+ name: parsed.data,
41
+ variant: null,
42
+ method: "get",
43
+ routes: "web",
44
+ handler: template.replace(/\.[cm]?[jt]sx?$/, ""),
45
+ tool: parsed.data.snake,
46
+ uri: "",
47
+ title: parsed.data.title,
48
+ }, root);
49
+ if (declared.kind === "manual") {
50
+ return failure(new Error(`Cannot map ${name} automatically (${declared.reason}):\n${declared.instructions}`));
51
+ }
52
+ let diffs = [];
53
+ for (let edit of declared.edits) {
54
+ diffs.push(unifiedDiff(edit.path, edit.before, edit.after));
55
+ if (!options.dryRun)
56
+ await writeFile(join(root, edit.path), edit.after);
57
+ }
58
+ fixed.push({ name, template, diffs });
59
+ }
60
+ return success(fixed);
61
+ }
62
+ /** Declared email names that have no `mail.map` entry. */
63
+ async function unmappedEmails(root) {
64
+ let index = await readModule(root, EMAILS_INDEX);
65
+ if (index === null)
66
+ return failure(new Error(`No ${EMAILS_INDEX} in the project`));
67
+ let declared = declaredEmails(index);
68
+ if (declared === null) {
69
+ return failure(new Error(`${EMAILS_INDEX} declares no emails({ … })`));
70
+ }
71
+ let initializer = await readModule(root, MAIL_INITIALIZER);
72
+ let mapped = initializer === null ? new Set() : new Set(mappings(initializer).keys());
73
+ return success(declared.filter((name) => !mapped.has(name)));
74
+ }
75
+ /** The template path under `app/emails/` for a dotted email name, or `null`. */
76
+ async function resolveTemplate(root, name) {
77
+ let base = `app/emails/${name.replaceAll(".", "/")}`;
78
+ for (let extension of EXTENSIONS) {
79
+ let path = `${base}${extension}`.replace(/\/index\/index/, "/index");
80
+ if (await exists(root, path))
81
+ return path;
82
+ }
83
+ return null;
84
+ }
85
+ async function exists(root, path) {
86
+ return isFailure(await wrap(() => access(join(root, path)))) === false;
87
+ }
88
+ async function readModule(root, path) {
89
+ let source = await wrap(() => readFile(join(root, path), "utf8"));
90
+ if (isFailure(source))
91
+ return null;
92
+ let tokens = tokenize(path, source.data);
93
+ let references = findModuleReferences(path, source.data);
94
+ if (isFailure(tokens) || isFailure(references))
95
+ return null;
96
+ let imports = new Map();
97
+ for (let reference of references.data) {
98
+ if (reference.kind !== "import")
99
+ continue;
100
+ for (let bound of reference.names) {
101
+ imports.set(bound.local, { specifier: reference.specifier, imported: bound.imported });
102
+ }
103
+ }
104
+ return { reader: new Reader(tokens.data, source.data), imports };
105
+ }
106
+ function declaredEmails(module) {
107
+ let declarations = module.reader.declarations();
108
+ let exported = declarations.defaultExport;
109
+ if (exported?.kind === "identifier")
110
+ exported = declarations.locals.get(exported.name) ?? null;
111
+ if (exported?.kind !== "call" || !isImportOf(module, exported.callee, "emails"))
112
+ return null;
113
+ let tree = exported.args[0]?.node;
114
+ if (tree?.kind !== "object")
115
+ return null;
116
+ return leaves(module, tree, []);
117
+ }
118
+ function leaves(module, node, path) {
119
+ if (node.kind === "call" && isImportOf(module, node.callee, "email"))
120
+ return [path.join(".")];
121
+ let group = node;
122
+ if (node.kind === "call" && isImportOf(module, node.callee, "emails")) {
123
+ group = node.args[0]?.node ?? node;
124
+ }
125
+ if (group.kind !== "object")
126
+ return [];
127
+ return group.entries.flatMap((entry) => "key" in entry ? leaves(module, entry.value, [...path, entry.key]) : []);
128
+ }
129
+ function isImportOf(module, callee, imported) {
130
+ return callee.kind === "identifier" && module.imports.get(callee.name)?.imported === imported;
131
+ }
132
+ function mappings(module) {
133
+ let reader = module.reader;
134
+ let found = new Map();
135
+ for (let index = 0; index < reader.tokens.length; index += 1) {
136
+ if (!reader.is(index, ".") || !reader.isWord(index + 1, "map") || !reader.is(index + 2, "(")) {
137
+ continue;
138
+ }
139
+ let start = index - 1;
140
+ let call = reader.expression(start, reader.tokens.length).node;
141
+ if (call.kind !== "call")
142
+ continue;
143
+ let [target] = call.args;
144
+ let name = target === undefined ? null : emailName(target.node);
145
+ if (name === null)
146
+ continue;
147
+ found.set(name, null);
148
+ }
149
+ return found;
150
+ }
151
+ function emailName(node) {
152
+ let path = [];
153
+ let current = node;
154
+ while (current.kind === "member") {
155
+ path.unshift(current.property);
156
+ current = current.object;
157
+ }
158
+ return current.kind === "identifier" && path.length > 0 ? path.join(".") : null;
159
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * `sdxc fix env`: appends every `bindings.secret()` key that `.env.example` leaves out, as empty
3
+ * `KEY=` lines, so CI's typegen and the env check agree without inventing secret values.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ import type { Result } from "@sdxc/result";
9
+ /** What `fix env` decided before writing. */
10
+ export interface EnvFixPlan {
11
+ /** Keys that will be appended. */
12
+ missing: string[];
13
+ /** Diff of `.env.example`, empty when nothing changes. */
14
+ diff: string;
15
+ /** Full file text after the append. */
16
+ after: string;
17
+ }
18
+ /**
19
+ * Plans the `.env.example` append for secrets declared in `cloudflare.config.ts` and missing
20
+ * from the example file.
21
+ */
22
+ export declare function planEnvFix(root: string): Promise<Result<EnvFixPlan, Error>>;
23
+ /** Writes the planned `.env.example`, or returns its diff under `dryRun`. */
24
+ export declare function fixEnv(root: string, options: {
25
+ dryRun: boolean;
26
+ }): Promise<Result<{
27
+ missing: string[];
28
+ diff: string;
29
+ }, Error>>;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * `sdxc fix env`: appends every `bindings.secret()` key that `.env.example` leaves out, as empty
3
+ * `KEY=` lines, so CI's typegen and the env check agree without inventing secret values.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ import { readFile, writeFile } from "node:fs/promises";
9
+ import { join } from "node:path";
10
+ import { iife } from "@sdxc/iife";
11
+ import { failure, isFailure, success, wrap } from "@sdxc/result";
12
+ import { unifiedDiff } from "../diff.js";
13
+ import { CONFIG_FILE, ENV_EXAMPLE_FILE, declaredBindings, exampleKeys } from "../doctor/env.js";
14
+ /**
15
+ * Plans the `.env.example` append for secrets declared in `cloudflare.config.ts` and missing
16
+ * from the example file.
17
+ */
18
+ export async function planEnvFix(root) {
19
+ let config = await wrap(() => readFile(join(root, CONFIG_FILE), "utf8"));
20
+ if (isFailure(config))
21
+ return failure(new Error(`No ${CONFIG_FILE} in the project`));
22
+ let declared = declaredBindings(config.data);
23
+ let example = await wrap(() => readFile(join(root, ENV_EXAMPLE_FILE), "utf8"));
24
+ let before = isFailure(example) ? "" : example.data;
25
+ let listed = exampleKeys(before);
26
+ let missing = [...declared]
27
+ .filter(([key, kind]) => kind === "secret" && !listed.has(key))
28
+ .map(([key]) => key);
29
+ if (missing.length === 0) {
30
+ return success({ missing: [], diff: "", after: before });
31
+ }
32
+ let block = missing.map((key) => `${key}=`).join("\n");
33
+ let after = iife(() => {
34
+ if (before === "")
35
+ return `${block}\n`;
36
+ if (before.endsWith("\n"))
37
+ return `${before}\n${block}\n`;
38
+ return `${before}\n\n${block}\n`;
39
+ });
40
+ return success({
41
+ missing,
42
+ diff: unifiedDiff(ENV_EXAMPLE_FILE, before === "" ? null : before, after),
43
+ after,
44
+ });
45
+ }
46
+ /** Writes the planned `.env.example`, or returns its diff under `dryRun`. */
47
+ export async function fixEnv(root, options) {
48
+ let planned = await planEnvFix(root);
49
+ if (isFailure(planned))
50
+ return planned;
51
+ if (planned.data.missing.length === 0) {
52
+ return success({ missing: [], diff: "" });
53
+ }
54
+ if (!options.dryRun) {
55
+ await writeFile(join(root, ENV_EXAMPLE_FILE), planned.data.after);
56
+ }
57
+ return success({ missing: planned.data.missing, diff: planned.data.diff });
58
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Repairs `sdxc doctor` findings the kit can apply safely: command-shaped fixes, missing
3
+ * `.env.example` secrets, and unambiguous model or email registration.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ export { fixCommands, parseFixCommand } from "./commands.js";
9
+ export { fixEmails } from "./emails.js";
10
+ export { fixEnv, planEnvFix } from "./env.js";
11
+ export { fixModels } from "./models.js";
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Repairs `sdxc doctor` findings the kit can apply safely: command-shaped fixes, missing
3
+ * `.env.example` secrets, and unambiguous model or email registration.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ export { fixCommands, parseFixCommand } from "./commands.js";
9
+ export { fixEmails } from "./emails.js";
10
+ export { fixEnv, planEnvFix } from "./env.js";
11
+ export { fixModels } from "./models.js";
@@ -0,0 +1,20 @@
1
+ /**
2
+ * `sdxc fix models`: registers every `createModel` module under `app/models/` that
3
+ * `app/models/index.ts` leaves out, through the same codemod `sdxc make model` uses.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ import type { Result } from "@sdxc/result";
9
+ /** One registration the fix applies. */
10
+ export interface ModelFix {
11
+ file: string;
12
+ diffs: string[];
13
+ }
14
+ /**
15
+ * Registers each unregistered model module. Refuses a file whose declaration cannot be placed
16
+ * automatically, naming the manual instructions.
17
+ */
18
+ export declare function fixModels(root: string, options: {
19
+ dryRun: boolean;
20
+ }): Promise<Result<ModelFix[], Error>>;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * `sdxc fix models`: registers every `createModel` module under `app/models/` that
3
+ * `app/models/index.ts` leaves out, through the same codemod `sdxc make model` uses.
4
+ *
5
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
6
+ * @copyright Sergio Xalambrí 2026
7
+ */
8
+ import { readFile, writeFile } from "node:fs/promises";
9
+ import { join, posix } from "node:path";
10
+ import { findModuleReferences } from "@sdxc/codemod";
11
+ import { failure, isFailure, success, wrap } from "@sdxc/result";
12
+ import { unifiedDiff } from "../diff.js";
13
+ import { isAppSource, listFiles } from "../doctor/files.js";
14
+ import { MODELS_INDEX } from "../doctor/models.js";
15
+ import { declare } from "../make/declare.js";
16
+ import { parseName } from "../make/names.js";
17
+ /** A module extension a specifier may carry or leave out. */
18
+ const EXTENSION = /\.[cm]?[jt]sx?$/;
19
+ /** A `createModel(` call, which is what makes a module a model rather than a helper beside one. */
20
+ const CREATES_MODEL = /\bcreateModel\s*\(/;
21
+ /**
22
+ * Registers each unregistered model module. Refuses a file whose declaration cannot be placed
23
+ * automatically, naming the manual instructions.
24
+ */
25
+ export async function fixModels(root, options) {
26
+ let missing = await unregisteredModels(root);
27
+ if (isFailure(missing))
28
+ return missing;
29
+ if (missing.data.length === 0)
30
+ return success([]);
31
+ let fixed = [];
32
+ for (let file of missing.data) {
33
+ let relative = file.replace(EXTENSION, "");
34
+ let segments = relative.replace(/^app\/models\//, "");
35
+ let name = parseName(segments);
36
+ if (isFailure(name))
37
+ return name;
38
+ let declared = await declare({
39
+ kind: "model",
40
+ name: name.data,
41
+ variant: null,
42
+ method: "get",
43
+ routes: "web",
44
+ handler: relative,
45
+ tool: name.data.snake,
46
+ uri: "",
47
+ title: name.data.title,
48
+ }, root);
49
+ if (declared.kind === "manual") {
50
+ return failure(new Error(`Cannot register ${file} automatically (${declared.reason}):\n${declared.instructions}`));
51
+ }
52
+ let diffs = [];
53
+ for (let edit of declared.edits) {
54
+ diffs.push(unifiedDiff(edit.path, edit.before, edit.after));
55
+ if (!options.dryRun)
56
+ await writeFile(join(root, edit.path), edit.after);
57
+ }
58
+ fixed.push({ file, diffs });
59
+ }
60
+ return success(fixed);
61
+ }
62
+ /** Model modules under `app/models/` that `createModels` does not import. */
63
+ async function unregisteredModels(root) {
64
+ let index = await wrap(() => readFile(join(root, MODELS_INDEX), "utf8"));
65
+ if (isFailure(index))
66
+ return failure(new Error(`No ${MODELS_INDEX} in the project`));
67
+ let references = findModuleReferences(MODELS_INDEX, index.data);
68
+ if (isFailure(references))
69
+ return failure(new Error(`${MODELS_INDEX} could not be read`));
70
+ let registered = new Set(references.data.map(({ specifier }) => modulePath(specifier)).filter((path) => path !== null));
71
+ let models = [];
72
+ for (let file of (await listFiles(root, "app/models")).filter(isAppSource)) {
73
+ if (file === MODELS_INDEX)
74
+ continue;
75
+ let source = await wrap(() => readFile(join(root, file), "utf8"));
76
+ if (isFailure(source) || !CREATES_MODEL.test(source.data))
77
+ continue;
78
+ let bare = file.replace(EXTENSION, "");
79
+ if (!registered.has(bare) && !registered.has(bare.replace(/\/index$/, ""))) {
80
+ models.push(file);
81
+ }
82
+ }
83
+ return success(models);
84
+ }
85
+ /** Project path a registry specifier names, or `null` for a package. */
86
+ function modulePath(specifier) {
87
+ let path;
88
+ if (specifier.startsWith("~/app/"))
89
+ path = specifier.slice(2);
90
+ else if (specifier.startsWith("."))
91
+ path = posix.join("app/models", specifier);
92
+ else
93
+ return null;
94
+ return posix.normalize(path).replace(EXTENSION, "");
95
+ }
package/dist/lock.js CHANGED
@@ -160,7 +160,13 @@ export function renderLock(lock) {
160
160
  continue;
161
161
  }
162
162
  let { kind, name, release, files } = line.entry;
163
- let ordered = Object.fromEntries(Object.entries(files).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
163
+ let ordered = Object.fromEntries(Object.entries(files).sort(([a], [b]) => {
164
+ if (a < b)
165
+ return -1;
166
+ if (a > b)
167
+ return 1;
168
+ return 0;
169
+ }));
164
170
  let rendered = JSONL.stringify([{ kind, name, release, files: ordered }]);
165
171
  if (isFailure(rendered))
166
172
  return rendered;
@@ -191,7 +197,11 @@ export async function writeLock(root, lock) {
191
197
  function compareLines(a, b) {
192
198
  let left = `${a.kind}\0${a.name}`;
193
199
  let right = `${b.kind}\0${b.name}`;
194
- return left < right ? -1 : left > right ? 1 : 0;
200
+ if (left < right)
201
+ return -1;
202
+ if (left > right)
203
+ return 1;
204
+ return 0;
195
205
  }
196
206
  /**
197
207
  * `text` as the byte source {@link JSONL.lines} reads.
@@ -0,0 +1,42 @@
1
+ /**
2
+ * `sdxc make secret`, `make binding` and `make do`: edit `cloudflare.config.ts`, append
3
+ * `.env.example` for secrets, re-export a Durable Object from `bootstrap/worker.ts`, and print
4
+ * `sdxc run typegen` so agents stop hand-editing three places.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import type { AnyCommandContext } from "@sdxc/cli";
10
+ import type { Result } from "@sdxc/result";
11
+ /** Binding kinds `make binding` accepts; `secret` also appends `.env.example`. */
12
+ export declare const BINDING_KINDS: readonly ["secret", "kv", "d1", "r2", "queue", "rateLimit", "sendEmail", "durableObject"];
13
+ /** One of {@link BINDING_KINDS}. */
14
+ export type BindingKind = (typeof BINDING_KINDS)[number];
15
+ /** Where a Durable Object class lives. */
16
+ export type DoRole = "model" | "service";
17
+ /** Context these makers need to print. */
18
+ export type BindingContext = Pick<AnyCommandContext, "stdout">;
19
+ /** Plans and optionally writes a `bindings.<kind>()` entry for `NAME`. */
20
+ export declare function makeBinding(ctx: BindingContext, root: string, input: {
21
+ kind: BindingKind;
22
+ name: string;
23
+ dryRun: boolean;
24
+ force: boolean;
25
+ }): Promise<Result<void, Error>>;
26
+ /** `make secret NAME` — shorthand for `make binding secret NAME`. */
27
+ export declare function makeSecret(ctx: BindingContext, root: string, input: {
28
+ name: string;
29
+ dryRun: boolean;
30
+ force: boolean;
31
+ }): Promise<Result<void, Error>>;
32
+ /**
33
+ * Writes a Durable Object class stub, re-exports it from `bootstrap/worker.ts`, and declares
34
+ * the binding plus `exports.durableObject` in `cloudflare.config.ts`.
35
+ */
36
+ export declare function makeDo(ctx: BindingContext, root: string, packageRoot: string, input: {
37
+ name: string;
38
+ role: DoRole;
39
+ binding?: string;
40
+ dryRun: boolean;
41
+ force: boolean;
42
+ }): Promise<Result<void, Error>>;