@askrjs/cli 0.0.2 → 0.0.3

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 (96) hide show
  1. package/README.md +9 -7
  2. package/dist/add.js +554 -1
  3. package/dist/add.js.map +1 -0
  4. package/dist/cli.js +43 -14
  5. package/dist/cli.js.map +1 -1
  6. package/dist/discovery-Difb7Y4G.js +325 -0
  7. package/dist/discovery-Difb7Y4G.js.map +1 -0
  8. package/dist/generate.js +396 -0
  9. package/dist/generate.js.map +1 -0
  10. package/dist/openapi.js +5 -4
  11. package/dist/openapi.js.map +1 -1
  12. package/dist/planner-VAj7qlxr.js +287 -0
  13. package/dist/planner-VAj7qlxr.js.map +1 -0
  14. package/dist/range-YUs9eimn.js +127 -0
  15. package/dist/range-YUs9eimn.js.map +1 -0
  16. package/dist/registry-CyrRHRG5.js +211 -0
  17. package/dist/registry-CyrRHRG5.js.map +1 -0
  18. package/dist/skills/askr-dashboard-charts/SKILL.md +61 -44
  19. package/dist/skills/askr-dashboard-charts/agents/openai.yaml +2 -2
  20. package/dist/specification-DXnDOC-0.js +51 -0
  21. package/dist/specification-DXnDOC-0.js.map +1 -0
  22. package/dist/templates/full-stack/AGENTS.md +0 -1
  23. package/dist/templates/full-stack/README.md +0 -1
  24. package/dist/templates/full-stack/index.html +0 -1
  25. package/dist/templates/full-stack/package.json +4 -2
  26. package/dist/templates/full-stack/server.ts +5 -9
  27. package/dist/templates/full-stack/src/action-authorizations.ts +2 -2
  28. package/dist/templates/full-stack/src/actions/create-message.ts +5 -5
  29. package/dist/templates/full-stack/src/i18n.ts +4 -4
  30. package/dist/templates/full-stack/src/main.tsx +4 -5
  31. package/dist/templates/full-stack/src/pages/home.tsx +5 -5
  32. package/dist/templates/full-stack/src/pages/layout.tsx +15 -5
  33. package/dist/templates/full-stack/src/pages/not-found.tsx +5 -2
  34. package/dist/templates/full-stack/src/routes.tsx +11 -12
  35. package/dist/templates/full-stack/src/schemas.ts +1 -2
  36. package/dist/templates/full-stack/src/server/action-registry.ts +6 -10
  37. package/dist/templates/full-stack/src/server/actions/create-message.ts +4 -4
  38. package/dist/templates/full-stack/src/server/app.ts +67 -57
  39. package/dist/templates/full-stack/src/server/dependencies.ts +10 -10
  40. package/dist/templates/full-stack/src/server/entry-server.ts +3 -3
  41. package/dist/templates/full-stack/src/telemetry.ts +1 -2
  42. package/dist/templates/full-stack/src/vite-server.d.ts +2 -3
  43. package/dist/templates/full-stack/tests/actions/create-message.test.ts +7 -8
  44. package/dist/templates/full-stack/tsconfig.json +0 -1
  45. package/dist/templates/full-stack/vite.config.ts +5 -6
  46. package/dist/templates/spa/AGENTS.md +1 -1
  47. package/dist/templates/spa/package.json +1 -1
  48. package/dist/templates/spa/src/adapters/operations-client.ts +7 -2
  49. package/dist/templates/spa/src/pages/app/admin-home.tsx +21 -3
  50. package/dist/templates/spa/src/styles.css +1 -1
  51. package/dist/templates/ssg/tests/ssg-config.test.ts +3 -3
  52. package/dist/templates/ssr/server.ts +4 -10
  53. package/dist/templates/ssr/src/entry-server.tsx +6 -4
  54. package/dist/update.js +284 -2
  55. package/dist/update.js.map +1 -0
  56. package/dist/writer-D8qe_7ud.js +228 -0
  57. package/dist/writer-D8qe_7ud.js.map +1 -0
  58. package/package.json +11 -15
  59. package/skills/askr-dashboard-charts/SKILL.md +61 -44
  60. package/skills/askr-dashboard-charts/agents/openai.yaml +2 -2
  61. package/templates/full-stack/AGENTS.md +0 -1
  62. package/templates/full-stack/README.md +0 -1
  63. package/templates/full-stack/index.html +0 -1
  64. package/templates/full-stack/package.json +4 -2
  65. package/templates/full-stack/server.ts +5 -9
  66. package/templates/full-stack/src/action-authorizations.ts +2 -2
  67. package/templates/full-stack/src/actions/create-message.ts +5 -5
  68. package/templates/full-stack/src/i18n.ts +4 -4
  69. package/templates/full-stack/src/main.tsx +4 -5
  70. package/templates/full-stack/src/pages/home.tsx +5 -5
  71. package/templates/full-stack/src/pages/layout.tsx +15 -5
  72. package/templates/full-stack/src/pages/not-found.tsx +5 -2
  73. package/templates/full-stack/src/routes.tsx +11 -12
  74. package/templates/full-stack/src/schemas.ts +1 -2
  75. package/templates/full-stack/src/server/action-registry.ts +6 -10
  76. package/templates/full-stack/src/server/actions/create-message.ts +4 -4
  77. package/templates/full-stack/src/server/app.ts +67 -57
  78. package/templates/full-stack/src/server/dependencies.ts +10 -10
  79. package/templates/full-stack/src/server/entry-server.ts +3 -3
  80. package/templates/full-stack/src/telemetry.ts +1 -2
  81. package/templates/full-stack/src/vite-server.d.ts +2 -3
  82. package/templates/full-stack/tests/actions/create-message.test.ts +7 -8
  83. package/templates/full-stack/tsconfig.json +0 -1
  84. package/templates/full-stack/vite.config.ts +5 -6
  85. package/templates/spa/AGENTS.md +1 -1
  86. package/templates/spa/package.json +1 -1
  87. package/templates/spa/src/adapters/operations-client.ts +7 -2
  88. package/templates/spa/src/pages/app/admin-home.tsx +21 -3
  89. package/templates/spa/src/styles.css +1 -1
  90. package/templates/ssg/tests/ssg-config.test.ts +3 -3
  91. package/templates/ssr/server.ts +4 -10
  92. package/templates/ssr/src/entry-server.tsx +6 -4
  93. package/dist/add-DqhqRzBQ.js +0 -555
  94. package/dist/add-DqhqRzBQ.js.map +0 -1
  95. package/dist/update-DyW1na5V.js +0 -1140
  96. package/dist/update-DyW1na5V.js.map +0 -1
