@alicesystems/cli 0.2.2 → 0.3.0

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.
package/README.md CHANGED
@@ -20,6 +20,7 @@ The only prompt is the project name.
20
20
  ## Other commands
21
21
 
22
22
  - `alice add --addons <addon>`: add `turborepo`, `fumadocs` or `ultracite` to an existing project.
23
+ - `alice generate <table> [fields...]`: add a database table and a full CRUD API to an existing project. See below.
23
24
  - `alice history`: list projects created on this machine.
24
25
 
25
26
  ## Telemetry
@@ -27,3 +28,25 @@ The only prompt is the project name.
27
28
  No telemetry is sent unless a collection endpoint is configured at build time. Set `ALICE_TELEMETRY_DISABLED=1` or `DO_NOT_TRACK=1` to disable it regardless.
28
29
 
29
30
  Forked from [Better-T-Stack](https://github.com/AmanVarshney01/create-better-t-stack) (MIT).
31
+
32
+ ## Generate a resource
33
+
34
+ Run it from the root of a project:
35
+
36
+ ```bash
37
+ alice generate blog_posts title:string body:text? published:boolean
38
+ ```
39
+
40
+ It adds a Drizzle table in `packages/database`, a route module in `apps/server` (list, get, create, update and delete, documented in OpenAPI) and registers both. Rows belong to the signed-in user, so one user can never read another's. Then create the table with `pnpm db:push`.
41
+
42
+ Fields are `name:type`. Add `?` to make one optional and write `author_id:references(users)` to point at another table, with `!cascade` to delete rows along with it. Types: `string`, `text`, `integer`, `bigint`, `float`, `boolean`, `timestamp`, `date`, `json`, `uuid`, `references`.
43
+
44
+ | Flag | What it does |
45
+ | ----------------- | --------------------------------------------------------- |
46
+ | `--owner none` | Rows belong to nobody (the default is the signed-in user) |
47
+ | `--no-timestamps` | Skip `createdAt` and `updatedAt` |
48
+ | `--index <field>` | Index one field |
49
+ | `--force` | Overwrite an existing resource |
50
+ | `--dry-run` | Show the files without writing them |
51
+
52
+ Run `alice generate` with no arguments to be prompted instead, or use `alice generate-json --json '{...}'` from a script. If dependencies are installed it also refreshes the API reference in the docs site.
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as createAliceCli } from "./src-D7QghBiE.mjs";
2
+ import { a as createAliceCli } from "./src-xWMOCKGW.mjs";
3
3
  import { lineByLineConsoleLogger } from "trpc-cli";
4
4
  //#region src/cli.ts
5
5
  await createAliceCli().run({ logger: lineByLineConsoleLogger });
@@ -5,6 +5,7 @@ import path from "node:path";
5
5
  import Handlebars from "handlebars";
6
6
  import yaml, { parse, stringify } from "yaml";
7
7
  import { Node, Project, SyntaxKind } from "ts-morph";
8
+ import pluralize from "pluralize";
8
9
  //#region ../../packages/template-generator/dist/is-binary-path-C-QlvTjz.mjs
9
10
  const extensions = /* @__PURE__ */ new Set([
10
11
  "3dm",
@@ -10458,6 +10459,535 @@ async function generate(options) {
10458
10459
  }
10459
10460
  });
10460
10461
  }
