clawnify 0.1.15 → 0.1.17

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.
@@ -14,7 +14,7 @@ import {
14
14
  readProject,
15
15
  saveAuth,
16
16
  saveProject
17
- } from "./chunk-GXEDX326.js";
17
+ } from "./chunk-CMM323B2.js";
18
18
 
19
19
  // src/cli.ts
20
20
  import { Command } from "commander";
@@ -169,8 +169,106 @@ async function loginCommand() {
169
169
  }
170
170
 
171
171
  // src/commands/deploy.ts
172
- import path from "path";
172
+ import path2 from "path";
173
173
  import readline2 from "readline";
174
+
175
+ // src/lib/sync-schema.ts
176
+ import fs from "fs/promises";
177
+ import path from "path";
178
+ import { execSync } from "child_process";
179
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
180
+ async function resolveApp(idOrSlug, orgFilter) {
181
+ const orgs = await listMyOrgs();
182
+ if (orgs.length === 0) return null;
183
+ const candidates = orgFilter ? orgs.filter((o) => o.id === orgFilter || o.slug === orgFilter) : orgs;
184
+ if (candidates.length === 0) return null;
185
+ const isUuid = UUID_RE.test(idOrSlug);
186
+ if (isUuid) {
187
+ for (const org of candidates) {
188
+ const res = await api.get(`/v1/apps/${idOrSlug}`, { orgId: org.id });
189
+ if (res.ok) {
190
+ const app = await res.json();
191
+ return { org, appId: app.id, slug: app.slug };
192
+ }
193
+ }
194
+ return null;
195
+ }
196
+ for (const org of candidates) {
197
+ const res = await api.get(`/v1/apps`, { orgId: org.id });
198
+ if (!res.ok) continue;
199
+ const payload = await res.json();
200
+ const apps = Array.isArray(payload) ? payload : payload.apps ?? [];
201
+ const match = apps.find((a) => a.slug === idOrSlug);
202
+ if (match) return { org, appId: match.id, slug: match.slug };
203
+ }
204
+ return null;
205
+ }
206
+ async function fetchSchema(ref) {
207
+ const appId = "appId" in ref ? ref.appId : ref.appId;
208
+ const orgId = "orgId" in ref ? ref.orgId : ref.org.id;
209
+ const res = await api.get(`/v1/apps/${appId}/schema`, { orgId });
210
+ if (!res.ok) {
211
+ if (res.status === 404) return null;
212
+ const err = await res.json().catch(() => ({}));
213
+ throw new Error(`Schema fetch failed: ${err.error ?? res.statusText}`);
214
+ }
215
+ const data = await res.json();
216
+ return data.schema_sql;
217
+ }
218
+ async function writeSchema(targetPath, schema, options = {}) {
219
+ if (schema === null) {
220
+ return { status: "no-schema", path: targetPath };
221
+ }
222
+ let existing = null;
223
+ try {
224
+ existing = await fs.readFile(targetPath, "utf8");
225
+ } catch (err) {
226
+ if (err.code !== "ENOENT") throw err;
227
+ }
228
+ if (existing === schema) {
229
+ return { status: "unchanged", path: targetPath };
230
+ }
231
+ if (existing !== null && !options.force) {
232
+ const dir = path.dirname(path.resolve(targetPath));
233
+ if (isInsideGitRepo(dir)) {
234
+ if (hasUncommittedChanges(dir, targetPath)) {
235
+ return { status: "refused-uncommitted", path: targetPath };
236
+ }
237
+ } else {
238
+ return { status: "refused-different", path: targetPath };
239
+ }
240
+ }
241
+ await fs.mkdir(path.dirname(targetPath), { recursive: true });
242
+ await fs.writeFile(targetPath, schema, "utf8");
243
+ return { status: "written", path: targetPath, bytes: schema.length };
244
+ }
245
+ function isInsideGitRepo(dir) {
246
+ try {
247
+ execSync("git rev-parse --is-inside-work-tree", {
248
+ cwd: dir,
249
+ stdio: ["ignore", "pipe", "ignore"]
250
+ });
251
+ return true;
252
+ } catch {
253
+ return false;
254
+ }
255
+ }
256
+ function hasUncommittedChanges(dir, filePath) {
257
+ try {
258
+ const relative = path.relative(dir, path.resolve(filePath));
259
+ const status = execSync(`git status --porcelain -- "${relative}"`, {
260
+ cwd: dir,
261
+ stdio: ["ignore", "pipe", "ignore"]
262
+ }).toString().trim();
263
+ return status.length > 0;
264
+ } catch {
265
+ return true;
266
+ }
267
+ }
268
+
269
+ // src/commands/deploy.ts
270
+ var EXIT_USAGE = 64;
271
+ var EXIT_CONFLICT_NEEDS_DECISION = 75;
174
272
  function ask(question) {
175
273
  const rl = readline2.createInterface({
176
274
  input: process.stdin,
@@ -226,15 +324,97 @@ function assertNodeVersion() {
226
324
  process.exit(1);
227
325
  }
228
326
  }
229
- async function deployCommand(dir, options) {
327
+ async function resolveOrgId(options, linkedProject) {
328
+ if (options.org) {
329
+ const orgs = await listMyOrgs();
330
+ const match = orgs.find((o) => o.id === options.org || o.slug === options.org);
331
+ if (!match) {
332
+ console.error(
333
+ `No org matched "${options.org}". Available: ${orgs.map((o) => o.slug).join(", ")}`
334
+ );
335
+ process.exit(EXIT_USAGE);
336
+ }
337
+ if (linkedProject?.app_id && linkedProject.org_id && linkedProject.org_id !== match.id) {
338
+ console.error(
339
+ `This project is linked to a different org (${linkedProject.org_id}).
340
+ --org ${options.org} resolves to ${match.id}.
341
+ Re-link first: clawnify link ${linkedProject.app_id} --org ${options.org}`
342
+ );
343
+ process.exit(1);
344
+ }
345
+ return match.id;
346
+ }
347
+ if (linkedProject?.app_id && linkedProject.org_id) {
348
+ return linkedProject.org_id;
349
+ }
350
+ return void 0;
351
+ }
352
+ async function resolveConflictDecision(options, conflict) {
353
+ if (options.updateExisting) return "update";
354
+ if (options.createNew) return "create";
355
+ if (options.yes) return "update";
356
+ if (!process.stdin.isTTY) {
357
+ console.error(
358
+ `
359
+ Slug '${conflict.slug}' is taken in this organization.
360
+ Pass one of:
361
+ --update-existing overwrite the existing app
362
+ --create-new deploy as '${conflict.suggested_slug}'
363
+ --yes default to update (safest)
364
+ `
365
+ );
366
+ process.exit(EXIT_CONFLICT_NEEDS_DECISION);
367
+ }
368
+ console.log(
369
+ `
370
+ Slug '${conflict.slug}' is taken in this organization (currently held by an app named '${conflict.existing_app_name}').
371
+ `
372
+ );
373
+ console.log(` 1) Update that app \u2014 deploy this source over it`);
374
+ console.log(` 2) Create a new app at slug '${conflict.suggested_slug}'
375
+ `);
376
+ const answer = await ask(" Choose [1/2] (default 1): ");
377
+ if (answer === "" || answer === "1") return "update";
378
+ if (answer === "2") return "create";
379
+ console.error(
380
+ `
381
+ Cancelled. Received '${answer}' \u2014 expected 1 or 2.
382
+ For non-interactive use, pass --update-existing or --create-new.
383
+ `
384
+ );
385
+ return "cancel";
386
+ }
387
+ function summarizeArchive(buf, files, framework, name) {
388
+ const sizeKB = (buf.length / 1024).toFixed(1);
389
+ console.log(`
390
+ Dry run \u2014 would deploy '${name}' (${framework})`);
391
+ console.log(` Archive: ${files.length} files, ${sizeKB}KB gzipped
392
+ `);
393
+ const preview = files.slice(0, 25);
394
+ for (const f of preview) console.log(` ${f}`);
395
+ if (files.length > preview.length) {
396
+ console.log(` ... and ${files.length - preview.length} more`);
397
+ }
398
+ console.log();
399
+ }
400
+ async function deployCommand(dir, options = {}) {
230
401
  assertNodeVersion();
231
402
  let appId;
232
403
  let slug;
233
404
  let appToken;
234
- if (options?.from) {
405
+ let resolvedOrgId;
406
+ let syncTargetDir;
407
+ if (options.from) {
235
408
  const repo = options.from.replace(/^github:/, "");
409
+ if (options.dryRun) {
410
+ console.log(`
411
+ Dry run \u2014 would deploy from GitHub repo '${repo}' (branch: main)
412
+ `);
413
+ return;
414
+ }
236
415
  console.log(`Deploying from ${repo}...`);
237
- const res = await api.post("/v1/apps/deploy", { repo, branch: "main" });
416
+ const orgId = options.org ? await resolveOrgId(options, null) : void 0;
417
+ const res = await api.post("/v1/apps/deploy", { repo, branch: "main" }, { orgId });
238
418
  if (!res.ok) {
239
419
  const err = await res.json().catch(() => ({}));
240
420
  console.error(`Deploy failed: ${err.error || res.statusText}`);
@@ -244,17 +424,30 @@ async function deployCommand(dir, options) {
244
424
  appId = data.app_id;
245
425
  slug = data.slug;
246
426
  appToken = data.app_token;
427
+ resolvedOrgId = orgId;
247
428
  } else {
248
- const resolvedDir = dir ? path.resolve(dir) : process.cwd();
429
+ const resolvedDir = dir ? path2.resolve(dir) : process.cwd();
430
+ syncTargetDir = resolvedDir;
249
431
  const manifest = readManifest(resolvedDir);
250
- const baseName = options?.name || manifest?.name || path.basename(resolvedDir);
432
+ const baseName = options.name || manifest?.name || path2.basename(resolvedDir);
251
433
  const framework = manifest?.app?.framework || "vite-preact";
252
434
  const linkedProject = readProject(resolvedDir);
253
- const archive = createArchive(resolvedDir);
254
- const projectOrgId = linkedProject?.org_id;
435
+ const { archive, files } = createArchive(resolvedDir);
436
+ const orgId = await resolveOrgId(options, linkedProject);
437
+ if (options.dryRun) {
438
+ summarizeArchive(archive, files, framework, baseName);
439
+ if (linkedProject?.app_id) {
440
+ console.log(` Would update existing app: ${linkedProject.slug ?? linkedProject.app_id}
441
+ `);
442
+ } else {
443
+ console.log(` Would create new app: ${baseName}
444
+ `);
445
+ }
446
+ return;
447
+ }
255
448
  if (linkedProject?.app_id) {
256
449
  console.log(`Updating ${baseName} (${linkedProject.slug ?? linkedProject.app_id})...`);
257
- const result2 = await uploadRedeploy(linkedProject.app_id, archive, projectOrgId);
450
+ const result2 = await uploadRedeploy(linkedProject.app_id, archive, orgId);
258
451
  if (!result2.ok) {
259
452
  console.error(`Deploy failed: ${result2.error}`);
260
453
  process.exit(1);
@@ -262,23 +455,14 @@ async function deployCommand(dir, options) {
262
455
  appId = result2.data.app_id;
263
456
  slug = result2.data.slug;
264
457
  appToken = result2.data.app_token;
265
- saveProject(resolvedDir, { org_id: projectOrgId, app_id: appId, slug, app_token: appToken });
458
+ saveProject(resolvedDir, { org_id: orgId, app_id: appId, slug, app_token: appToken });
266
459
  } else {
267
460
  console.log(`Deploying ${baseName}...`);
268
- let result2 = await uploadDeploy(archive, baseName, framework, projectOrgId);
461
+ let result2 = await uploadDeploy(archive, baseName, framework, orgId);
269
462
  if (!result2.ok && "conflict" in result2) {
270
- const c = result2.conflict;
271
- console.log(
272
- `
273
- An app named '${c.existing_app_name}' (slug: ${c.slug}) already exists in this organization.
274
- `
275
- );
276
- console.log(` 1) Update the existing app`);
277
- console.log(` 2) Create a new app as '${c.suggested_slug}'
278
- `);
279
- const answer = await ask(" Choose [1/2]: ");
280
- if (answer === "1" || answer === "") {
281
- const redeployResult = await uploadRedeploy(c.existing_app_id, archive, projectOrgId);
463
+ const decision = await resolveConflictDecision(options, result2.conflict);
464
+ if (decision === "update") {
465
+ const redeployResult = await uploadRedeploy(result2.conflict.existing_app_id, archive, orgId);
282
466
  if (!redeployResult.ok) {
283
467
  console.error(`Deploy failed: ${redeployResult.error}`);
284
468
  process.exit(1);
@@ -286,8 +470,8 @@ async function deployCommand(dir, options) {
286
470
  appId = redeployResult.data.app_id;
287
471
  slug = redeployResult.data.slug;
288
472
  appToken = redeployResult.data.app_token;
289
- } else if (answer === "2") {
290
- result2 = await uploadDeploy(archive, c.suggested_slug, framework, projectOrgId);
473
+ } else if (decision === "create") {
474
+ result2 = await uploadDeploy(archive, result2.conflict.suggested_slug, framework, orgId);
291
475
  if (!result2.ok) {
292
476
  const errMsg = "conflict" in result2 ? "Slug still conflicts" : result2.error;
293
477
  console.error(`Deploy failed: ${errMsg}`);
@@ -297,8 +481,7 @@ async function deployCommand(dir, options) {
297
481
  slug = result2.data.slug;
298
482
  appToken = result2.data.app_token;
299
483
  } else {
300
- console.error("Cancelled.");
301
- process.exit(1);
484
+ process.exit(EXIT_CONFLICT_NEEDS_DECISION);
302
485
  }
303
486
  } else if (!result2.ok) {
304
487
  console.error(`Deploy failed: ${result2.error}`);
@@ -308,7 +491,8 @@ async function deployCommand(dir, options) {
308
491
  slug = result2.data.slug;
309
492
  appToken = result2.data.app_token;
310
493
  }
311
- saveProject(resolvedDir, { org_id: projectOrgId, app_id: appId, slug, app_token: appToken });
494
+ saveProject(resolvedDir, { org_id: orgId, app_id: appId, slug, app_token: appToken });
495
+ resolvedOrgId = orgId;
312
496
  }
313
497
  }
314
498
  const result = await pollUntilReady(appId);
@@ -324,6 +508,40 @@ async function deployCommand(dir, options) {
324
508
  `);
325
509
  console.log(` Open: clawnify open ${slug}
326
510
  `);
511
+ if (syncTargetDir && !options.noSync && resolvedOrgId) {
512
+ try {
513
+ const schema = await fetchSchema({ appId, orgId: resolvedOrgId });
514
+ const target = path2.join(syncTargetDir, "schema.sql");
515
+ const writeResult = await writeSchema(target, schema);
516
+ const rel = path2.relative(process.cwd(), writeResult.path) || writeResult.path;
517
+ switch (writeResult.status) {
518
+ case "written":
519
+ console.log(` Synced ${rel} (${writeResult.bytes} bytes)
520
+ `);
521
+ break;
522
+ case "refused-uncommitted":
523
+ console.log(
524
+ ` ${rel} has uncommitted changes \u2014 not overwriting.
525
+ Run \`clawnify pull schema --force --from ${slug}\` to overwrite.
526
+ `
527
+ );
528
+ break;
529
+ case "refused-different":
530
+ console.log(
531
+ ` ${rel} differs from the deployed copy (not in git).
532
+ Run \`clawnify pull schema --force --from ${slug}\` to overwrite.
533
+ `
534
+ );
535
+ break;
536
+ case "no-schema":
537
+ case "unchanged":
538
+ break;
539
+ }
540
+ } catch (err) {
541
+ console.log(` (schema sync skipped: ${err.message})
542
+ `);
543
+ }
544
+ }
327
545
  }
328
546
 
329
547
  // src/commands/ls.ts
@@ -443,8 +661,8 @@ async function whoamiCommand() {
443
661
  }
444
662
 
445
663
  // src/commands/init.ts
446
- import fs from "fs";
447
- import path2 from "path";
664
+ import fs2 from "fs";
665
+ import path3 from "path";
448
666
  import readline4 from "readline";
449
667
  function ask2(question) {
450
668
  const rl = readline4.createInterface({
@@ -464,7 +682,7 @@ function slugify(name) {
464
682
  async function initCommand(dir, opts) {
465
683
  const name = opts?.name || await ask2("App name: ") || "my-app";
466
684
  const slug = slugify(name);
467
- const targetDir = dir ? path2.resolve(dir) : path2.resolve(slug);
685
+ const targetDir = dir ? path3.resolve(dir) : path3.resolve(slug);
468
686
  let template;
469
687
  if (opts?.template) {
470
688
  template = opts.template === "crud" ? "crud" : "blank";
@@ -477,12 +695,12 @@ async function initCommand(dir, opts) {
477
695
  const templateChoice = await ask2("Template [1]: ") || "1";
478
696
  template = templateChoice === "2" ? "crud" : "blank";
479
697
  }
480
- if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length > 0) {
698
+ if (fs2.existsSync(targetDir) && fs2.readdirSync(targetDir).length > 0) {
481
699
  console.error(`Directory ${targetDir} is not empty.`);
482
700
  process.exit(1);
483
701
  }
484
- fs.mkdirSync(path2.join(targetDir, "src/server"), { recursive: true });
485
- fs.mkdirSync(path2.join(targetDir, "src/client"), { recursive: true });
702
+ fs2.mkdirSync(path3.join(targetDir, "src/server"), { recursive: true });
703
+ fs2.mkdirSync(path3.join(targetDir, "src/client"), { recursive: true });
486
704
  let storage;
487
705
  if (opts?.storage !== void 0) {
488
706
  storage = opts.storage;
@@ -503,7 +721,7 @@ async function initCommand(dir, opts) {
503
721
  "@types/react": "^19.0.0",
504
722
  "@types/react-dom": "^19.0.0",
505
723
  "@vitejs/plugin-react": "^4.0.0",
506
- "clawnify": "^0.1.13",
724
+ "clawnify": "^0.1.15",
507
725
  "tailwindcss": "^4.0.0",
508
726
  "vite": "^6.0.0",
509
727
  "wrangler": "^4.0.0"
@@ -518,9 +736,11 @@ async function initCommand(dir, opts) {
518
736
  deploy: "clawnify deploy"
519
737
  },
520
738
  dependencies: {
739
+ "@hono/zod-openapi": "^0.19.0",
521
740
  hono: "^4.0.0",
522
741
  react: "^19.0.0",
523
- "react-dom": "^19.0.0"
742
+ "react-dom": "^19.0.0",
743
+ zod: "^3.0.0"
524
744
  },
525
745
  devDependencies: devDeps,
526
746
  engines: { node: ">=22" },
@@ -625,14 +845,14 @@ export async function run(
625
845
  }
626
846
  `);
627
847
  if (storage) {
628
- write(targetDir, "src/server/index.ts", `import { Hono } from "hono";
848
+ write(targetDir, "src/server/index.ts", `import { OpenAPIHono } from "@hono/zod-openapi";
629
849
  import { initDB } from "./db";
630
850
  import { initUploads } from "./uploads";
631
851
  import api from "./routes";
632
852
 
633
853
  type Env = { Bindings: { DB: D1Database; UPLOADS: R2Bucket } };
634
854
 
635
- const app = new Hono<Env>();
855
+ const app = new OpenAPIHono<Env>();
636
856
 
637
857
  app.use("*", async (c, next) => {
638
858
  initDB(c.env.DB);
@@ -642,6 +862,11 @@ app.use("*", async (c, next) => {
642
862
 
643
863
  app.route("/", api);
644
864
 
865
+ app.doc("/api/openapi.json", {
866
+ openapi: "3.0.0",
867
+ info: { title: "${name}", version: "1.0.0" },
868
+ });
869
+
645
870
  export default app;
646
871
  `);
647
872
  write(targetDir, "src/server/uploads.ts", `let _bucket: R2Bucket;
@@ -686,13 +911,13 @@ export async function readUploadAsBase64DataUrl(
686
911
  }
687
912
  `);
688
913
  } else {
689
- write(targetDir, "src/server/index.ts", `import { Hono } from "hono";
914
+ write(targetDir, "src/server/index.ts", `import { OpenAPIHono } from "@hono/zod-openapi";
690
915
  import { initDB } from "./db";
691
916
  import api from "./routes";
692
917
 
693
918
  type Env = { Bindings: { DB: D1Database } };
694
919
 
695
- const app = new Hono<Env>();
920
+ const app = new OpenAPIHono<Env>();
696
921
 
697
922
  app.use("*", async (c, next) => {
698
923
  initDB(c.env.DB);
@@ -701,6 +926,11 @@ app.use("*", async (c, next) => {
701
926
 
702
927
  app.route("/", api);
703
928
 
929
+ app.doc("/api/openapi.json", {
930
+ openapi: "3.0.0",
931
+ info: { title: "${name}", version: "1.0.0" },
932
+ });
933
+
704
934
  export default app;
705
935
  `);
706
936
  }
@@ -723,10 +953,10 @@ createRoot(document.getElementById("app")!).render(
723
953
  writeBlankTemplate(targetDir, name);
724
954
  }
725
955
  console.log();
726
- console.log(` Created ${name} in ${path2.relative(process.cwd(), targetDir)}/`);
956
+ console.log(` Created ${name} in ${path3.relative(process.cwd(), targetDir)}/`);
727
957
  console.log();
728
958
  console.log(" Get started:");
729
- console.log(` cd ${path2.relative(process.cwd(), targetDir)}`);
959
+ console.log(` cd ${path3.relative(process.cwd(), targetDir)}`);
730
960
  console.log(" pnpm install");
731
961
  console.log(" pnpm dev # local dev at http://localhost:5173");
732
962
  console.log(" pnpm deploy # deploy to production");
@@ -739,15 +969,34 @@ function writeBlankTemplate(dir, name) {
739
969
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
740
970
  );
741
971
  `);
742
- write(dir, "src/server/routes.ts", `import { Hono } from "hono";
972
+ write(dir, "src/server/routes.ts", `import { OpenAPIHono, createRoute, z } from "@hono/zod-openapi";
743
973
  import { query } from "./db";
744
974
 
745
- const api = new Hono();
975
+ const api = new OpenAPIHono();
746
976
 
747
- api.get("/api/items", async (c) => {
748
- const items = await query("SELECT * FROM items ORDER BY created_at DESC");
749
- return c.json(items);
750
- });
977
+ const ItemSchema = z.object({
978
+ id: z.number(),
979
+ name: z.string(),
980
+ created_at: z.string(),
981
+ }).openapi("Item");
982
+
983
+ api.openapi(
984
+ createRoute({
985
+ method: "get",
986
+ path: "/api/items",
987
+ summary: "List items",
988
+ responses: {
989
+ 200: {
990
+ description: "List of items",
991
+ content: { "application/json": { schema: z.array(ItemSchema) } },
992
+ },
993
+ },
994
+ }),
995
+ async (c) => {
996
+ const items = await query("SELECT * FROM items ORDER BY created_at DESC");
997
+ return c.json(items);
998
+ },
999
+ );
751
1000
 
752
1001
  export default api;
753
1002
  `);
@@ -786,41 +1035,107 @@ function writeCrudTemplate(dir, name) {
786
1035
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
787
1036
  );
788
1037
  `);
789
- write(dir, "src/server/routes.ts", `import { Hono } from "hono";
1038
+ write(dir, "src/server/routes.ts", `import { OpenAPIHono, createRoute, z } from "@hono/zod-openapi";
790
1039
  import { query, run } from "./db";
791
1040
 
792
- const api = new Hono();
1041
+ const api = new OpenAPIHono();
793
1042
 
794
- api.get("/api/items", async (c) => {
795
- const items = await query("SELECT * FROM items ORDER BY created_at DESC");
796
- return c.json(items);
797
- });
1043
+ const ItemSchema = z.object({
1044
+ id: z.number(),
1045
+ title: z.string(),
1046
+ status: z.string(),
1047
+ created_at: z.string(),
1048
+ }).openapi("Item");
798
1049
 
799
- api.post("/api/items", async (c) => {
800
- const { title } = await c.req.json<{ title: string }>();
801
- if (!title?.trim()) return c.json({ error: "Title required" }, 400);
802
- const result = await run("INSERT INTO items (title) VALUES (?)", [title.trim()]);
803
- return c.json({ id: result.lastInsertRowid, title: title.trim(), status: "active" }, 201);
804
- });
1050
+ const CreateItemSchema = z.object({ title: z.string().min(1) }).openapi("CreateItem");
1051
+ const UpdateItemSchema = z.object({
1052
+ title: z.string().min(1).optional(),
1053
+ status: z.string().optional(),
1054
+ }).openapi("UpdateItem");
1055
+ const IdParamSchema = z.object({ id: z.string() });
1056
+ const OkSchema = z.object({ ok: z.boolean() }).openapi("Ok");
805
1057
 
806
- api.patch("/api/items/:id", async (c) => {
807
- const id = c.req.param("id");
808
- const body = await c.req.json<{ title?: string; status?: string }>();
809
- const sets: string[] = [];
810
- const params: unknown[] = [];
811
- if (body.title !== undefined) { sets.push("title = ?"); params.push(body.title); }
812
- if (body.status !== undefined) { sets.push("status = ?"); params.push(body.status); }
813
- if (sets.length === 0) return c.json({ error: "Nothing to update" }, 400);
814
- params.push(id);
815
- await run(\`UPDATE items SET \${sets.join(", ")} WHERE id = ?\`, params);
816
- return c.json({ ok: true });
817
- });
1058
+ api.openapi(
1059
+ createRoute({
1060
+ method: "get",
1061
+ path: "/api/items",
1062
+ summary: "List items",
1063
+ responses: {
1064
+ 200: {
1065
+ description: "List of items",
1066
+ content: { "application/json": { schema: z.array(ItemSchema) } },
1067
+ },
1068
+ },
1069
+ }),
1070
+ async (c) => {
1071
+ const items = await query("SELECT * FROM items ORDER BY created_at DESC");
1072
+ return c.json(items);
1073
+ },
1074
+ );
818
1075
 
819
- api.delete("/api/items/:id", async (c) => {
820
- const id = c.req.param("id");
821
- await run("DELETE FROM items WHERE id = ?", [id]);
822
- return c.json({ ok: true });
823
- });
1076
+ api.openapi(
1077
+ createRoute({
1078
+ method: "post",
1079
+ path: "/api/items",
1080
+ summary: "Create item",
1081
+ request: { body: { content: { "application/json": { schema: CreateItemSchema } } } },
1082
+ responses: {
1083
+ 201: {
1084
+ description: "Created item",
1085
+ content: { "application/json": { schema: ItemSchema } },
1086
+ },
1087
+ },
1088
+ }),
1089
+ async (c) => {
1090
+ const { title } = c.req.valid("json");
1091
+ const result = await run("INSERT INTO items (title) VALUES (?)", [title.trim()]);
1092
+ return c.json({ id: result.lastInsertRowid, title: title.trim(), status: "active", created_at: new Date().toISOString() }, 201);
1093
+ },
1094
+ );
1095
+
1096
+ api.openapi(
1097
+ createRoute({
1098
+ method: "patch",
1099
+ path: "/api/items/:id",
1100
+ summary: "Update item",
1101
+ request: {
1102
+ params: IdParamSchema,
1103
+ body: { content: { "application/json": { schema: UpdateItemSchema } } },
1104
+ },
1105
+ responses: {
1106
+ 200: { description: "Updated", content: { "application/json": { schema: OkSchema } } },
1107
+ },
1108
+ }),
1109
+ async (c) => {
1110
+ const { id } = c.req.valid("param");
1111
+ const body = c.req.valid("json");
1112
+ const sets: string[] = [];
1113
+ const params: unknown[] = [];
1114
+ if (body.title !== undefined) { sets.push("title = ?"); params.push(body.title); }
1115
+ if (body.status !== undefined) { sets.push("status = ?"); params.push(body.status); }
1116
+ if (sets.length === 0) return c.json({ ok: false }, 400);
1117
+ params.push(id);
1118
+ await run(\`UPDATE items SET \${sets.join(", ")} WHERE id = ?\`, params);
1119
+ return c.json({ ok: true });
1120
+ },
1121
+ );
1122
+
1123
+ api.openapi(
1124
+ createRoute({
1125
+ method: "delete",
1126
+ path: "/api/items/:id",
1127
+ summary: "Delete item",
1128
+ request: { params: IdParamSchema },
1129
+ responses: {
1130
+ 200: { description: "Deleted", content: { "application/json": { schema: OkSchema } } },
1131
+ },
1132
+ }),
1133
+ async (c) => {
1134
+ const { id } = c.req.valid("param");
1135
+ await run("DELETE FROM items WHERE id = ?", [id]);
1136
+ return c.json({ ok: true });
1137
+ },
1138
+ );
824
1139
 
825
1140
  export default api;
826
1141
  `);
@@ -920,14 +1235,14 @@ export function App() {
920
1235
  `);
921
1236
  }
922
1237
  function write(dir, file, content) {
923
- const fullPath = path2.join(dir, file);
924
- fs.mkdirSync(path2.dirname(fullPath), { recursive: true });
925
- fs.writeFileSync(fullPath, content);
1238
+ const fullPath = path3.join(dir, file);
1239
+ fs2.mkdirSync(path3.dirname(fullPath), { recursive: true });
1240
+ fs2.writeFileSync(fullPath, content);
926
1241
  }
927
1242
 
928
1243
  // src/commands/dev.ts
929
- import fs2 from "fs";
930
- import path3 from "path";
1244
+ import fs3 from "fs";
1245
+ import path4 from "path";
931
1246
  import { spawn } from "child_process";
932
1247
  function slugify2(name) {
933
1248
  return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 30);
@@ -972,7 +1287,7 @@ function assertNodeVersion2() {
972
1287
  }
973
1288
  async function devCommand(dir, options) {
974
1289
  assertNodeVersion2();
975
- const resolvedDir = dir ? path3.resolve(dir) : process.cwd();
1290
+ const resolvedDir = dir ? path4.resolve(dir) : process.cwd();
976
1291
  const manifest = readManifest(resolvedDir);
977
1292
  if (!manifest) {
978
1293
  console.error("No clawnify.json found. Run `clawnify init` first.");
@@ -982,12 +1297,12 @@ async function devCommand(dir, options) {
982
1297
  const database = manifest.app.database !== false;
983
1298
  const storage = manifest.app.storage === true;
984
1299
  const apiPort = options?.port || "8787";
985
- const clawnifyDir = path3.join(resolvedDir, ".clawnify");
986
- fs2.mkdirSync(clawnifyDir, { recursive: true });
987
- const wranglerPath = path3.join(clawnifyDir, "wrangler.toml");
988
- fs2.writeFileSync(wranglerPath, generateWranglerToml(slug, { database, storage }));
989
- const schemaPath = path3.join(resolvedDir, "src/server/schema.sql");
990
- if (database && fs2.existsSync(schemaPath)) {
1300
+ const clawnifyDir = path4.join(resolvedDir, ".clawnify");
1301
+ fs3.mkdirSync(clawnifyDir, { recursive: true });
1302
+ const wranglerPath = path4.join(clawnifyDir, "wrangler.toml");
1303
+ fs3.writeFileSync(wranglerPath, generateWranglerToml(slug, { database, storage }));
1304
+ const schemaPath = path4.join(resolvedDir, "src/server/schema.sql");
1305
+ if (database && fs3.existsSync(schemaPath)) {
991
1306
  await runQuiet(resolvedDir, "npx", [
992
1307
  "wrangler",
993
1308
  "d1",
@@ -1088,25 +1403,13 @@ function runQuiet(cwd, cmd, args) {
1088
1403
  }
1089
1404
 
1090
1405
  // src/commands/link.ts
1091
- import path4 from "path";
1092
- async function linkCommand(appId, options) {
1093
- const dir = options?.dir ? path4.resolve(options.dir) : process.cwd();
1094
- const orgs = await listMyOrgs();
1095
- if (orgs.length === 0) {
1096
- console.error("No organizations found. Run `clawnify login` first.");
1097
- process.exit(1);
1098
- }
1099
- const candidates = options?.org ? orgs.filter((o) => o.id === options.org || o.slug === options.org) : orgs;
1100
- if (candidates.length === 0) {
1101
- console.error(`No org matched "${options?.org}". Available: ${orgs.map((o) => o.slug).join(", ")}`);
1102
- process.exit(1);
1103
- }
1104
- let matched = null;
1105
- for (const org of candidates) {
1406
+ import path5 from "path";
1407
+ var UUID_RE2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1408
+ async function findByAppId(orgs, appId) {
1409
+ for (const org of orgs) {
1106
1410
  const res = await api.get(`/v1/apps/${appId}`, { orgId: org.id });
1107
1411
  if (res.ok) {
1108
- matched = { app: await res.json(), orgId: org.id, orgName: org.name };
1109
- break;
1412
+ return { app: await res.json(), org };
1110
1413
  }
1111
1414
  if (res.status !== 404) {
1112
1415
  const err = await res.json().catch(() => ({}));
@@ -1114,24 +1417,112 @@ async function linkCommand(appId, options) {
1114
1417
  process.exit(1);
1115
1418
  }
1116
1419
  }
1420
+ return null;
1421
+ }
1422
+ async function findBySlug(orgs, slug) {
1423
+ for (const org of orgs) {
1424
+ const res = await api.get(`/v1/apps`, { orgId: org.id });
1425
+ if (!res.ok) {
1426
+ if (res.status === 404) continue;
1427
+ const err = await res.json().catch(() => ({}));
1428
+ console.error(`Link failed (${org.name}): ${err.error || res.statusText}`);
1429
+ process.exit(1);
1430
+ }
1431
+ const payload = await res.json();
1432
+ const apps = Array.isArray(payload) ? payload : payload.apps;
1433
+ const match = apps.find((a) => a.slug === slug);
1434
+ if (match) {
1435
+ const detailRes = await api.get(`/v1/apps/${match.id}`, { orgId: org.id });
1436
+ if (detailRes.ok) {
1437
+ return { app: await detailRes.json(), org };
1438
+ }
1439
+ return { app: match, org };
1440
+ }
1441
+ }
1442
+ return null;
1443
+ }
1444
+ async function linkCommand(appIdOrSlug, options) {
1445
+ const dir = options?.dir ? path5.resolve(options.dir) : process.cwd();
1446
+ const orgs = await listMyOrgs();
1447
+ if (orgs.length === 0) {
1448
+ console.error("No organizations found. Run `clawnify login` first.");
1449
+ process.exit(1);
1450
+ }
1451
+ const candidates = options?.org ? orgs.filter((o) => o.id === options.org || o.slug === options.org) : orgs;
1452
+ if (candidates.length === 0) {
1453
+ console.error(
1454
+ `No org matched "${options?.org}". Available: ${orgs.map((o) => o.slug).join(", ")}`
1455
+ );
1456
+ process.exit(1);
1457
+ }
1458
+ const isUuid = UUID_RE2.test(appIdOrSlug);
1459
+ const matched = isUuid ? await findByAppId(candidates, appIdOrSlug) : await findBySlug(candidates, appIdOrSlug);
1117
1460
  if (!matched) {
1461
+ const kind = isUuid ? "id" : "slug";
1118
1462
  console.error(
1119
- `App ${appId} not found in any org you belong to (${candidates.map((o) => o.slug).join(", ")}). Check the id in the dashboard.`
1463
+ `App with ${kind} '${appIdOrSlug}' not found in ${candidates.map((o) => o.slug).join(", ")}.`
1120
1464
  );
1121
1465
  process.exit(1);
1122
1466
  }
1123
1467
  saveProject(dir, {
1124
- org_id: matched.orgId,
1468
+ org_id: matched.org.id,
1125
1469
  app_id: matched.app.id,
1126
1470
  slug: matched.app.slug,
1127
1471
  app_token: matched.app.app_token
1128
1472
  });
1129
- const rel = path4.relative(process.cwd(), dir) || ".";
1130
- console.log(` Linked ${matched.app.name} (${matched.app.slug}) in ${matched.orgName}`);
1473
+ const rel = path5.relative(process.cwd(), dir) || ".";
1474
+ console.log(` Linked ${matched.app.name} (${matched.app.slug}) in ${matched.org.name}`);
1131
1475
  console.log(` Wrote ${rel}/.clawnify/project.json`);
1132
1476
  console.log(` Run \`clawnify deploy\` to push the current source to this app.`);
1133
1477
  }
1134
1478
 
1479
+ // src/commands/pull.ts
1480
+ import path6 from "path";
1481
+ async function pullSchemaCommand(options) {
1482
+ if (!options.from) {
1483
+ console.error("Usage: clawnify pull schema --from <app-id-or-slug>");
1484
+ process.exit(64);
1485
+ }
1486
+ const ref = await resolveApp(options.from, options.org);
1487
+ if (!ref) {
1488
+ console.error(`App '${options.from}' not found in your orgs.`);
1489
+ process.exit(1);
1490
+ }
1491
+ let schema;
1492
+ try {
1493
+ schema = await fetchSchema(ref);
1494
+ } catch (err) {
1495
+ console.error(`Failed to fetch schema: ${err.message}`);
1496
+ process.exit(1);
1497
+ }
1498
+ const targetPath = path6.resolve(options.out ?? "schema.sql");
1499
+ const result = await writeSchema(targetPath, schema, { force: options.force });
1500
+ const rel = path6.relative(process.cwd(), result.path) || result.path;
1501
+ switch (result.status) {
1502
+ case "no-schema":
1503
+ console.log(` ${ref.slug}: no schema.sql in R2 (pre-backfill app, or no database)`);
1504
+ process.exit(0);
1505
+ case "unchanged":
1506
+ console.log(` ${rel} is already up to date`);
1507
+ process.exit(0);
1508
+ case "written":
1509
+ console.log(` \u2713 wrote ${rel} (${result.bytes} bytes, from ${ref.slug})`);
1510
+ process.exit(0);
1511
+ case "refused-uncommitted":
1512
+ console.error(
1513
+ ` ${rel} has uncommitted changes \u2014 refusing to overwrite.
1514
+ Commit/stash first, or rerun with --force.`
1515
+ );
1516
+ process.exit(1);
1517
+ case "refused-different":
1518
+ console.error(
1519
+ ` ${rel} exists locally and differs from the deployed copy.
1520
+ Not inside a git repo \u2014 can't tell intent. Rerun with --force to overwrite.`
1521
+ );
1522
+ process.exit(1);
1523
+ }
1524
+ }
1525
+
1135
1526
  // src/commands/org.ts
1136
1527
  async function orgListCommand() {
1137
1528
  const orgs = await listMyOrgs();
@@ -1176,8 +1567,10 @@ function runCli() {
1176
1567
  program.command("init [dir]").description("Scaffold a new Clawnify app").option("--name <name>", "App name (skips prompt)").option("--template <template>", "Template: blank or crud (skips prompt)").option("--storage", "Enable file uploads (R2)").action(initCommand);
1177
1568
  program.command("dev [dir]").description("Start local dev server").option("--port <port>", "API server port (default: 8787)").action(devCommand);
1178
1569
  program.command("login").description("Authenticate with Clawnify").action(loginCommand);
1179
- program.command("deploy [dir]").description("Deploy an app to Clawnify").option("--from <repo>", "Deploy from a GitHub repo (owner/repo)").option("--name <name>", "Override app name").action(deployCommand);
1180
- program.command("link <app-id>").description("Link the current directory to an existing Clawnify app").option("--dir <dir>", "Directory to link (default: cwd)").option("--org <slug-or-id>", "Restrict the app lookup to a specific org").action(linkCommand);
1570
+ program.command("deploy [dir]").description("Deploy an app to Clawnify").option("--from <repo>", "Deploy from a GitHub repo (owner/repo)").option("--name <name>", "Override app name").option("--org <slug-or-id>", "Deploy to a specific org (overrides active org)").option("-y, --yes", "Non-interactive: on slug conflict, update existing app").option("--update-existing", "Non-interactive: on slug conflict, overwrite existing app").option("--create-new", "Non-interactive: on slug conflict, create a new app with the suggested slug").option("--dry-run", "List files that would be uploaded; do not deploy").option("--no-sync", "Skip the post-deploy schema.sql sync into the local working directory").action(deployCommand);
1571
+ program.command("link <app-id-or-slug>").description("Link the current directory to an existing Clawnify app (accepts id or slug)").option("--dir <dir>", "Directory to link (default: cwd)").option("--org <slug-or-id>", "Restrict the app lookup to a specific org").action(linkCommand);
1572
+ const pull = program.command("pull").description("Pull artifacts from a deployed app into the current directory");
1573
+ pull.command("schema").description("Fetch the deployed app's current schema.sql snapshot into the local repo").option("--from <app-id-or-slug>", "App to fetch from (required)").option("--out <path>", "Where to write (default: ./schema.sql)").option("--force", "Overwrite a locally-modified or uncommitted schema.sql").option("--org <slug-or-id>", "Restrict the app lookup to a specific org").action(pullSchemaCommand);
1181
1574
  const org = program.command("org").description("Manage organizations");
1182
1575
  org.command("list").description("List orgs you belong to").action(orgListCommand);
1183
1576
  org.command("use <slug-or-id>").description("Set the active org for global commands (ls, whoami, etc.)").action(orgUseCommand);
@@ -1191,4 +1584,4 @@ function runCli() {
1191
1584
  export {
1192
1585
  runCli
1193
1586
  };
1194
- //# sourceMappingURL=cli-VQJAJZQV.js.map
1587
+ //# sourceMappingURL=cli-I45E7PD2.js.map