@sdxc/kit 2026.10.21 → 2026.10.24

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 (113) hide show
  1. package/README.md +84 -4
  2. package/changelog.jsonl +168 -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 +11 -8
  103. package/registry/ui/attachment.json +2 -2
  104. package/registry/ui/breadcrumbs.json +6 -3
  105. package/registry/ui/group.json +6 -3
  106. package/registry/ui/link-button.json +3 -3
  107. package/registry/ui/link.json +6 -3
  108. package/registry/ui/nav-link.json +6 -3
  109. package/registry/ui/navigation-menu.json +6 -3
  110. package/registry/ui/pagination.json +3 -3
  111. package/registry/ui/sidebar.json +3 -3
  112. package/templates/app/AGENTS.md +14 -1
  113. package/templates/app/package.json +1 -1
@@ -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>>;
@@ -0,0 +1,237 @@
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 { mkdir, readFile, writeFile } from "node:fs/promises";
10
+ import { dirname, join } from "node:path";
11
+ import { failure, isFailure, success, wrap } from "@sdxc/result";
12
+ import { addHeaderTags, headerTags, resolveAuthor } from "../author.js";
13
+ import { unifiedDiff } from "../diff.js";
14
+ import { CONFIG_FILE, ENV_EXAMPLE_FILE, declaredBindings, exampleKeys } from "../doctor/env.js";
15
+ import { parseName } from "./names.js";
16
+ /** Binding kinds `make binding` accepts; `secret` also appends `.env.example`. */
17
+ export const BINDING_KINDS = [
18
+ "secret",
19
+ "kv",
20
+ "d1",
21
+ "r2",
22
+ "queue",
23
+ "rateLimit",
24
+ "sendEmail",
25
+ "durableObject",
26
+ ];
27
+ /** Plans and optionally writes a `bindings.<kind>()` entry for `NAME`. */
28
+ export async function makeBinding(ctx, root, input) {
29
+ let key = bindingKey(input.name);
30
+ if (isFailure(key))
31
+ return key;
32
+ let config = await wrap(() => readFile(join(root, CONFIG_FILE), "utf8"));
33
+ if (isFailure(config))
34
+ return failure(new Error(`No ${CONFIG_FILE} in the project`));
35
+ let existing = declaredBindings(config.data);
36
+ if (existing.has(key.data) && !input.force) {
37
+ return failure(new Error(`${key.data} is already declared in ${CONFIG_FILE}; pass --force to replace it`));
38
+ }
39
+ let bindingLine = bindingCall(input.kind, key.data);
40
+ let afterConfig = insertEnvBinding(config.data, key.data, bindingLine);
41
+ if (isFailure(afterConfig))
42
+ return afterConfig;
43
+ let exampleEdit = null;
44
+ if (input.kind === "secret") {
45
+ let example = await wrap(() => readFile(join(root, ENV_EXAMPLE_FILE), "utf8"));
46
+ let before = isFailure(example) ? "" : example.data;
47
+ if (!exampleKeys(before).has(key.data)) {
48
+ let after;
49
+ if (before === "")
50
+ after = `${key.data}=\n`;
51
+ else if (before.endsWith("\n"))
52
+ after = `${before}${key.data}=\n`;
53
+ else
54
+ after = `${before}\n${key.data}=\n`;
55
+ exampleEdit = { before, after };
56
+ }
57
+ }
58
+ if (input.dryRun) {
59
+ ctx.stdout(unifiedDiff(CONFIG_FILE, config.data, afterConfig.data));
60
+ if (exampleEdit !== null) {
61
+ ctx.stdout(unifiedDiff(ENV_EXAMPLE_FILE, exampleEdit.before === "" ? null : exampleEdit.before, exampleEdit.after));
62
+ }
63
+ return success(undefined);
64
+ }
65
+ await writeFile(join(root, CONFIG_FILE), afterConfig.data);
66
+ ctx.stdout(`edited ${CONFIG_FILE}\n`);
67
+ if (exampleEdit !== null) {
68
+ await writeFile(join(root, ENV_EXAMPLE_FILE), exampleEdit.after);
69
+ ctx.stdout(`edited ${ENV_EXAMPLE_FILE}\n`);
70
+ }
71
+ ctx.stdout("Next: sdxc run typegen\n");
72
+ return success(undefined);
73
+ }
74
+ /** `make secret NAME` — shorthand for `make binding secret NAME`. */
75
+ export async function makeSecret(ctx, root, input) {
76
+ return makeBinding(ctx, root, { ...input, kind: "secret" });
77
+ }
78
+ /**
79
+ * Writes a Durable Object class stub, re-exports it from `bootstrap/worker.ts`, and declares
80
+ * the binding plus `exports.durableObject` in `cloudflare.config.ts`.
81
+ */
82
+ export async function makeDo(ctx, root, packageRoot, input) {
83
+ let parsed = parseName(input.name);
84
+ if (isFailure(parsed))
85
+ return parsed;
86
+ let className = parsed.data.pascal.endsWith("DO")
87
+ ? parsed.data.pascal
88
+ : `${parsed.data.pascal}DO`;
89
+ let binding = input.binding !== undefined
90
+ ? bindingKey(input.binding)
91
+ : success(snakeUpper(parsed.data.base.replace(/-?do$/, "") || parsed.data.base));
92
+ if (isFailure(binding))
93
+ return binding;
94
+ let folder = input.role === "model" ? "app/models" : "app/services";
95
+ let file = `${folder}/${parsed.data.segments.join("/")}.ts`;
96
+ let stub = addHeaderTags(durableObjectStub(className), headerTags(await resolveAuthor(join(root, dirname(file)))));
97
+ let config = await wrap(() => readFile(join(root, CONFIG_FILE), "utf8"));
98
+ if (isFailure(config))
99
+ return failure(new Error(`No ${CONFIG_FILE} in the project`));
100
+ let worker = await wrap(() => readFile(join(root, "bootstrap/worker.ts"), "utf8"));
101
+ if (isFailure(worker))
102
+ return failure(new Error("No bootstrap/worker.ts in the project"));
103
+ let existing = declaredBindings(config.data);
104
+ if (existing.has(binding.data) && !input.force) {
105
+ return failure(new Error(`${binding.data} is already declared in ${CONFIG_FILE}; pass --force`));
106
+ }
107
+ let afterConfig = insertDurableObject(config.data, binding.data, className);
108
+ if (isFailure(afterConfig))
109
+ return afterConfig;
110
+ let exportLine = `export { ${className} } from "~/${file.replace(/\.ts$/, "")}";\n`;
111
+ let afterWorker = worker.data.includes(`export { ${className} }`)
112
+ ? worker.data
113
+ : `${worker.data.trimEnd()}\n\n${exportLine}`;
114
+ if (input.dryRun) {
115
+ ctx.stdout(unifiedDiff(file, null, stub));
116
+ ctx.stdout(unifiedDiff(CONFIG_FILE, config.data, afterConfig.data));
117
+ ctx.stdout(unifiedDiff("bootstrap/worker.ts", worker.data, afterWorker));
118
+ return success(undefined);
119
+ }
120
+ await mkdir(dirname(join(root, file)), { recursive: true });
121
+ let written = await wrap(() => writeFile(join(root, file), stub, { flag: input.force ? "w" : "wx" }));
122
+ if (isFailure(written)) {
123
+ if (written.error.code === "EEXIST") {
124
+ return failure(new Error(`${file} already exists; pass --force to replace it`));
125
+ }
126
+ return written;
127
+ }
128
+ ctx.stdout(`wrote ${file}\n`);
129
+ await writeFile(join(root, CONFIG_FILE), afterConfig.data);
130
+ ctx.stdout(`edited ${CONFIG_FILE}\n`);
131
+ await writeFile(join(root, "bootstrap/worker.ts"), afterWorker);
132
+ ctx.stdout("edited bootstrap/worker.ts\n");
133
+ ctx.stdout("Next: sdxc run typegen\n");
134
+ void packageRoot;
135
+ return success(undefined);
136
+ }
137
+ /** `NAME` as an env binding key: already `SCREAMING_SNAKE` or derived from kebab/camel. */
138
+ function bindingKey(name) {
139
+ if (/^[A-Z][A-Z0-9_]*$/.test(name))
140
+ return success(name);
141
+ let parsed = parseName(name.replaceAll("_", "-"));
142
+ if (isFailure(parsed)) {
143
+ return failure(new Error(`"${name}" is not a binding name`));
144
+ }
145
+ return success(snakeUpper(parsed.data.base));
146
+ }
147
+ function snakeUpper(kebab) {
148
+ return kebab.replaceAll("-", "_").toUpperCase();
149
+ }
150
+ function bindingCall(kind, key) {
151
+ if (kind === "secret")
152
+ return `${key}: bindings.secret()`;
153
+ if (kind === "sendEmail")
154
+ return `${key}: bindings.sendEmail()`;
155
+ if (kind === "rateLimit") {
156
+ return `${key}: bindings.rateLimit({ namespace: "1001", simple: { limit: 100, period: 60 } })`;
157
+ }
158
+ if (kind === "kv") {
159
+ return `${key}: bindings.kv({ id: "00000000000000000000000000000000" })`;
160
+ }
161
+ if (kind === "d1") {
162
+ return `${key}: bindings.d1({ name: manifest.name, id: "00000000-0000-4000-8000-000000000000" })`;
163
+ }
164
+ if (kind === "r2")
165
+ return `${key}: bindings.r2({ name: "${key.toLowerCase()}" })`;
166
+ if (kind === "queue")
167
+ return `${key}: bindings.queue({ name: manifest.name })`;
168
+ return `${key}: bindings.durableObject({ worker: /* self */, exportName: "TODO" })`;
169
+ }
170
+ /** Inserts a binding property into the Worker's `env: { … }` object. */
171
+ function insertEnvBinding(source, key, line) {
172
+ let env = /env\s*:\s*\{/.exec(source);
173
+ if (env === null || env.index === undefined) {
174
+ return failure(new Error(`${CONFIG_FILE} has no env: { … } block to edit`));
175
+ }
176
+ let start = env.index + env[0].length;
177
+ let stripped = source.replace(new RegExp(`(?:^|\\n)(\\s*)${key}\\s*:\\s*bindings\\.\\w+\\s*\\([^)]*\\)\\s*,?`, "m"), "\n");
178
+ let envAgain = /env\s*:\s*\{/.exec(stripped);
179
+ if (envAgain === null || envAgain.index === undefined) {
180
+ return failure(new Error(`${CONFIG_FILE} env block could not be re-found after cleanup`));
181
+ }
182
+ start = envAgain.index + envAgain[0].length;
183
+ let indent = "\t\t\t";
184
+ return success(`${stripped.slice(0, start)}\n${indent}${line},${stripped.slice(start)}`);
185
+ }
186
+ /** Declares the DO export and env binding in `cloudflare.config.ts`. */
187
+ function insertDurableObject(source, binding, className) {
188
+ let withExport = source;
189
+ if (!source.includes(`exports`) || !/exports\s*:\s*\{/.test(source)) {
190
+ let worker = /worker\s*:\s*\{/.exec(source);
191
+ if (worker === null || worker.index === undefined) {
192
+ return failure(new Error(`${CONFIG_FILE} has no worker: { … } block`));
193
+ }
194
+ let insertAt = worker.index + worker[0].length;
195
+ withExport = `${source.slice(0, insertAt)}\n\t\texports: {\n\t\t\t${className}: exports.durableObject({ storage: "sqlite" }),\n\t\t},${source.slice(insertAt)}`;
196
+ if (!/import\s*\{[^}]*\bexports\b/.test(withExport) &&
197
+ withExport.includes('from "cf/config"')) {
198
+ withExport = withExport.replace(/import\s*\{([^}]+)\}\s*from\s*"cf\/config"/, (_match, names) => {
199
+ let list = names.split(",").map((part) => part.trim());
200
+ if (!list.includes("exports"))
201
+ list.push("exports");
202
+ return `import { ${list.join(", ")} } from "cf/config"`;
203
+ });
204
+ }
205
+ }
206
+ else if (!withExport.includes(`${className}:`)) {
207
+ let exportsBlock = /exports\s*:\s*\{/.exec(withExport);
208
+ if (exportsBlock === null || exportsBlock.index === undefined) {
209
+ return failure(new Error(`${CONFIG_FILE} exports block is malformed`));
210
+ }
211
+ let at = exportsBlock.index + exportsBlock[0].length;
212
+ withExport = `${withExport.slice(0, at)}\n\t\t\t${className}: exports.durableObject({ storage: "sqlite" }),${withExport.slice(at)}`;
213
+ }
214
+ let line = `${binding}: bindings.durableObject({ worker: manifest.name, exportName: "${className}" })`;
215
+ return insertEnvBinding(withExport, binding, line);
216
+ }
217
+ /** Minimal Durable Object class stub; `@author` / `@copyright` are added by {@link makeDo}. */
218
+ function durableObjectStub(className) {
219
+ return `/**
220
+ * The ${className} Durable Object: fill in its storage and request handlers.
221
+ */
222
+
223
+ import { DurableObject } from "cloudflare:workers";
224
+
225
+ /** Durable Object class re-exported from bootstrap/worker.ts for its binding. */
226
+ export class ${className} extends DurableObject<Cloudflare.Env> {
227
+ /**
228
+ * Handles a fetch against this object.
229
+ *
230
+ * @param request - The inbound request.
231
+ */
232
+ async fetch(request: Request): Promise<Response> {
233
+ return new Response("${className}", { status: 200 });
234
+ }
235
+ }
236
+ `;
237
+ }
@@ -38,11 +38,13 @@ export function ensureImport(filename, source, what, matches, specifier, preferr
38
38
  });
39
39
  }
40
40
  }
41
- let clause = what.kind === "namespace"
42
- ? `* as ${preferred}`
43
- : what.kind === "default"
44
- ? preferred
45
- : `{ ${what.name} }`;
41
+ let clause;
42
+ if (what.kind === "namespace")
43
+ clause = `* as ${preferred}`;
44
+ else if (what.kind === "default")
45
+ clause = preferred;
46
+ else
47
+ clause = `{ ${what.name} }`;
46
48
  let local = what.kind === "named" ? what.name : preferred;
47
49
  let statement = `import ${clause} from ${literal(specifier)};`;
48
50
  return success({ source: insertImport(source, references.data, statement), local });
@@ -7,6 +7,7 @@
7
7
  * @copyright Sergio Xalambrí 2026
8
8
  */
9
9
  import { DatabaseSync } from "node:sqlite";
10
+ import { iife } from "@sdxc/iife";
10
11
  import { failure, isFailure, success, wrap } from "@sdxc/result";
11
12
  import { checksOf, columnClause, createTable, createTableStatement, defaultClause, isKey, isNotNull, quote, uniqueIndex, } from "./schema.js";
12
13
  /**
@@ -199,7 +200,13 @@ function diffTable(db, table, current) {
199
200
  * `INTEGER PRIMARY KEY` as nullable.
200
201
  */
201
202
  function columnDifference(table, name, definition, existing) {
202
- let generated = definition.computed === undefined ? 0 : definition.computed.stored ? 3 : 2;
203
+ let generated = iife(() => {
204
+ if (definition.computed === undefined)
205
+ return 0;
206
+ if (definition.computed.stored)
207
+ return 3;
208
+ return 2;
209
+ });
203
210
  let hidden = existing.hidden === 2 || existing.hidden === 3 ? existing.hidden : 0;
204
211
  if (generated !== hidden)
205
212
  return "changes how it is generated";
package/dist/models.js CHANGED
@@ -36,13 +36,13 @@ async function modelFiles(root) {
36
36
  function columnsOf(table) {
37
37
  return Object.entries(table.columns).map(([name, definition]) => {
38
38
  let reference = definition.references;
39
- let key = table.primaryKey.includes(name)
40
- ? "primary"
41
- : reference !== undefined
42
- ? `${reference.table.name}.${reference.columns.join(", ")}`
43
- : definition.unique !== undefined && definition.unique !== false
44
- ? "unique"
45
- : null;
39
+ let key = null;
40
+ if (table.primaryKey.includes(name))
41
+ key = "primary";
42
+ else if (reference !== undefined)
43
+ key = `${reference.table.name}.${reference.columns.join(", ")}`;
44
+ else if (definition.unique !== undefined && definition.unique !== false)
45
+ key = "unique";
46
46
  return {
47
47
  name,
48
48
  type: definition.type,
@@ -9,6 +9,7 @@
9
9
  import { readFile, stat } from "node:fs/promises";
10
10
  import { join, posix } from "node:path";
11
11
  import { findModuleReferences, tokenize } from "@sdxc/codemod";
12
+ import { iife } from "@sdxc/iife";
12
13
  import { isFailure, isSuccess, wrap } from "@sdxc/result";
13
14
  import { applyHelper, helperName } from "./helpers.js";
14
15
  import { Reader } from "./parse.js";
@@ -201,11 +202,13 @@ export class Project {
201
202
  let tokens = tokenize(path, source.data);
202
203
  let references = findModuleReferences(path, source.data);
203
204
  if (isFailure(tokens) || isFailure(references)) {
204
- let error = isFailure(tokens)
205
- ? tokens.error
206
- : isFailure(references)
207
- ? references.error
208
- : null;
205
+ let error = iife(() => {
206
+ if (isFailure(tokens))
207
+ return tokens.error;
208
+ if (isFailure(references))
209
+ return references.error;
210
+ return null;
211
+ });
209
212
  this.diagnostics.push(`${path}: could not be read (${error?.message ?? "unknown error"})`);
210
213
  return null;
211
214
  }
@@ -188,8 +188,9 @@ export class Reader {
188
188
  }
189
189
  }
190
190
  /** `[async] function name(…) { … }` at `index`, as a function node, or `null`. */
191
- functionDeclaration(index, limit) {
192
- let start = index;
191
+ functionDeclaration(at, limit) {
192
+ let start = at;
193
+ let index = at;
193
194
  if (this.isWord(index, "async"))
194
195
  index += 1;
195
196
  if (!this.isWord(index, "function"))
@@ -436,11 +437,11 @@ export class Reader {
436
437
  index = this.afterComma(this.skipToDelimiter(index + 1, close), close);
437
438
  continue;
438
439
  }
439
- let name = key?.type === "identifier" || key?.type === "number"
440
- ? key.value
441
- : key?.type === "string"
442
- ? cook(key.value)
443
- : null;
440
+ let name = null;
441
+ if (key?.type === "identifier" || key?.type === "number")
442
+ name = key.value;
443
+ else if (key?.type === "string")
444
+ name = cook(key.value);
444
445
  if (name === null) {
445
446
  index = this.afterComma(this.skipToDelimiter(index, close), close);
446
447
  continue;
@@ -6,6 +6,7 @@
6
6
  * @author [Sergio Xalambrí](https://sergiodxa.com)
7
7
  * @copyright Sergio Xalambrí 2026
8
8
  */
9
+ import { iife } from "@sdxc/iife";
9
10
  /** The longest middleware expression shown whole; longer calls show as `callee(…)`. */
10
11
  const NAME_LIMIT = 40;
11
12
  /**
@@ -301,11 +302,14 @@ export async function middlewareList(project, module, node, seen = new Set()) {
301
302
  /** One middleware: its expression as written and the module its name comes from. */
302
303
  async function middlewareEntry(project, module, node) {
303
304
  let text = module.reader.text(node);
304
- let name = node.kind === "function"
305
- ? "(inline)"
306
- : text.length > NAME_LIMIT && node.kind === "call"
307
- ? `${module.reader.text(node.callee)}(…)`
308
- : text;
305
+ let name = iife(() => {
306
+ if (node.kind === "function")
307
+ return "(inline)";
308
+ if (text.length > NAME_LIMIT && node.kind === "call") {
309
+ return `${module.reader.text(node.callee)}(…)`;
310
+ }
311
+ return text;
312
+ });
309
313
  let root = node;
310
314
  while (root.kind === "call" || root.kind === "member") {
311
315
  root = root.kind === "call" ? root.callee : root.object;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `sdxc setup auth`: OIDC relying-party wiring against r3-auth (default), reduced to the
3
+ * template's session/`actor` world — initializer, middleware, controllers, routes, secrets and
4
+ * a `signIn()` test helper.
5
+ *
6
+ * @author [Sergio Xalambrí](https://sergiodxa.com)
7
+ * @copyright Sergio Xalambrí 2026
8
+ */
9
+ import type { Result } from "@sdxc/result";
10
+ import type { SetupPlan } from "./plan.js";
11
+ /** Builds the auth setup plan for `provider` (currently only `r3-auth`). */
12
+ export declare function planAuth(root: string, provider: string): Promise<Result<SetupPlan, Error>>;