10462
+ const RESERVED_TABLES = /* @__PURE__ */ new Set([
10463
+ "user",
10464
+ "users",
10465
+ "session",
10466
+ "sessions",
10467
+ "account",
10468
+ "accounts",
10469
+ "verification",
10470
+ "verifications",
10471
+ "file",
10472
+ "files",
10473
+ "notification",
10474
+ "notifications",
10475
+ "content",
10476
+ "storage",
10477
+ "index",
10478
+ "doc"
10479
+ ]);
10480
+ const USER_TABLES = /* @__PURE__ */ new Set(["user", "users"]);
10481
+ const capitalize = (word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`;
10482
+ const camel = (name) => name.split("_").map((word, index) => index === 0 ? word : capitalize(word)).join("");
10483
+ const pascal = (name) => name.split("_").map(capitalize).join("");
10484
+ const kebab = (name) => name.replaceAll("_", "-");
10485
+ function resourceNames(table) {
10486
+ const singular = pluralize.singular(table);
10487
+ return {
10488
+ table,
10489
+ singular,
10490
+ plural: camel(table),
10491
+ item: camel(singular),
10492
+ Item: pascal(singular),
10493
+ slug: kebab(table),
10494
+ title: capitalize(table.replaceAll("_", " "))
10495
+ };
10496
+ }
10497
+ const isRequired = (field) => field.required !== false;
10498
+ const isUserReference = (field) => field.type === "references" && USER_TABLES.has(field.references ?? "");
10499
+ /** Everything that would make the generated code wrong, as readable messages. */
10500
+ function validateResource(input) {
10501
+ const problems = [];
10502
+ const names = resourceNames(input.name);
10503
+ const owner = input.owner ?? "user";
10504
+ const timestamps = input.timestamps !== false;
10505
+ if (RESERVED_TABLES.has(input.name)) problems.push(`"${input.name}" is already used by the generated project`);
10506
+ if (names.singular === input.name) problems.push(`"${input.name}" needs a distinct plural name (it reads the same in the singular); try a longer name`);
10507
+ const taken = /* @__PURE__ */ new Set(["id"]);
10508
+ if (owner === "user") taken.add("user_id");
10509
+ if (timestamps) {
10510
+ taken.add("created_at");
10511
+ taken.add("updated_at");
10512
+ }
10513
+ const seen = /* @__PURE__ */ new Set();
10514
+ for (const field of input.fields) {
10515
+ if (seen.has(field.name)) problems.push(`Field "${field.name}" is listed twice`);
10516
+ seen.add(field.name);
10517
+ if (taken.has(field.name)) problems.push(`Field "${field.name}" is added automatically; remove it from the list`);
10518
+ if (field.type === "references") {
10519
+ if (!field.references) problems.push(`Field "${field.name}" is a reference but names no table`);
10520
+ else if (field.references === input.name) problems.push(`Field "${field.name}" cannot point at its own table`);
10521
+ } else if (field.references !== void 0 || field.cascade !== void 0) problems.push(`Field "${field.name}" is not a reference, so references and cascade do not apply`);
10522
+ }
10523
+ if (input.index !== void 0 && !seen.has(input.index)) problems.push(`Cannot index "${input.index}": it is not one of the fields`);
10524
+ return problems;
10525
+ }
10526
+ function columnFor(field) {
10527
+ const name = JSON.stringify(field.name);
10528
+ const notNull = isRequired(field) ? ".notNull()" : "";
10529
+ switch (field.type) {
10530
+ case "string": return {
10531
+ expression: `varchar(${name}, { length: 255 })${notNull}`,
10532
+ imports: ["varchar"]
10533
+ };
10534
+ case "text": return {
10535
+ expression: `text(${name})${notNull}`,
10536
+ imports: ["text"]
10537
+ };
10538
+ case "integer": return {
10539
+ expression: `integer(${name})${notNull}`,
10540
+ imports: ["integer"]
10541
+ };
10542
+ case "bigint": return {
10543
+ expression: `bigint(${name}, { mode: "number" })${notNull}`,
10544
+ imports: ["bigint"]
10545
+ };
10546
+ case "float": return {
10547
+ expression: `doublePrecision(${name})${notNull}`,
10548
+ imports: ["doublePrecision"]
10549
+ };
10550
+ case "boolean": return {
10551
+ expression: `boolean(${name})${notNull}`,
10552
+ imports: ["boolean"]
10553
+ };
10554
+ case "timestamp": return {
10555
+ expression: `timestamp(${name})${notNull}`,
10556
+ imports: ["timestamp"]
10557
+ };
10558
+ case "date": return {
10559
+ expression: `date(${name}, { mode: "string" })${notNull}`,
10560
+ imports: ["date"]
10561
+ };
10562
+ case "json": return {
10563
+ expression: `jsonb(${name})${notNull}`,
10564
+ imports: ["jsonb"]
10565
+ };
10566
+ case "uuid": return {
10567
+ expression: `uuid(${name})${notNull}`,
10568
+ imports: ["uuid"]
10569
+ };
10570
+ case "references": {
10571
+ const onDelete = field.cascade ? ", { onDelete: \"cascade\" }" : "";
10572
+ if (isUserReference(field)) return {
10573
+ expression: `text(${name})${notNull}.references(() => user.id${onDelete})`,
10574
+ imports: ["text"]
10575
+ };
10576
+ return {
10577
+ expression: `uuid(${name})${notNull}.references(() => ${camel(field.references ?? "")}.id${onDelete})`,
10578
+ imports: ["uuid"]
10579
+ };
10580
+ }
10581
+ }
10582
+ }
10583
+ function buildSchema(input, names) {
10584
+ const owner = input.owner ?? "user";
10585
+ const timestamps = input.timestamps !== false;
10586
+ const imports = /* @__PURE__ */ new Set(["pgTable", "uuid"]);
10587
+ const lines = [" id: uuid(\"id\").defaultRandom().primaryKey(),"];
10588
+ const siblingImports = [];
10589
+ const needsUser = owner === "user" || input.fields.some(isUserReference);
10590
+ if (owner === "user") {
10591
+ imports.add("text");
10592
+ lines.push(" userId: text(\"user_id\")", " .notNull()", " .references(() => user.id, { onDelete: \"cascade\" }),");
10593
+ }
10594
+ for (const field of input.fields) {
10595
+ const column = columnFor(field);
10596
+ for (const name of column.imports) imports.add(name);
10597
+ lines.push(` ${camel(field.name)}: ${column.expression},`);
10598
+ if (field.type === "references" && !isUserReference(field) && field.references) {
10599
+ const line = `import { ${camel(field.references)} } from "./${kebab(field.references)}";`;
10600
+ if (!siblingImports.includes(line)) siblingImports.push(line);
10601
+ }
10602
+ }
10603
+ if (timestamps) {
10604
+ imports.add("timestamp");
10605
+ lines.push(" createdAt: timestamp(\"created_at\").defaultNow().notNull(),", " updatedAt: timestamp(\"updated_at\")", " .defaultNow()", " .$onUpdate(() => new Date())", " .notNull(),");
10606
+ }
10607
+ const indexed = input.index === void 0 ? void 0 : camel(input.index);
10608
+ if (indexed) imports.add("index");
10609
+ const importLine = `import { ${[...imports].sort().join(", ")} } from "drizzle-orm/pg-core";`;
10610
+ const local = [...needsUser ? ["import { user } from \"./auth\";"] : [], ...siblingImports.sort()];
10611
+ const header = [importLine, ...local.length > 0 ? ["", ...local] : []].join("\n");
10612
+ const tableName = JSON.stringify(names.table);
10613
+ const body = lines.join("\n");
10614
+ if (indexed) {
10615
+ const indexName = JSON.stringify(`${names.table}_${input.index}_idx`);
10616
+ return `${header}
10617
+
10618
+ export const ${names.plural} = pgTable(
10619
+ ${tableName},
10620
+ {
10621
+ ${body}
10622
+ },
10623
+ (table) => [index(${indexName}).on(table.${indexed})],
10624
+ );
10625
+ `;
10626
+ }
10627
+ return `${header}
10628
+
10629
+ export const ${names.plural} = pgTable(${tableName}, {
10630
+ ${body}
10631
+ });
10632
+ `;
10633
+ }
10634
+ /** The Zod type of a field as it appears in responses. */
10635
+ function zodOutput(field) {
10636
+ const base = (() => {
10637
+ switch (field.type) {
10638
+ case "string":
10639
+ case "text":
10640
+ case "timestamp":
10641
+ case "date": return "z.string()";
10642
+ case "integer":
10643
+ case "bigint": return "z.number().int()";
10644
+ case "float": return "z.number()";
10645
+ case "boolean": return "z.boolean()";
10646
+ case "json": return "z.unknown()";
10647
+ case "uuid": return "z.uuid()";
10648
+ case "references": return isUserReference(field) ? "z.string()" : "z.uuid()";
10649
+ }
10650
+ })();
10651
+ return isRequired(field) ? base : `${base}.nullable()`;
10652
+ }
10653
+ /** The Zod type of a field as it is sent to create or update a row. */
10654
+ function zodInput(field, update) {
10655
+ const base = (() => {
10656
+ switch (field.type) {
10657
+ case "string": return "z.string().min(1).max(255)";
10658
+ case "text": return "z.string()";
10659
+ case "timestamp": return "z.iso.datetime()";
10660
+ case "date": return "z.iso.date()";
10661
+ case "integer":
10662
+ case "bigint": return "z.number().int()";
10663
+ case "float": return "z.number()";
10664
+ case "boolean": return "z.boolean()";
10665
+ case "json": return "z.json()";
10666
+ case "uuid": return "z.uuid()";
10667
+ case "references": return isUserReference(field) ? "z.string()" : "z.uuid()";
10668
+ }
10669
+ })();
10670
+ if (isRequired(field)) return update ? `${base}.optional()` : base;
10671
+ return update ? `${base}.nullable().optional()` : `${base}.optional()`;
10672
+ }
10673
+ function buildRoutes(input, names) {
10674
+ const timestamps = input.timestamps !== false;
10675
+ const outputFields = input.fields.map((field) => ` ${camel(field.name)}: ${zodOutput(field)},`);
10676
+ const createFields = input.fields.map((field) => ` ${camel(field.name)}: ${zodInput(field, false)},`);
10677
+ const updateFields = input.fields.map((field) => ` ${camel(field.name)}: ${zodInput(field, true)},`);
10678
+ const stamps = timestamps ? [" createdAt: z.string(),", " updatedAt: z.string(),"] : [];
10679
+ const path = `/${names.slug}`;
10680
+ const plural = names.plural;
10681
+ const item = names.item;
10682
+ return `import { createRoute, z } from "@hono/zod-openapi";
10683
+ import * as HttpStatusCodes from "stoker/http-status-codes";
10684
+ import { jsonContent } from "stoker/openapi/helpers";
10685
+
10686
+ import { notFoundSchema, unauthorizedSchema } from "@/lib/constants";
10687
+
10688
+ const tags = [${JSON.stringify(names.title)}];
10689
+ const security = [{ session: [] }];
10690
+
10691
+ const ${item}Schema = z.object({
10692
+ id: z.uuid(),
10693
+ ${[...outputFields, ...stamps].join("\n")}
10694
+ });
10695
+
10696
+ const create${names.Item}Body = z.object({
10697
+ ${createFields.join("\n")}
10698
+ });
10699
+
10700
+ const update${names.Item}Body = z.object({
10701
+ ${updateFields.join("\n")}
10702
+ });
10703
+
10704
+ const idParams = z.object({ id: z.uuid() });
10705
+
10706
+ export const list = createRoute({
10707
+ path: ${JSON.stringify(path)},
10708
+ method: "get",
10709
+ tags,
10710
+ security,
10711
+ summary: ${JSON.stringify(`List ${names.title.toLowerCase()}`)},
10712
+ responses: {
10713
+ [HttpStatusCodes.OK]: jsonContent(
10714
+ z.object({ ${plural}: z.array(${item}Schema) }),
10715
+ ${JSON.stringify(`The ${names.title.toLowerCase()}`)},
10716
+ ),
10717
+ [HttpStatusCodes.UNAUTHORIZED]: jsonContent(unauthorizedSchema, "Not signed in"),
10718
+ },
10719
+ });
10720
+
10721
+ export const get = createRoute({
10722
+ path: ${JSON.stringify(`${path}/{id}`)},
10723
+ method: "get",
10724
+ tags,
10725
+ security,
10726
+ summary: ${JSON.stringify(`Get one ${names.singular.replaceAll("_", " ")}`)},
10727
+ request: { params: idParams },
10728
+ responses: {
10729
+ [HttpStatusCodes.OK]: jsonContent(${item}Schema, "The row"),
10730
+ [HttpStatusCodes.UNAUTHORIZED]: jsonContent(unauthorizedSchema, "Not signed in"),
10731
+ [HttpStatusCodes.NOT_FOUND]: jsonContent(notFoundSchema, "The row does not exist"),
10732
+ },
10733
+ });
10734
+
10735
+ export const create = createRoute({
10736
+ path: ${JSON.stringify(path)},
10737
+ method: "post",
10738
+ tags,
10739
+ security,
10740
+ summary: ${JSON.stringify(`Create a ${names.singular.replaceAll("_", " ")}`)},
10741
+ request: {
10742
+ body: {
10743
+ required: true,
10744
+ content: { "application/json": { schema: create${names.Item}Body } },
10745
+ },
10746
+ },
10747
+ responses: {
10748
+ [HttpStatusCodes.CREATED]: jsonContent(${item}Schema, "The row was created"),
10749
+ [HttpStatusCodes.UNAUTHORIZED]: jsonContent(unauthorizedSchema, "Not signed in"),
10750
+ },
10751
+ });
10752
+
10753
+ export const update = createRoute({
10754
+ path: ${JSON.stringify(`${path}/{id}`)},
10755
+ method: "patch",
10756
+ tags,
10757
+ security,
10758
+ summary: ${JSON.stringify(`Update a ${names.singular.replaceAll("_", " ")}`)},
10759
+ request: {
10760
+ params: idParams,
10761
+ body: {
10762
+ required: true,
10763
+ content: { "application/json": { schema: update${names.Item}Body } },
10764
+ },
10765
+ },
10766
+ responses: {
10767
+ [HttpStatusCodes.OK]: jsonContent(${item}Schema, "The updated row"),
10768
+ [HttpStatusCodes.UNAUTHORIZED]: jsonContent(unauthorizedSchema, "Not signed in"),
10769
+ [HttpStatusCodes.NOT_FOUND]: jsonContent(notFoundSchema, "The row does not exist"),
10770
+ },
10771
+ });
10772
+
10773
+ export const remove = createRoute({
10774
+ path: ${JSON.stringify(`${path}/{id}`)},
10775
+ method: "delete",
10776
+ tags,
10777
+ security,
10778
+ summary: ${JSON.stringify(`Delete a ${names.singular.replaceAll("_", " ")}`)},
10779
+ request: { params: idParams },
10780
+ responses: {
10781
+ [HttpStatusCodes.NO_CONTENT]: { description: "The row was deleted" },
10782
+ [HttpStatusCodes.UNAUTHORIZED]: jsonContent(unauthorizedSchema, "Not signed in"),
10783
+ [HttpStatusCodes.NOT_FOUND]: jsonContent(notFoundSchema, "The row does not exist"),
10784
+ },
10785
+ });
10786
+
10787
+ export type ListRoute = typeof list;
10788
+ export type GetRoute = typeof get;
10789
+ export type CreateRoute = typeof create;
10790
+ export type UpdateRoute = typeof update;
10791
+ export type RemoveRoute = typeof remove;
10792
+ `;
10793
+ }
10794
+ /** Turns a request value into the value stored in the column. */
10795
+ function toColumnValue(field, source, update) {
10796
+ if (field.type !== "timestamp") return source;
10797
+ if (isRequired(field)) return update ? `${source} === undefined ? undefined : new Date(${source})` : `new Date(${source})`;
10798
+ return update ? `${source} === undefined || ${source} === null ? ${source} : new Date(${source})` : `${source} === undefined ? undefined : new Date(${source})`;
10799
+ }
10800
+ function toJsonValue(field) {
10801
+ const property = `row.${camel(field.name)}`;
10802
+ if (field.type !== "timestamp") return property;
10803
+ return isRequired(field) ? `${property}.toISOString()` : `${property} === null ? null : ${property}.toISOString()`;
10804
+ }
10805
+ function buildHandlers(input, names, scope) {
10806
+ const owner = input.owner ?? "user";
10807
+ const timestamps = input.timestamps !== false;
10808
+ const table = names.plural;
10809
+ const ownerScoped = owner === "user";
10810
+ const userLine = ownerScoped ? " const user = c.get(\"user\");\n" : "";
10811
+ const idWhere = ownerScoped ? `and(eq(${table}.id, id), eq(${table}.userId, user.id))` : `eq(${table}.id, id)`;
10812
+ const jsonFields = [
10813
+ " id: row.id,",
10814
+ ...input.fields.map((field) => ` ${camel(field.name)}: ${toJsonValue(field)},`),
10815
+ ...timestamps ? [" createdAt: row.createdAt.toISOString(),", " updatedAt: row.updatedAt.toISOString(),"] : []
10816
+ ];
10817
+ const createValues = [...ownerScoped ? [" userId: user.id,"] : [], ...input.fields.map((field) => ` ${camel(field.name)}: ${toColumnValue(field, `body.${camel(field.name)}`, false)},`)];
10818
+ const changeValues = input.fields.map((field) => ` ${camel(field.name)}: ${toColumnValue(field, `body.${camel(field.name)}`, true)},`);
10819
+ const operators = [
10820
+ "eq",
10821
+ ...ownerScoped ? ["and"] : [],
10822
+ ...timestamps ? ["desc"] : []
10823
+ ].sort();
10824
+ const listWhere = ownerScoped ? `\n .where(eq(${table}.userId, user.id))` : "";
10825
+ const listOrder = timestamps ? `\n .orderBy(desc(${table}.createdAt))` : "";
10826
+ return `import { ${[...operators, table].sort().join(", ")} } from "@${scope}/database";
10827
+ import * as HttpStatusCodes from "stoker/http-status-codes";
10828
+ import * as HttpStatusPhrases from "stoker/http-status-phrases";
10829
+
10830
+ import type { AuthedRouteHandler } from "@/lib/types";
10831
+
10832
+ import { db } from "@/services";
10833
+
10834
+ import type { CreateRoute, GetRoute, ListRoute, RemoveRoute, UpdateRoute } from "./${names.slug}.routes";
10835
+
10836
+ const toJson = (row: typeof ${table}.$inferSelect) => ({
10837
+ ${jsonFields.join("\n")}
10838
+ });
10839
+
10840
+ const notFound = { message: HttpStatusPhrases.NOT_FOUND };
10841
+
10842
+ export const list: AuthedRouteHandler<ListRoute> = async (c) => {
10843
+ ${userLine} const rows = await db
10844
+ .select()
10845
+ .from(${table})${listWhere}${listOrder};
10846
+
10847
+ return c.json({ ${table}: rows.map(toJson) }, HttpStatusCodes.OK);
10848
+ };
10849
+
10850
+ export const get: AuthedRouteHandler<GetRoute> = async (c) => {
10851
+ ${userLine} const { id } = c.req.valid("param");
10852
+
10853
+ const [row] = await db.select().from(${table}).where(${idWhere});
10854
+ if (!row) {
10855
+ return c.json(notFound, HttpStatusCodes.NOT_FOUND);
10856
+ }
10857
+
10858
+ return c.json(toJson(row), HttpStatusCodes.OK);
10859
+ };
10860
+
10861
+ export const create: AuthedRouteHandler<CreateRoute> = async (c) => {
10862
+ ${userLine} const body = c.req.valid("json");
10863
+
10864
+ const [row] = await db
10865
+ .insert(${table})
10866
+ .values({
10867
+ ${createValues.join("\n")}
10868
+ })
10869
+ .returning();
10870
+ if (!row) {
10871
+ throw new Error("The row was not created");
10872
+ }
10873
+
10874
+ return c.json(toJson(row), HttpStatusCodes.CREATED);
10875
+ };
10876
+
10877
+ export const update: AuthedRouteHandler<UpdateRoute> = async (c) => {
10878
+ ${userLine} const { id } = c.req.valid("param");
10879
+ const body = c.req.valid("json");
10880
+
10881
+ const changes = {
10882
+ ${changeValues.join("\n")}
10883
+ };
10884
+
10885
+ // An empty change set would make the query invalid, so return the row as it is.
10886
+ if (Object.values(changes).every((value) => value === undefined)) {
10887
+ const [current] = await db.select().from(${table}).where(${idWhere});
10888
+ return current ? c.json(toJson(current), HttpStatusCodes.OK) : c.json(notFound, HttpStatusCodes.NOT_FOUND);
10889
+ }
10890
+
10891
+ const [row] = await db.update(${table}).set(changes).where(${idWhere}).returning();
10892
+ if (!row) {
10893
+ return c.json(notFound, HttpStatusCodes.NOT_FOUND);
10894
+ }
10895
+
10896
+ return c.json(toJson(row), HttpStatusCodes.OK);
10897
+ };
10898
+
10899
+ export const remove: AuthedRouteHandler<RemoveRoute> = async (c) => {
10900
+ ${userLine} const { id } = c.req.valid("param");
10901
+
10902
+ const deleted = await db.delete(${table}).where(${idWhere}).returning({ id: ${table}.id });
10903
+ if (deleted.length === 0) {
10904
+ return c.json(notFound, HttpStatusCodes.NOT_FOUND);
10905
+ }
10906
+
10907
+ return c.body(null, HttpStatusCodes.NO_CONTENT);
10908
+ };
10909
+ `;
10910
+ }
10911
+ function buildIndex(names) {
10912
+ return `import { createAuthedRouter } from "@/lib/create-app";
10913
+
10914
+ import * as handlers from "./${names.slug}.handlers";
10915
+ import * as routes from "./${names.slug}.routes";
10916
+
10917
+ const router = createAuthedRouter()
10918
+ .openapi(routes.list, handlers.list)
10919
+ .openapi(routes.get, handlers.get)
10920
+ .openapi(routes.create, handlers.create)
10921
+ .openapi(routes.update, handlers.update)
10922
+ .openapi(routes.remove, handlers.remove);
10923
+
10924
+ export default router;
10925
+ `;
10926
+ }
10927
+ /** Builds every new file for a resource. `scope` is the project's package scope, as in `@scope/database`. */
10928
+ function planResource(input, scope) {
10929
+ const names = resourceNames(input.name);
10930
+ const routeDir = `apps/server/src/routes/${names.slug}`;
10931
+ return {
10932
+ names,
10933
+ schemaModule: names.slug,
10934
+ route: {
10935
+ importName: names.plural,
10936
+ importPath: `@/routes/${names.slug}/${names.slug}.index`
10937
+ },
10938
+ referencedTables: [...new Set(input.fields.flatMap((field) => field.type === "references" && field.references && !isUserReference(field) ? [field.references] : []))],
10939
+ files: [
10940
+ {
10941
+ path: `packages/database/src/schema/${names.slug}.ts`,
10942
+ content: buildSchema(input, names)
10943
+ },
10944
+ {
10945
+ path: `${routeDir}/${names.slug}.routes.ts`,
10946
+ content: buildRoutes(input, names)
10947
+ },
10948
+ {
10949
+ path: `${routeDir}/${names.slug}.handlers.ts`,
10950
+ content: buildHandlers(input, names, scope)
10951
+ },
10952
+ {
10953
+ path: `${routeDir}/${names.slug}.index.ts`,
10954
+ content: buildIndex(names)
10955
+ }
10956
+ ]
10957
+ };
10958
+ }
10959
+ /** Adds `export * from "./<module>";` to the schema barrel. Safe to run twice. */
10960
+ function addSchemaExport(content, module) {
10961
+ const line = `export * from "./${module}";`;
10962
+ if (content.includes(line)) return content;
10963
+ return `${content.endsWith("\n") || content.length === 0 ? content : `${content}\n`}${line}\n`;
10964
+ }
10965
+ /**
10966
+ * Registers a route module in apps/server/src/app.ts: one import, kept in path order with the
10967
+ * other route imports, and one `.route("/", name)` at the end of the chain. Safe to run twice.
10968
+ */
10969
+ function addRouteToApp(content, route) {
10970
+ if (content.includes(`"${route.importPath}"`)) return content;
10971
+ const lines = content.split("\n");
10972
+ const routeImports = lines.flatMap((line, index) => {
10973
+ const path = /^import .* from "(@\/routes\/[^"]+)";$/.exec(line)?.[1];
10974
+ return path === void 0 ? [] : [{
10975
+ index,
10976
+ path
10977
+ }];
10978
+ });
10979
+ if (routeImports.length === 0) throw new Error("Could not find the route imports in apps/server/src/app.ts");
10980
+ const importLine = `import ${route.importName} from "${route.importPath}";`;
10981
+ const before = routeImports.find((entry) => entry.path > route.importPath);
10982
+ const last = routeImports.at(-1);
10983
+ const insertAt = before ? before.index : (last?.index ?? 0) + 1;
10984
+ lines.splice(insertAt, 0, importLine);
10985
+ const updated = lines.join("\n");
10986
+ const chainStart = updated.indexOf("const routes = app");
10987
+ const chainEnd = chainStart === -1 ? -1 : updated.indexOf(";", chainStart);
10988
+ if (chainEnd === -1) throw new Error("Could not find the route list in apps/server/src/app.ts");
10989
+ return `${updated.slice(0, chainEnd)}\n .route("/", ${route.importName})${updated.slice(chainEnd)}`;
10990
+ }
10461
10991
  const EMBEDDED_TEMPLATES = /* @__PURE__ */ new Map([
10462
10992
  ["auth/better-auth/native/base/lib/auth-client.ts.hbs", `import {
10463
10993
  expoClient,
@@ -10947,7 +11477,7 @@ export default defineConfig({
10947
11477
  },
10948
11478
  });
10949
11479
  `],
10950
- ["backend/server/hono/scripts/generate-openapi.ts.hbs", `import { writeFile } from "node:fs/promises";
11480
+ ["backend/server/hono/scripts/generate-openapi.ts.hbs", `import { mkdir, writeFile } from "node:fs/promises";
10951
11481
 
10952
11482
  import app from "@/app";
10953
11483
  import { openApiConfig } from "@/lib/configure-open-api";
@@ -10959,6 +11489,7 @@ import { openApiConfig } from "@/lib/configure-open-api";
10959
11489
  const OUTPUT = new URL("../../fumadocs/openapi.json", import.meta.url);
10960
11490
 
10961
11491
  const document = app.getOpenAPI31Document(openApiConfig);
11492
+ await mkdir(new URL(".", OUTPUT), { recursive: true });
10962
11493
  await writeFile(OUTPUT, \`\${JSON.stringify(document, null, 2)}\\n\`);
10963
11494
  `],
10964
11495
  ["backend/server/hono/src/app.test.ts.hbs", `import { readFile } from "node:fs/promises";
@@ -25922,4 +26453,4 @@ export function checkFile(file: { type: string; size: number }): FileCheck {
25922
26453
  ]);
25923
26454
  const TEMPLATE_COUNT = 313;
25924
26455
  //#endregion
25925
- export { dependencyVersionMap as a, processAddonTemplates as c, processPnpmWorkspaceConfig as d, processTemplateString as f, join as h, VirtualFileSystem as i, processAddonsDeps as l, dirname as m, GeneratorError as n, generate as o, processTurboConfig as p, TEMPLATE_COUNT as r, generateReproducibleCommand as s, EMBEDDED_TEMPLATES as t, processPackageConfigs as u };
26456
+ export { validateResource as _, addRouteToApp as a, generate as c, processAddonTemplates as d, processAddonsDeps as f, processTurboConfig as g, processTemplateString as h, VirtualFileSystem as i, generateReproducibleCommand as l, processPnpmWorkspaceConfig as m, GeneratorError as n, addSchemaExport as o, processPackageConfigs as p, TEMPLATE_COUNT as r, dependencyVersionMap as s, EMBEDDED_TEMPLATES as t, planResource as u, dirname as v, join as y };
package/dist/index.d.mts CHANGED
@@ -145,6 +145,19 @@ interface CreateProjectResult {
145
145
  warnings?: string[];
146
146
  }
147
147
  //#endregion
148
+ //#region src/helpers/core/generate-handler.d.ts
149
+ type GenerateResult = {
150
+ success: boolean;
151
+ projectDir: string;
152
+ resource?: string;
153
+ createdFiles?: string[];
154
+ updatedFiles?: string[];
155
+ dryRun?: boolean;
156
+ openApiRegenerated?: boolean;
157
+ nextSteps?: string[];
158
+ error?: string;
159
+ };
160
+ //#endregion
148
161
  //#region src/helpers/core/add-handler.d.ts
149
162
  interface AddResult {
150
163
  success: boolean;
@@ -175,6 +188,7 @@ export declare const SchemaNameSchema: z.ZodDefault<z.ZodEnum<{
175
188
  directoryConflict: "directoryConflict";
176
189
  examples: "examples";
177
190
  frontend: "frontend";
191
+ generateInput: "generateInput";
178
192
  initResult: "initResult";
179
193
  orm: "orm";
180
194
  packageManager: "packageManager";
@@ -706,6 +720,7 @@ export declare const router: {
706
720
  directoryConflict: "directoryConflict";
707
721
  examples: "examples";
708
722
  frontend: "frontend";
723
+ generateInput: "generateInput";
709
724
  initResult: "initResult";
710
725
  orm: "orm";
711
726
  packageManager: "packageManager";
@@ -1039,6 +1054,50 @@ export declare const router: {
1039
1054
  dryRun: z.ZodOptional<z.ZodBoolean>;
1040
1055
  disableAnalytics: z.ZodOptional<z.ZodBoolean>;
1041
1056
  }, z.core.$strict>, import("@orpc/server").Schema<AddResult, AddResult>, import("@orpc/server").MergedErrorMap<Record<never, never>, Record<never, never>>, TrpcCliMeta & Record<never, never>>;
1057
+ generate: import("@orpc/server").Procedure<import("@orpc/server").MergedInitialContext<Record<never, never>, Record<never, never>, Record<never, never>>, Record<never, never>, z.ZodTuple<[z.ZodOptional<z.ZodString>, z.ZodOptional<z.ZodArray<z.ZodString>>, z.ZodObject<{
1058
+ owner: z.ZodOptional<z.ZodEnum<{
1059
+ none: "none";
1060
+ user: "user";
1061
+ }>>;
1062
+ timestamps: z.ZodOptional<z.ZodBoolean>;
1063
+ index: z.ZodOptional<z.ZodString>;
1064
+ force: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
1065
+ projectDir: z.ZodOptional<z.ZodString>;
1066
+ dryRun: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
1067
+ disableAnalytics: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
1068
+ }, z.core.$strip>], null>, import("@orpc/server").Schema<void, void>, import("@orpc/server").MergedErrorMap<Record<never, never>, Record<never, never>>, TrpcCliMeta & Record<never, never>>;
1069
+ generateJson: import("@orpc/server").Procedure<import("@orpc/server").MergedInitialContext<Record<never, never>, Record<never, never>, Record<never, never>>, Record<never, never>, z.ZodObject<{
1070
+ name: z.ZodString;
1071
+ fields: z.ZodArray<z.ZodObject<{
1072
+ name: z.ZodString;
1073
+ type: z.ZodEnum<{
1074
+ string: "string";
1075
+ bigint: "bigint";
1076
+ boolean: "boolean";
1077
+ date: "date";
1078
+ text: "text";
1079
+ integer: "integer";
1080
+ float: "float";
1081
+ timestamp: "timestamp";
1082
+ json: "json";
1083
+ uuid: "uuid";
1084
+ references: "references";
1085
+ }>;
1086
+ required: z.ZodOptional<z.ZodBoolean>;
1087
+ references: z.ZodOptional<z.ZodString>;
1088
+ cascade: z.ZodOptional<z.ZodBoolean>;
1089
+ }, z.core.$strict>>;
1090
+ owner: z.ZodOptional<z.ZodEnum<{
1091
+ none: "none";
1092
+ user: "user";
1093
+ }>>;
1094
+ timestamps: z.ZodOptional<z.ZodBoolean>;
1095
+ index: z.ZodOptional<z.ZodString>;
1096
+ force: z.ZodOptional<z.ZodBoolean>;
1097
+ projectDir: z.ZodOptional<z.ZodString>;
1098
+ dryRun: z.ZodOptional<z.ZodBoolean>;
1099
+ disableAnalytics: z.ZodOptional<z.ZodBoolean>;
1100
+ }, z.core.$strict>, import("@orpc/server").Schema<GenerateResult, GenerateResult>, import("@orpc/server").MergedErrorMap<Record<never, never>, Record<never, never>>, TrpcCliMeta & Record<never, never>>;
1042
1101
  history: import("@orpc/server").Procedure<import("@orpc/server").MergedInitialContext<Record<never, never>, Record<never, never>, Record<never, never>>, Record<never, never>, z.ZodObject<{
1043
1102
  limit: z.ZodDefault<z.ZodOptional<z.ZodNumber>>;
1044
1103
  clear: z.ZodDefault<z.ZodOptional<z.ZodBoolean>>;
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import { a as createAliceCli, c as router, d as CompatibilityError, f as DatabaseSetupError, g as ValidationError, h as UserCancelledError, i as create, l as ProjectLauncherSchema, m as ProjectCreationError, n as SchemaNameSchema, o as createVirtual, p as DirectoryConflictError, r as add, s as getSchemaResult, t as Result, u as CLIError } from "./src-D7QghBiE.mjs";
3
- import { i as VirtualFileSystem, n as GeneratorError, o as generate, r as TEMPLATE_COUNT, t as EMBEDDED_TEMPLATES } from "./dist-CWkT5Epw.mjs";
2
+ import { a as createAliceCli, c as router, d as CompatibilityError, f as DatabaseSetupError, g as ValidationError, h as UserCancelledError, i as create, l as ProjectLauncherSchema, m as ProjectCreationError, n as SchemaNameSchema, o as createVirtual, p as DirectoryConflictError, r as add, s as getSchemaResult, t as Result, u as CLIError } from "./src-xWMOCKGW.mjs";
3
+ import { c as generate, i as VirtualFileSystem, n as GeneratorError, r as TEMPLATE_COUNT, t as EMBEDDED_TEMPLATES } from "./dist-iQ2v9K-q.mjs";
4
4
  export { CLIError, CompatibilityError, DatabaseSetupError, DirectoryConflictError, EMBEDDED_TEMPLATES, GeneratorError, ProjectCreationError, ProjectLauncherSchema, Result, SchemaNameSchema, TEMPLATE_COUNT, UserCancelledError, ValidationError, VirtualFileSystem, add, create, createAliceCli, createVirtual, generate, getSchemaResult, router };
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as dependencyVersionMap, c as processAddonTemplates, d as processPnpmWorkspaceConfig, f as processTemplateString, h as join, i as VirtualFileSystem, l as processAddonsDeps, m as dirname, n as GeneratorError, o as generate, p as processTurboConfig, s as generateReproducibleCommand, t as EMBEDDED_TEMPLATES, u as processPackageConfigs } from "./dist-CWkT5Epw.mjs";
2
+ import { _ as validateResource, a as addRouteToApp, c as generate, d as processAddonTemplates, f as processAddonsDeps, g as processTurboConfig, h as processTemplateString, i as VirtualFileSystem, l as generateReproducibleCommand, m as processPnpmWorkspaceConfig, n as GeneratorError, o as addSchemaExport, p as processPackageConfigs, s as dependencyVersionMap, t as EMBEDDED_TEMPLATES, u as planResource, v as dirname, y as join } from "./dist-iQ2v9K-q.mjs";
3
3
  import z, { z as z$1 } from "zod";
4
4
  import { os } from "@orpc/server";
5
5
  import { Result, Result as Result$1, TaggedError } from "better-result";
@@ -10,6 +10,7 @@ import path from "node:path";
10
10
  import envPaths from "env-paths";
11
11
  import fs from "fs-extra";
12
12
  import { fileURLToPath } from "node:url";
13
+ import pluralize from "pluralize";
13
14
  import { SelectPrompt, isCancel as isCancel$1, wrapTextWithPrefix } from "@clack/core";
14
15
  import { consola, createConsola } from "consola";
15
16
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -416,6 +417,40 @@ const AddInputSchema = z$1.object({
416
417
  dryRun: z$1.boolean().optional(),
417
418
  disableAnalytics: z$1.boolean().optional()
418
419
  }).strict();
420
+ const GENERATE_FIELD_TYPES = [
421
+ "string",
422
+ "text",
423
+ "integer",
424
+ "bigint",
425
+ "float",
426
+ "boolean",
427
+ "timestamp",
428
+ "date",
429
+ "json",
430
+ "uuid",
431
+ "references"
432
+ ];
433
+ const GenerateFieldTypeSchema = z$1.enum(GENERATE_FIELD_TYPES).describe("Column type. `references` points at another table");
434
+ const snakeCaseName = z$1.string().min(1).max(63).regex(/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/, "Use snake_case: lowercase letters and digits separated by underscores");
435
+ const GenerateFieldSchema = z$1.object({
436
+ name: snakeCaseName.describe("Column name in snake_case"),
437
+ type: GenerateFieldTypeSchema,
438
+ required: z$1.boolean().optional().describe("Whether the column is NOT NULL (default true)"),
439
+ references: snakeCaseName.optional().describe("Table the column points at (only for the `references` type)"),
440
+ cascade: z$1.boolean().optional().describe("Delete this row when the referenced row is deleted")
441
+ }).strict();
442
+ const GenerateOwnerSchema = z$1.enum(["user", "none"]).describe("Who owns the rows: the signed-in user (default) or nobody");
443
+ const GenerateInputSchema = z$1.object({
444
+ name: snakeCaseName.describe("Plural table name in snake_case, for example blog_posts"),
445
+ fields: z$1.array(GenerateFieldSchema).min(1).max(40),
446
+ owner: GenerateOwnerSchema.optional(),
447
+ timestamps: z$1.boolean().optional().describe("Add createdAt and updatedAt (default true)"),
448
+ index: snakeCaseName.optional().describe("Name of a field to index"),
449
+ force: z$1.boolean().optional().describe("Overwrite files of an existing resource"),
450
+ projectDir: z$1.string().optional(),
451
+ dryRun: z$1.boolean().optional(),
452
+ disableAnalytics: z$1.boolean().optional()
453
+ }).strict();
419
454
  CreateInputSchema.safeExtend({ projectDirectory: z$1.string().optional() }).strict();
420
455
  const ProjectConfigSchema = z$1.object({
421
456
  projectName: z$1.string(),
@@ -555,6 +590,9 @@ function getCreateInputJsonSchema() {
555
590
  function getAddInputJsonSchema() {
556
591
  return z$1.toJSONSchema(AddInputSchema);
557
592
  }
593
+ function getGenerateInputJsonSchema() {
594
+ return z$1.toJSONSchema(GenerateInputSchema);
595
+ }
558
596
  function getProjectConfigJsonSchema() {
559
597
  return z$1.toJSONSchema(ProjectConfigSchema);
560
598
  }
@@ -589,6 +627,7 @@ function getAllJsonSchemas() {
589
627
  dbSetupOptions: getDbSetupOptionsJsonSchema(),
590
628
  createInput: getCreateInputJsonSchema(),
591
629
  addInput: getAddInputJsonSchema(),
630
+ generateInput: getGenerateInputJsonSchema(),
592
631
  projectConfig: getProjectConfigJsonSchema(),
593
632
  aliceConfig: getAliceConfigJsonSchema(),
594
633
  aliceConfigFile: getAliceConfigFileJsonSchema(),
@@ -6393,6 +6432,279 @@ async function handleDirectoryConflictProgrammatically(currentPathInput, strateg
6393
6432
  }
6394
6433
  }
6395
6434
  //#endregion
6435
+ //#region src/prompts/generate-prompts.ts
6436
+ const SNAKE_CASE = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/;
6437
+ const NOT_REFERENCEABLE = /* @__PURE__ */ new Set([
6438
+ "index",
6439
+ "auth",
6440
+ "files"
6441
+ ]);
6442
+ function snakeCaseError(value) {
6443
+ return value && SNAKE_CASE.test(value) ? void 0 : "Use snake_case: lowercase letters and digits separated by underscores";
6444
+ }
6445
+ function unwrap(value) {
6446
+ if (isCancel(value)) {
6447
+ cancel("Operation cancelled");
6448
+ throw new UserCancelledError({ message: "Operation cancelled" });
6449
+ }
6450
+ return value;
6451
+ }
6452
+ /** Tables a new field can point at: the user table plus resources generated earlier. */
6453
+ async function referenceableTables(projectDir) {
6454
+ const schemaDir = path.join(projectDir, "packages/database/src/schema");
6455
+ return ["users", ...(await fs.pathExists(schemaDir) ? await fs.readdir(schemaDir) : []).filter((entry) => entry.endsWith(".ts")).map((entry) => entry.slice(0, -3)).filter((name) => !NOT_REFERENCEABLE.has(name)).map((name) => name.replaceAll("-", "_"))];
6456
+ }
6457
+ async function promptForResource(projectDir, initialName) {
6458
+ return Result.tryPromise({
6459
+ try: async () => {
6460
+ markPromptShown();
6461
+ const name = initialName ?? unwrap(await text({
6462
+ message: "Table name (plural, snake_case)",
6463
+ placeholder: "blog_posts",
6464
+ validate: snakeCaseError
6465
+ }));
6466
+ const tables = await referenceableTables(projectDir);
6467
+ const fields = [];
6468
+ let addMore = true;
6469
+ while (addMore) {
6470
+ const type = unwrap(await select({
6471
+ message: "Field type",
6472
+ options: GENERATE_FIELD_TYPES.filter((candidate) => candidate !== "references" || tables.length > 0).map((candidate) => ({
6473
+ value: candidate,
6474
+ label: candidate
6475
+ }))
6476
+ }));
6477
+ if (type === "references") {
6478
+ const references = unwrap(await select({
6479
+ message: "Which table does it point at?",
6480
+ options: tables.map((table) => ({
6481
+ value: table,
6482
+ label: table
6483
+ }))
6484
+ }));
6485
+ const fieldName = unwrap(await text({
6486
+ message: "Field name (snake_case)",
6487
+ initialValue: `${pluralize.singular(references)}_id`,
6488
+ validate: snakeCaseError
6489
+ }));
6490
+ const cascade = unwrap(await confirm({
6491
+ message: "Delete this row when the other one is deleted?",
6492
+ initialValue: false
6493
+ }));
6494
+ const required = unwrap(await confirm({
6495
+ message: "Is it required?",
6496
+ initialValue: true
6497
+ }));
6498
+ fields.push({
6499
+ name: fieldName,
6500
+ type,
6501
+ references,
6502
+ cascade,
6503
+ required
6504
+ });
6505
+ } else {
6506
+ const fieldName = unwrap(await text({
6507
+ message: "Field name (snake_case)",
6508
+ validate: snakeCaseError
6509
+ }));
6510
+ const required = unwrap(await confirm({
6511
+ message: "Is it required?",
6512
+ initialValue: true
6513
+ }));
6514
+ fields.push({
6515
+ name: fieldName,
6516
+ type,
6517
+ required
6518
+ });
6519
+ }
6520
+ addMore = unwrap(await confirm({
6521
+ message: "Add another field?",
6522
+ initialValue: false
6523
+ }));
6524
+ }
6525
+ return {
6526
+ name,
6527
+ fields,
6528
+ index: unwrap(await confirm({
6529
+ message: "Index one of the fields?",
6530
+ initialValue: false
6531
+ })) ? unwrap(await select({
6532
+ message: "Which field?",
6533
+ options: fields.map((field) => ({
6534
+ value: field.name,
6535
+ label: field.name
6536
+ }))
6537
+ })) : void 0,
6538
+ timestamps: unwrap(await confirm({
6539
+ message: "Add created and updated timestamps?",
6540
+ initialValue: true
6541
+ })),
6542
+ owner: unwrap(await confirm({
6543
+ message: "Does each row belong to the signed-in user?",
6544
+ initialValue: true
6545
+ })) ? "user" : "none"
6546
+ };
6547
+ },
6548
+ catch: (cause) => UserCancelledError.is(cause) ? cause : new UserCancelledError({ message: "Operation cancelled" })
6549
+ });
6550
+ }
6551
+ //#endregion
6552
+ //#region src/helpers/core/generate-handler.ts
6553
+ const SCHEMA_INDEX = "packages/database/src/schema/index.ts";
6554
+ const SERVER_APP = "apps/server/src/app.ts";
6555
+ async function generateHandler(input, options = {}) {
6556
+ const { silent = false, mode } = options;
6557
+ return runWithContextAsync({
6558
+ silent,
6559
+ mode,
6560
+ analyticsDisabled: input.disableAnalytics
6561
+ }, async () => {
6562
+ const result = await generateHandlerInternal(input);
6563
+ if (result.isOk()) return result.value;
6564
+ const error = result.error;
6565
+ if (UserCancelledError.is(error)) return isSilent() ? {
6566
+ success: false,
6567
+ projectDir: "",
6568
+ error: error.message
6569
+ } : void 0;
6570
+ if (isSilent()) return {
6571
+ success: false,
6572
+ projectDir: "",
6573
+ error: error.message
6574
+ };
6575
+ displayError(error);
6576
+ process.exit(1);
6577
+ });
6578
+ }
6579
+ async function generateHandlerInternal(partial) {
6580
+ const projectDirInput = partial.projectDir || process.cwd();
6581
+ const hardening = validateAgentSafePathInput(projectDirInput, "projectDir");
6582
+ if (hardening.isErr()) return Result.err(new CLIError({
6583
+ message: hardening.error.message,
6584
+ cause: hardening.error
6585
+ }));
6586
+ const projectDir = path.resolve(projectDirInput);
6587
+ if (!isSilent()) {
6588
+ renderTitle();
6589
+ intro(pc.magenta("Generate a resource"));
6590
+ }
6591
+ const config = await detectProjectConfig(projectDir);
6592
+ if (!config) return Result.err(new CLIError({ message: `No Alice project found in "${projectDir}". Make sure alice.jsonc exists.` }));
6593
+ for (const required of [SCHEMA_INDEX, SERVER_APP]) if (!await fs.pathExists(path.join(projectDir, required))) return Result.err(new CLIError({ message: `${required} is missing, so there is nowhere to add the resource. Run this from the root of an Alice project.` }));
6594
+ let input;
6595
+ if (partial.name && partial.fields && partial.fields.length > 0) input = {
6596
+ ...partial,
6597
+ name: partial.name,
6598
+ fields: partial.fields
6599
+ };
6600
+ else if (isSilent()) return Result.err(new CLIError({ message: "A resource name and at least one field are required." }));
6601
+ else {
6602
+ const prompted = await promptForResource(projectDir, partial.name);
6603
+ if (prompted.isErr()) return Result.err(prompted.error);
6604
+ input = {
6605
+ ...partial,
6606
+ ...prompted.value
6607
+ };
6608
+ }
6609
+ const problems = validateResource(input);
6610
+ if (problems.length > 0) return Result.err(new CLIError({ message: problems.join("\n") }));
6611
+ const plan = planResource(input, config.projectName);
6612
+ for (const table of plan.referencedTables) {
6613
+ const slug = table.replaceAll("_", "-");
6614
+ if (!await fs.pathExists(path.join(projectDir, `packages/database/src/schema/${slug}.ts`))) return Result.err(new CLIError({ message: `"${table}" does not exist yet. Generate it first with: alice generate ${table} ...` }));
6615
+ }
6616
+ const existing = [];
6617
+ for (const file of plan.files) if (await fs.pathExists(path.join(projectDir, file.path))) existing.push(file.path);
6618
+ if (existing.length > 0 && !input.force) return Result.err(new CLIError({ message: `${plan.names.table} already exists:\n${existing.map((file) => ` ${file}`).join("\n")}\nRun with --force to overwrite these files.` }));
6619
+ const createdFiles = plan.files.map((file) => file.path);
6620
+ const updatedFiles = [SCHEMA_INDEX, SERVER_APP];
6621
+ if (input.dryRun) {
6622
+ if (!isSilent()) {
6623
+ log.success(pc.green("Dry run passed · no files written"));
6624
+ log.message(pc.dim(createdFiles.join("\n")));
6625
+ outro(pc.dim("Project unchanged"));
6626
+ }
6627
+ return Result.ok({
6628
+ success: true,
6629
+ projectDir,
6630
+ resource: plan.names.table,
6631
+ createdFiles,
6632
+ updatedFiles,
6633
+ dryRun: true
6634
+ });
6635
+ }
6636
+ const written = await Result.tryPromise({
6637
+ try: async () => {
6638
+ for (const file of plan.files) await fs.outputFile(path.join(projectDir, file.path), file.content);
6639
+ const indexPath = path.join(projectDir, SCHEMA_INDEX);
6640
+ await fs.writeFile(indexPath, addSchemaExport(await fs.readFile(indexPath, "utf-8"), plan.schemaModule));
6641
+ const appPath = path.join(projectDir, SERVER_APP);
6642
+ await fs.writeFile(appPath, addRouteToApp(await fs.readFile(appPath, "utf-8"), plan.route));
6643
+ },
6644
+ catch: (cause) => new CLIError({
6645
+ message: `Could not write the resource: ${cause instanceof Error ? cause.message : String(cause)}`,
6646
+ cause
6647
+ })
6648
+ });
6649
+ if (written.isErr()) return Result.err(written.error);
6650
+ const openApiRegenerated = await regenerateOpenApi(projectDir, config.packageManager);
6651
+ const nextSteps = [...openApiRegenerated ? [] : [`${config.packageManager} run openapi:generate # refresh the API docs`], `${config.packageManager} run db:push # create the table (or db:generate then db:migrate)`];
6652
+ if (!isSilent()) {
6653
+ log.success(pc.green(`Generated ${plan.names.table}`));
6654
+ log.message([...createdFiles.map((file) => ` + ${file}`), ...updatedFiles.map((file) => ` ~ ${file}`)].map((line) => pc.dim(line)).join("\n"));
6655
+ outro(`Next steps\n${nextSteps.map((step) => ` ${pc.cyan(step)}`).join("\n")}`);
6656
+ }
6657
+ return Result.ok({
6658
+ success: true,
6659
+ projectDir,
6660
+ resource: plan.names.table,
6661
+ createdFiles,
6662
+ updatedFiles,
6663
+ openApiRegenerated,
6664
+ nextSteps
6665
+ });
6666
+ }
6667
+ /**
6668
+ * The docs site renders apps/fumadocs/openapi.json, and a server test fails when it is stale.
6669
+ * Regenerating needs installed dependencies, so this is skipped (and reported) without them.
6670
+ */
6671
+ async function regenerateOpenApi(projectDir, packageManager) {
6672
+ if (shouldSkipExternalCommands()) return false;
6673
+ if (!await fs.pathExists(path.join(projectDir, "node_modules"))) return false;
6674
+ return (await Result.tryPromise({
6675
+ try: () => $({
6676
+ cwd: projectDir,
6677
+ stdio: "ignore"
6678
+ })`${packageManager} run openapi:generate`,
6679
+ catch: (cause) => cause
6680
+ })).isOk();
6681
+ }
6682
+ //#endregion
6683
+ //#region src/utils/field-spec.ts
6684
+ const FIELD_SPEC = /^([a-z][a-z0-9_]*):([a-z]+)(?:\(([a-z][a-z0-9_]*)\))?(!cascade)?(\?)?$/;
6685
+ const isFieldType = (value) => GENERATE_FIELD_TYPES.some((type) => type === value);
6686
+ /**
6687
+ * Parses `title:string`, `body:text?` (optional) and `author_id:references(users)!cascade`
6688
+ * into the fields the generator takes.
6689
+ */
6690
+ function parseFieldSpecs(specs) {
6691
+ const fields = [];
6692
+ for (const spec of specs) {
6693
+ const match = FIELD_SPEC.exec(spec);
6694
+ if (!match) return Result.err(new CLIError({ message: `Cannot read the field "${spec}". Write fields as name:type, for example title:string, body:text? or author_id:references(users)` }));
6695
+ const [, name = "", type = "", references, cascade, optional] = match;
6696
+ if (!isFieldType(type)) return Result.err(new CLIError({ message: `Unknown field type "${type}" in "${spec}". Use one of: ${GENERATE_FIELD_TYPES.join(", ")}` }));
6697
+ fields.push({
6698
+ name,
6699
+ type,
6700
+ required: optional === void 0,
6701
+ references,
6702
+ cascade: cascade === void 0 ? void 0 : true
6703
+ });
6704
+ }
6705
+ return Result.ok(fields);
6706
+ }
6707
+ //#endregion
6396
6708
  //#region src/index.ts
6397
6709
  const SchemaNameSchema = z.enum([
6398
6710
  "all",
@@ -6417,6 +6729,7 @@ const SchemaNameSchema = z.enum([
6417
6729
  "dbSetupOptions",
6418
6730
  "createInput",
6419
6731
  "addInput",
6732
+ "generateInput",
6420
6733
  "projectConfig",
6421
6734
  "aliceConfig",
6422
6735
  "aliceConfigFile",
@@ -6520,6 +6833,46 @@ const router = os.router({
6520
6833
  if (!result.success) throw new CLIError({ message: result.error || "Unknown error occurred" });
6521
6834
  return result;
6522
6835
  }),
6836
+ generate: command.meta({
6837
+ description: "Generate a database table and a full CRUD API for a new resource in an existing Alice project",
6838
+ negateBooleans: true
6839
+ }).input(z.tuple([
6840
+ z.string().optional().describe("Plural table name in snake_case, for example blog_posts"),
6841
+ z.array(z.string()).optional().describe("Fields as name:type, e.g. title:string body:text? author_id:references(users)"),
6842
+ z.object({
6843
+ owner: GenerateOwnerSchema.optional(),
6844
+ timestamps: z.boolean().optional().describe("Add createdAt and updatedAt (default true)"),
6845
+ index: z.string().optional().describe("Name of a field to index"),
6846
+ force: z.boolean().optional().default(false).describe("Overwrite an existing resource"),
6847
+ projectDir: z.string().optional().describe("Project directory (defaults to current)"),
6848
+ dryRun: z.boolean().optional().default(false).describe("Preview the files without writing them"),
6849
+ disableAnalytics: z.boolean().optional().default(false).describe("Disable analytics")
6850
+ })
6851
+ ])).handler(async ({ input }) => {
6852
+ const [name, fieldSpecs, options] = input;
6853
+ const parsed = parseFieldSpecs(fieldSpecs ?? []);
6854
+ if (parsed.isErr()) {
6855
+ displayError(parsed.error);
6856
+ process.exit(1);
6857
+ }
6858
+ await generateHandler({
6859
+ ...options,
6860
+ name,
6861
+ fields: parsed.value.length > 0 ? parsed.value : void 0
6862
+ });
6863
+ }),
6864
+ generateJson: command.meta({
6865
+ description: "Generate a resource from a raw JSON payload (agent-friendly)",
6866
+ jsonInput: "always"
6867
+ }).input(GenerateInputSchema).handler(async ({ input }) => {
6868
+ const result = await generateHandler(input, {
6869
+ silent: true,
6870
+ mode: "json"
6871
+ });
6872
+ if (!result) throw new UserCancelledError({ message: "Operation cancelled" });
6873
+ if (!result.success) throw new CLIError({ message: result.error || "Unknown error occurred" });
6874
+ return result;
6875
+ }),
6523
6876
  history: command.meta({ description: "Show project creation history" }).input(z.object({
6524
6877
  limit: z.number().optional().default(10).describe("Number of entries to show"),
6525
6878
  clear: z.boolean().optional().default(false).describe("Clear all history"),
package/dist/virtual.mjs CHANGED
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import { i as VirtualFileSystem, n as GeneratorError, o as generate, r as TEMPLATE_COUNT, t as EMBEDDED_TEMPLATES } from "./dist-CWkT5Epw.mjs";
2
+ import { c as generate, i as VirtualFileSystem, n as GeneratorError, r as TEMPLATE_COUNT, t as EMBEDDED_TEMPLATES } from "./dist-iQ2v9K-q.mjs";
3
3
  import { Result } from "better-result";
4
4
  export { EMBEDDED_TEMPLATES, GeneratorError, Result, TEMPLATE_COUNT, VirtualFileSystem, generate };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alicesystems/cli",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "Scaffold an opinionated full-stack TypeScript monorepo: Next.js, Expo, Hono, Drizzle, Better Auth",
5
5
  "keywords": [
6
6
  "better-auth",
@@ -79,6 +79,7 @@
79
79
  "jsonc-parser": "^3.3.1",
80
80
  "oxfmt": "^0.72.0",
81
81
  "picocolors": "^1.1.1",
82
+ "pluralize": "^8.0.0",
82
83
  "semver": "^7.8.5",
83
84
  "tinyglobby": "^0.2.17",
84
85
  "trpc-cli": "^0.16.0",
@@ -93,6 +94,7 @@
93
94
  "@types/bun": "^1.4.3",
94
95
  "@types/fs-extra": "^11.0.4",
95
96
  "@types/node": "^26.5.0",
97
+ "@types/pluralize": "^0.0.33",
96
98
  "@types/semver": "^7.8.0",
97
99
  "publint": "^0.3.24",
98
100
  "tsdown": "^0.23.0",