package/README.md CHANGED
@@ -43,7 +43,9 @@ unless you opt out with `--no-skills`.
43
43
  - `askr skills sync [--cwd <dir>]`
44
44
  - `askr ssg --config <path> --output <dir> [--incremental]`
45
45
  - `askr openapi [--entry ./src/api.ts] [--output ./openapi.yml] [--check]`
46
- - `askr update [packages...] [-u] [-f] [--workspace <glob>] [--tag <tag>] [--json]`
46
+ - `askr outdated [packages...] [--workspace <glob>] [--tag <tag>] [--json]`
47
+ - `askr update [packages...] [--workspace <glob>] [--tag <tag>] [--json]`
48
+ - `askr upgrade [packages...] [--workspace <glob>] [--tag <tag>] [--json]`
47
49
 
48
50
  The installed command is `askr`. Subcommands are intentionally not published
49
51
  as compatibility binaries.
@@ -69,24 +71,24 @@ registers it in route-first SPA branches (`src/pages/app/_routes.tsx` or
69
71
 
70
72
  ## Dependency updates
71
73
 
72
- `askr update` is an Askr-owned, dry-run-first dependency updater. It discovers
73
- the containing npm or pnpm workspace from nested directories, includes the root
74
+ The dependency commands are Askr-owned and discover
75
+ the containing npm or pnpm workspace from nested directories, include the root
74
76
  manifest and declared workspaces, and reports safe, breaking, local, manual,
75
77
  and failed decisions without running an install.
76
78
 
77
79
  ```bash
80
+ askr outdated
78
81
  askr update
79
- askr update -u
80
- askr update -u -f
82
+ askr upgrade
81
83
  askr update vite "@types/*"
82
84
  askr update --workspace "@scope/app" --tag next --json
83
85
  ```
84
86
 
85
- `-u` writes compatible range changes. `-u -f` additionally permits breaking
87
+ `askr update` writes safe range changes. `askr upgrade` additionally permits next-version
86
88
  major changes for stable packages and breaking minor changes for `0.x`
87
89
  packages. Peer requirements from co-dependencies are still enforced: a target
88
90
  is left for manual review if it would move outside another selected package's
89
- published peer range. Force never bypasses that compatibility guard.
91
+ published peer range. `askr upgrade` never bypasses that compatibility guard.
90
92
 
91
93
  The updater preserves exact, caret, tilde, and x-range styles. It can widen one
92
94
  bounded interval, and it updates only the highest clause of a simple OR union.
package/dist/add.js CHANGED
@@ -1,3 +1,556 @@
1
1
  #!/usr/bin/env node
2
- import { t as runAddCli } from "./add-DqhqRzBQ.js";
2
+ import { t as isDirectExecution } from "./is-direct-execution-Cdlr-ZUl.js";
3
+ import fs from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { randomUUID } from "node:crypto";
6
+ //#region src/file-changes.ts
7
+ async function remove(paths) {
8
+ await Promise.all(paths.map((filePath) => fs.rm(filePath, { force: true }).catch(() => void 0)));
9
+ }
10
+ async function restore(changes) {
11
+ let complete = true;
12
+ for (const change of [...changes].reverse()) try {
13
+ if (change.original === null) {
14
+ await fs.rm(change.filePath, { force: true });
15
+ continue;
16
+ }
17
+ const rollbackPath = path.join(path.dirname(change.filePath), `.${path.basename(change.filePath)}.askr-rollback-${randomUUID()}`);
18
+ await fs.writeFile(rollbackPath, change.original, {
19
+ flag: "wx",
20
+ mode: change.mode
21
+ });
22
+ await fs.rename(rollbackPath, change.filePath);
23
+ } catch {
24
+ complete = false;
25
+ }
26
+ return complete;
27
+ }
28
+ async function writeFileChanges(changes, options = {}) {
29
+ const ordered = [...changes].sort((left, right) => left.filePath.localeCompare(right.filePath));
30
+ if (new Set(ordered.map((change) => change.filePath)).size !== ordered.length) throw new Error("File changes contain duplicate target paths.");
31
+ const replace = options.replace ?? fs.rename;
32
+ const staged = [];
33
+ try {
34
+ for (const change of ordered) {
35
+ await fs.mkdir(path.dirname(change.filePath), { recursive: true });
36
+ const stat = await fs.stat(change.filePath).catch(() => null);
37
+ const original = stat ? await fs.readFile(change.filePath) : null;
38
+ const temporaryPath = path.join(path.dirname(change.filePath), `.${path.basename(change.filePath)}.askr-change-${randomUUID()}`);
39
+ const mode = stat?.mode ?? 420;
40
+ await fs.writeFile(temporaryPath, change.content, {
41
+ flag: "wx",
42
+ mode
43
+ });
44
+ staged.push({
45
+ ...change,
46
+ original,
47
+ mode,
48
+ temporaryPath
49
+ });
50
+ }
51
+ } catch (error) {
52
+ await remove(staged.map((change) => change.temporaryPath));
53
+ throw error;
54
+ }
55
+ const replaced = [];
56
+ try {
57
+ for (const change of staged) {
58
+ await replace(change.temporaryPath, change.filePath);
59
+ replaced.push(change);
60
+ }
61
+ } catch {
62
+ const complete = await restore(replaced);
63
+ await remove(staged.map((change) => change.temporaryPath));
64
+ throw new Error(complete ? "File replacement failed; completed changes were rolled back." : "File replacement failed and rollback was incomplete.");
65
+ }
66
+ }
67
+ //#endregion
68
+ //#region src/bin/add.ts
69
+ const BRANCH_CONFIG = {
70
+ app: {
71
+ badge: "app route",
72
+ pagesDir: [
73
+ "src",
74
+ "pages",
75
+ "app"
76
+ ],
77
+ routesFile: [
78
+ "src",
79
+ "pages",
80
+ "app",
81
+ "_routes.tsx"
82
+ ]
83
+ },
84
+ public: {
85
+ badge: "public route",
86
+ pagesDir: [
87
+ "src",
88
+ "pages",
89
+ "public"
90
+ ],
91
+ routesFile: [
92
+ "src",
93
+ "pages",
94
+ "public",
95
+ "_routes.tsx"
96
+ ]
97
+ }
98
+ };
99
+ function helpText() {
100
+ return [
101
+ "askr add - Generate code into an existing Askr project",
102
+ "",
103
+ "Usage:",
104
+ " askr add page <name> [--branch app|public] [--cwd <dir>] [--title <title>] [--route <path>] [--force]",
105
+ " askr add action <name> --route <path> [--cwd <dir>] [--force]",
106
+ "",
107
+ "Commands:",
108
+ " page Scaffold a route page and register it in a route-first SPA branch",
109
+ " action Scaffold a browser descriptor, server handler, registration, authorization, and test",
110
+ "",
111
+ "Options:",
112
+ " --branch <name> Route branch to target (default: app)",
113
+ " --cwd <dir> Project directory (default: current directory)",
114
+ " --title <text> Override the generated page title",
115
+ " --route <path> Override the generated route path",
116
+ " --force Overwrite an existing page file",
117
+ " --help Show this help message",
118
+ "",
119
+ "Examples:",
120
+ " askr add page audit-log",
121
+ " askr add page ops/audit-log --branch public",
122
+ " askr add page approvals --title \"Human approvals\" --route /app/approvals",
123
+ " askr add action approve-request --route /requests/{id}",
124
+ "",
125
+ "Notes:",
126
+ " Page generation supports route-first SPA projects created from `askr create spa`.",
127
+ " Action generation supports projects created from `askr create full-stack`."
128
+ ].join("\n");
129
+ }
130
+ function parseArgs(args) {
131
+ const positional = [];
132
+ const parsed = {
133
+ branch: "app",
134
+ cwd: process.cwd(),
135
+ force: false,
136
+ help: false,
137
+ routePath: "",
138
+ title: "",
139
+ errors: []
140
+ };
141
+ for (let index = 0; index < args.length; index += 1) {
142
+ const arg = args[index];
143
+ if (arg === "--help" || arg === "-h") parsed.help = true;
144
+ else if (arg === "--force") parsed.force = true;
145
+ else if (arg === "--branch") if (index + 1 >= args.length) parsed.errors.push("Missing value for --branch");
146
+ else {
147
+ parsed.branch = args[index + 1];
148
+ index += 1;
149
+ }
150
+ else if (arg === "--cwd") if (index + 1 >= args.length) parsed.errors.push("Missing value for --cwd");
151
+ else {
152
+ parsed.cwd = args[index + 1];
153
+ index += 1;
154
+ }
155
+ else if (arg === "--title") if (index + 1 >= args.length) parsed.errors.push("Missing value for --title");
156
+ else {
157
+ parsed.title = args[index + 1].trim();
158
+ index += 1;
159
+ }
160
+ else if (arg === "--route") if (index + 1 >= args.length) parsed.errors.push("Missing value for --route");
161
+ else {
162
+ parsed.routePath = args[index + 1].trim();
163
+ index += 1;
164
+ }
165
+ else positional.push(arg);
166
+ }
167
+ return {
168
+ ...parsed,
169
+ command: positional[0] || "",
170
+ name: positional[1] || ""
171
+ };
172
+ }
173
+ async function pathExists(filePath) {
174
+ return Boolean(await fs.stat(filePath).catch(() => null));
175
+ }
176
+ function slugifySegment(value) {
177
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
178
+ }
179
+ function normalizePageSegments(input) {
180
+ const segments = input.replace(/^\/+|\/+$/g, "").split("/").map((segment) => slugifySegment(segment.trim())).filter(Boolean);
181
+ if (segments.length === 0 || segments.some((segment) => segment.startsWith("_"))) return [];
182
+ return segments;
183
+ }
184
+ function toWords(segments) {
185
+ return segments.flatMap((segment) => segment.split("-").filter(Boolean));
186
+ }
187
+ function toTitleCase(words) {
188
+ return words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
189
+ }
190
+ function buildComponentName(segments) {
191
+ return `${toWords(segments).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("")}Page`;
192
+ }
193
+ function buildIdentifier(segments) {
194
+ const [first = "action", ...rest] = toWords(segments);
195
+ return [first.toLowerCase(), ...rest.map((word) => word.charAt(0).toUpperCase() + word.slice(1))].join("").replace(/^[^a-z_$]/i, "action");
196
+ }
197
+ function renderAuthorizationRegistry(actions) {
198
+ const imports = actions.map((action) => `import { ${action.descriptorName} } from './actions/${action.slug}.js';`);
199
+ const routes = /* @__PURE__ */ new Map();
200
+ for (const action of actions) {
201
+ const entries = routes.get(action.routePath) ?? [];
202
+ entries.push(action);
203
+ routes.set(action.routePath, entries);
204
+ }
205
+ const routeLines = [...routes].sort(([left], [right]) => left.localeCompare(right)).map(([routePath, entries]) => ` ${JSON.stringify(routePath)}: [${entries.map((entry) => entry.descriptorName).join(", ")}],`);
206
+ return [
207
+ "import type { ActionDescriptor } from '@askrjs/askr/actions';",
208
+ ...imports,
209
+ "",
210
+ "const actionsByRoute: Readonly<Record<string, readonly ActionDescriptor[]>> = Object.freeze({",
211
+ ...routeLines,
212
+ "});",
213
+ "",
214
+ "export function actionsFor(path: string): readonly ActionDescriptor[] {",
215
+ " return actionsByRoute[path] ?? [];",
216
+ "}",
217
+ ""
218
+ ].join("\n");
219
+ }
220
+ function renderServerActionRegistry(actions) {
221
+ return [
222
+ "import { defineServerActions, handleAction } from '@askrjs/server/askr';",
223
+ ...actions.map((action) => `import { ${action.descriptorName} } from '../actions/${action.slug}.js';`),
224
+ ...actions.map((action) => `import { ${action.handlerName} } from './actions/${action.slug}.js';`),
225
+ "import type { AppDependencies } from './dependencies.js';",
226
+ "",
227
+ "export function createActions(deps: AppDependencies) {",
228
+ " return defineServerActions({ dependencies: deps,",
229
+ " csrf: { secret: process.env.CSRF_SECRET ?? 'development-only-secret' },",
230
+ " },",
231
+ ...actions.map((action) => ` handleAction(${action.descriptorName}, ${action.handlerName}),`),
232
+ " );",
233
+ "}",
234
+ ""
235
+ ].join("\n");
236
+ }
237
+ async function discoverDeclaredActions(projectRoot, replacement) {
238
+ const actionsDir = path.join(projectRoot, "src", "actions");
239
+ const names = await fs.readdir(actionsDir).catch(() => []);
240
+ const files = new Set(names.filter((name) => name.endsWith(".ts")).map((name) => path.join(actionsDir, name)));
241
+ files.add(replacement.filePath);
242
+ const actions = [];
243
+ for (const filePath of [...files].sort()) {
244
+ const content = filePath === replacement.filePath ? replacement.content : await fs.readFile(filePath, "utf8");
245
+ const descriptor = /export const (\w+Action) = defineAction\(/.exec(content)?.[1];
246
+ if (!descriptor) continue;
247
+ const routeName = `${descriptor}Route`;
248
+ const routeMatch = new RegExp(`export const ${routeName} = (['"])(.*?)\\1;`).exec(content);
249
+ if (!routeMatch) throw new Error(`Action descriptor ${path.basename(filePath)} must declare ${routeName}.`);
250
+ const slug = path.basename(filePath, ".ts");
251
+ actions.push({
252
+ slug,
253
+ descriptorName: descriptor,
254
+ handlerName: buildIdentifier([slug]),
255
+ routePath: routeMatch[2]
256
+ });
257
+ }
258
+ return actions.sort((left, right) => left.slug.localeCompare(right.slug));
259
+ }
260
+ function renderActionDescriptor(options) {
261
+ return [
262
+ "import { defineAction } from '@askrjs/askr/actions';",
263
+ "import { schema } from '@askrjs/schema';",
264
+ "",
265
+ `export const ${options.descriptorName}Route = ${JSON.stringify(options.routePath)};`,
266
+ "",
267
+ `export const ${options.descriptorName} = defineAction({`,
268
+ ` id: '${options.slug}',`,
269
+ " input: schema.object({ value: schema.string({ minLength: 1 }) }),",
270
+ " invalidates: [],",
271
+ "});",
272
+ ""
273
+ ].join("\n");
274
+ }
275
+ function renderActionHandler(options) {
276
+ return [
277
+ "import type { InferSchema } from '@askrjs/schema';",
278
+ `import { ${options.descriptorName} } from '../../actions/${options.slug}.js';`,
279
+ "import type { AppDependencies } from '../dependencies.js';",
280
+ "",
281
+ `type Input = InferSchema<typeof ${options.descriptorName}.input>;`,
282
+ "",
283
+ `export async function ${options.handlerName}(`,
284
+ " _context: unknown,",
285
+ " input: Input,",
286
+ " deps: Pick<AppDependencies, 'actions'>,",
287
+ ") {",
288
+ " await deps.actions.record({ action: " + JSON.stringify(options.slug) + ", value: input.value });",
289
+ " return { result: { accepted: true } };",
290
+ "}",
291
+ ""
292
+ ].join("\n");
293
+ }
294
+ function renderActionTest(options) {
295
+ return [
296
+ "import { describe, expect, it } from 'vitest';",
297
+ `import { ${options.descriptorName} } from '../../src/actions/${options.slug}.js';`,
298
+ "",
299
+ `describe('${options.slug} action', () => {`,
300
+ " it('should expose a browser-safe executable input contract', () => {",
301
+ ` expect(${options.descriptorName}.id).toBe('${options.slug}');`,
302
+ ` expect(${options.descriptorName}.input.safeParse({ value: 'example' }).success).toBe(true);`,
303
+ ` expect(${options.descriptorName}.input.safeParse({ value: '' }).success).toBe(false);`,
304
+ " });",
305
+ "});",
306
+ ""
307
+ ].join("\n");
308
+ }
309
+ function buildRoutePath(branch, segments, overridePath = "") {
310
+ if (!overridePath) {
311
+ const suffix = segments.join("/");
312
+ return branch === "app" ? `/app/${suffix}` : `/${suffix}`;
313
+ }
314
+ const normalized = overridePath.startsWith("/") ? overridePath : `/${overridePath}`;
315
+ if (branch === "app") return normalized === "/app" || normalized.startsWith("/app/") ? normalized : `/app${normalized}`;
316
+ if (normalized === "/app" || normalized.startsWith("/app/")) throw new Error("Public branch routes cannot live under /app.");
317
+ return normalized;
318
+ }
319
+ function toImportSpecifier(fromFile, toFile) {
320
+ const withoutExtension = path.relative(path.dirname(fromFile), toFile).replace(/\\/g, "/").replace(/\.tsx$/i, "");
321
+ return withoutExtension.startsWith(".") ? withoutExtension : `./${withoutExtension}`;
322
+ }
323
+ function createUpdatedRouteFile(routeFileContent, options) {
324
+ const normalized = routeFileContent.replace(/\r\n/g, "\n");
325
+ const lines = normalized.split("\n");
326
+ const lastImportIndex = lines.reduce((currentIndex, line, index) => line.startsWith("import ") ? index : currentIndex, -1);
327
+ if (lastImportIndex === -1) throw new Error("Unsupported route file: could not find import block.");
328
+ const importLine = `import ${options.componentName} from '${options.importSpecifier}';`;
329
+ if (normalized.includes(importLine) || normalized.includes(`route('${options.routePath}',`) || normalized.includes(`route("${options.routePath}",`)) throw new Error(`Route '${options.routePath}' is already registered.`);
330
+ lines.splice(lastImportIndex + 1, 0, importLine);
331
+ const closingIndex = lines.map((line) => line.trim()).lastIndexOf("}");
332
+ if (closingIndex === -1) throw new Error("Unsupported route file: could not find registration function body.");
333
+ lines.splice(closingIndex, 0, ` route('${options.routePath}', ${options.componentName});`);
334
+ return `${lines.join("\n")}\n`;
335
+ }
336
+ function renderPageFile(options) {
337
+ return [
338
+ "import {",
339
+ " Badge,",
340
+ " Card,",
341
+ " CardContent,",
342
+ " CardDescription,",
343
+ " CardHeader,",
344
+ " CardTitle,",
345
+ "} from '@askrjs/themes/components';",
346
+ "import { Stack } from '@askrjs/themes/components';",
347
+ "",
348
+ `export default function ${options.componentName}() {`,
349
+ " return (",
350
+ " <Stack gap=\"5\">",
351
+ " <section class=\"page-heading\">",
352
+ " <Stack gap=\"2\">",
353
+ ` <Badge>${options.badge}</Badge>`,
354
+ ` <h1>${options.title}</h1>`,
355
+ " <p class=\"lead\">",
356
+ ` Route-first scaffold for ${options.routePath}. Keep adapters, queries, and mutations outside the page as this surface grows.`,
357
+ " </p>",
358
+ " </Stack>",
359
+ " </section>",
360
+ "",
361
+ " <Card>",
362
+ " <CardHeader>",
363
+ " <CardTitle>Next step</CardTitle>",
364
+ " <CardDescription>",
365
+ " Move view logic into feature folders and keep loading, empty, error, and success states explicit.",
366
+ " </CardDescription>",
367
+ " </CardHeader>",
368
+ " <CardContent>",
369
+ " <Stack gap=\"3\">",
370
+ " <p>Start with a focused feature boundary instead of inline data fetching.</p>",
371
+ " <p>Prefer resource(), derive(), and For once the page takes on real state.</p>",
372
+ " </Stack>",
373
+ " </CardContent>",
374
+ " </Card>",
375
+ " </Stack>",
376
+ " );",
377
+ "}",
378
+ ""
379
+ ].join("\n");
380
+ }
381
+ async function addPage(parsed, io) {
382
+ if (!parsed.name) {
383
+ io.error("Page name is required.");
384
+ return 1;
385
+ }
386
+ const branch = parsed.branch.toLowerCase();
387
+ const branchConfig = BRANCH_CONFIG[branch];
388
+ if (!branchConfig) {
389
+ io.error(`Unsupported branch '${parsed.branch}'. Use app or public.`);
390
+ return 1;
391
+ }
392
+ const segments = normalizePageSegments(parsed.name);
393
+ if (segments.length === 0) {
394
+ io.error("Page name must contain at least one non-empty path segment.");
395
+ return 1;
396
+ }
397
+ const projectRoot = path.resolve(parsed.cwd);
398
+ const routesFile = path.join(projectRoot, ...branchConfig.routesFile);
399
+ if (!await pathExists(routesFile)) {
400
+ io.error(`Unsupported project layout. Expected route file: ${routesFile}`);
401
+ io.error("askr add page currently supports route-first SPA projects created by `askr create spa`.");
402
+ return 1;
403
+ }
404
+ const pageFile = path.join(projectRoot, ...branchConfig.pagesDir, ...segments).concat(".tsx");
405
+ if (await pathExists(pageFile) && !parsed.force) {
406
+ io.error(`Page file already exists: ${pageFile}`);
407
+ io.error("Pass --force to overwrite the existing file.");
408
+ return 1;
409
+ }
410
+ const title = parsed.title || toTitleCase(toWords(segments));
411
+ const componentName = buildComponentName(segments);
412
+ let routePath = "";
413
+ try {
414
+ routePath = buildRoutePath(branch, segments, parsed.routePath);
415
+ } catch (error) {
416
+ io.error(error instanceof Error ? error.message : String(error));
417
+ return 1;
418
+ }
419
+ const importSpecifier = toImportSpecifier(routesFile, pageFile);
420
+ let updatedRoutes = "";
421
+ try {
422
+ updatedRoutes = createUpdatedRouteFile(await fs.readFile(routesFile, "utf8"), {
423
+ componentName,
424
+ importSpecifier,
425
+ routePath
426
+ });
427
+ } catch (error) {
428
+ io.error(error instanceof Error ? error.message : String(error));
429
+ return 1;
430
+ }
431
+ try {
432
+ await fs.mkdir(path.dirname(pageFile), { recursive: true });
433
+ await fs.writeFile(pageFile, renderPageFile({
434
+ badge: branchConfig.badge,
435
+ componentName,
436
+ routePath,
437
+ title
438
+ }), "utf8");
439
+ await fs.writeFile(routesFile, updatedRoutes, "utf8");
440
+ } catch (error) {
441
+ io.error("Failed to write generated page artifacts.");
442
+ io.error(error instanceof Error ? error.message : String(error));
443
+ return 1;
444
+ }
445
+ io.log(`Added ${branch} page '${title}'.`);
446
+ io.log(` File: ${path.relative(projectRoot, pageFile).replace(/\\/g, "/")}`);
447
+ io.log(` Route: ${routePath}`);
448
+ io.log(` Router: ${path.relative(projectRoot, routesFile).replace(/\\/g, "/")}`);
449
+ return 0;
450
+ }
451
+ async function addAction(parsed, io) {
452
+ if (!parsed.name) {
453
+ io.error("Action name is required.");
454
+ return 1;
455
+ }
456
+ if (!parsed.routePath || !parsed.routePath.startsWith("/")) {
457
+ io.error("Action generation requires an absolute --route path.");
458
+ return 1;
459
+ }
460
+ const segments = normalizePageSegments(parsed.name);
461
+ if (segments.length === 0) {
462
+ io.error("Action name must contain at least one non-empty path segment.");
463
+ return 1;
464
+ }
465
+ const projectRoot = path.resolve(parsed.cwd);
466
+ const slug = segments.join("-");
467
+ const handlerName = buildIdentifier(segments);
468
+ const descriptorName = `${handlerName}Action`;
469
+ const descriptorFile = path.join(projectRoot, "src", "actions", `${slug}.ts`);
470
+ const handlerFile = path.join(projectRoot, "src", "server", "actions", `${slug}.ts`);
471
+ const registryFile = path.join(projectRoot, "src", "server", "action-registry.ts");
472
+ const authorizationFile = path.join(projectRoot, "src", "action-authorizations.ts");
473
+ const testFile = path.join(projectRoot, "tests", "actions", `${slug}.test.ts`);
474
+ if (!await pathExists(registryFile) || !await pathExists(authorizationFile)) {
475
+ io.error("Unsupported project layout. Expected an `askr create full-stack` project.");
476
+ return 1;
477
+ }
478
+ if (!parsed.force && (await pathExists(descriptorFile) || await pathExists(handlerFile))) {
479
+ io.error(`Action '${slug}' already exists. Pass --force to replace its generated files.`);
480
+ return 1;
481
+ }
482
+ try {
483
+ const descriptor = renderActionDescriptor({
484
+ descriptorName,
485
+ routePath: parsed.routePath,
486
+ slug
487
+ });
488
+ const actions = await discoverDeclaredActions(projectRoot, {
489
+ filePath: descriptorFile,
490
+ content: descriptor
491
+ });
492
+ await writeFileChanges([
493
+ {
494
+ filePath: descriptorFile,
495
+ content: descriptor
496
+ },
497
+ {
498
+ filePath: handlerFile,
499
+ content: renderActionHandler({
500
+ descriptorName,
501
+ handlerName,
502
+ slug
503
+ })
504
+ },
505
+ {
506
+ filePath: testFile,
507
+ content: renderActionTest({
508
+ descriptorName,
509
+ slug
510
+ })
511
+ },
512
+ {
513
+ filePath: registryFile,
514
+ content: renderServerActionRegistry(actions)
515
+ },
516
+ {
517
+ filePath: authorizationFile,
518
+ content: renderAuthorizationRegistry(actions)
519
+ }
520
+ ]);
521
+ } catch (error) {
522
+ io.error("Failed to write generated action artifacts.");
523
+ io.error(error instanceof Error ? error.message : String(error));
524
+ return 1;
525
+ }
526
+ io.log(`Added action '${slug}' for ${parsed.routePath}.`);
527
+ io.log(` Descriptor: ${path.relative(projectRoot, descriptorFile).replace(/\\/g, "/")}`);
528
+ io.log(` Handler: ${path.relative(projectRoot, handlerFile).replace(/\\/g, "/")}`);
529
+ io.log(` Test: ${path.relative(projectRoot, testFile).replace(/\\/g, "/")}`);
530
+ return 0;
531
+ }
532
+ async function runAddCli(args = process.argv.slice(2), io = console) {
533
+ const parsed = parseArgs(args);
534
+ if (parsed.errors.length > 0) {
535
+ for (const message of parsed.errors) io.error(message);
536
+ return 1;
537
+ }
538
+ if (!parsed.command || parsed.help) {
539
+ io.log(helpText());
540
+ return 0;
541
+ }
542
+ if (parsed.command === "page") return addPage(parsed, io);
543
+ if (parsed.command === "action") return addAction(parsed, io);
544
+ io.error(`Unknown add command: ${parsed.command}`);
545
+ io.error("Run `askr add --help` to see available commands.");
546
+ return 1;
547
+ }
548
+ async function main() {
549
+ const code = await runAddCli(process.argv.slice(2));
550
+ process.exit(code);
551
+ }
552
+ if (isDirectExecution(import.meta.url)) main();
553
+ //#endregion
3
554
  export { runAddCli };
555
+
556
+ //# sourceMappingURL=add.js.map