flypod 0.9.0 → 0.10.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.
@@ -1,17 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ DeployError,
3
4
  atomicWriteFile,
4
5
  clearSession,
5
6
  collectDist,
6
7
  createClient,
7
8
  deploySite,
8
9
  installSkill,
10
+ packDeploy,
9
11
  projectsFilePath,
10
12
  resolveCredentials,
11
13
  resolveDeployDir,
12
- saveSession,
13
- zipSync
14
- } from "../cli-db9gcrd0.js";
14
+ saveSession
15
+ } from "../cli-198a0gkx.js";
15
16
 
16
17
  // bin/deploy.ts
17
18
  import { readFile as readFile2 } from "node:fs/promises";
@@ -19,6 +20,188 @@ import { homedir } from "node:os";
19
20
  import { relative } from "node:path";
20
21
  import { fileURLToPath } from "node:url";
21
22
 
23
+ // src/cli/errors.ts
24
+ var USAGE_CODES = new Set([
25
+ "usage",
26
+ "unknown_command",
27
+ "unknown_flag",
28
+ "interactive_login_required"
29
+ ]);
30
+ var AUTH_CODES = new Set([
31
+ "not_signed_in",
32
+ "unauthorized",
33
+ "token_rejected",
34
+ "no_token",
35
+ "login_denied"
36
+ ]);
37
+ var RETRY_CODES = new Set([
38
+ "rate_limited",
39
+ "server_error",
40
+ "network",
41
+ "authorization_pending",
42
+ "login_timeout"
43
+ ]);
44
+ function exitCodeFor(code) {
45
+ if (USAGE_CODES.has(code))
46
+ return 2;
47
+ if (AUTH_CODES.has(code))
48
+ return 3;
49
+ if (RETRY_CODES.has(code))
50
+ return 4;
51
+ return 1;
52
+ }
53
+ function errorEnvelope(err) {
54
+ return {
55
+ ok: false,
56
+ code: err.code,
57
+ error: err.error,
58
+ ...err.fix ? { fix: err.fix } : {},
59
+ ...err.status !== undefined ? { status: err.status } : {},
60
+ ...err.extra ?? {}
61
+ };
62
+ }
63
+ function emitError(err, args, io, opts = {}) {
64
+ if (args.json) {
65
+ io.out(JSON.stringify(errorEnvelope(err)));
66
+ } else {
67
+ const prefix = opts.prefix ? `${opts.prefix}: ` : "";
68
+ io.err(`${prefix}${err.error}`);
69
+ if (err.fix)
70
+ io.err(` ${err.fix}`);
71
+ }
72
+ return exitCodeFor(err.code);
73
+ }
74
+ function fail(code, error, args, io, opts = {}) {
75
+ return emitError({ code, error, fix: opts.fix, status: opts.status, extra: opts.extra }, args, io, { prefix: opts.prefix });
76
+ }
77
+ async function readServerMessage(res) {
78
+ const text = await res.text().catch(() => "");
79
+ if (!text)
80
+ return { message: `HTTP ${res.status}` };
81
+ try {
82
+ const body = JSON.parse(text);
83
+ const message = typeof body.error === "string" ? body.error : typeof body.message === "string" ? body.message : text;
84
+ return { message, code: typeof body.code === "string" ? body.code : undefined };
85
+ } catch {
86
+ return { message: text.length > 200 ? `${text.slice(0, 200)}…` : text };
87
+ }
88
+ }
89
+ async function classifyResponse(res, ctx) {
90
+ const { message, code: serverCode } = await readServerMessage(res);
91
+ const status = res.status;
92
+ const site = ctx.siteId ? ` ${ctx.siteId}` : "";
93
+ const base = { status, error: message };
94
+ if (serverCode === "token_rejected") {
95
+ return {
96
+ ...base,
97
+ code: "token_rejected",
98
+ error: "The credential you sent was not accepted, so nothing was deployed.",
99
+ fix: "Run `flypod login` again, or set a valid FLYPOD_TOKEN (unset it to deploy anonymously)."
100
+ };
101
+ }
102
+ if (serverCode === "challenge_required" || /challenge required/i.test(message)) {
103
+ return {
104
+ ...base,
105
+ code: "challenge_required",
106
+ error: "The server wants a human challenge for this deploy.",
107
+ fix: "Run `flypod login` and deploy again: signed-in deploys skip the challenge."
108
+ };
109
+ }
110
+ switch (status) {
111
+ case 401:
112
+ case 403:
113
+ if (/blocked/i.test(message)) {
114
+ return {
115
+ ...base,
116
+ code: "blocked",
117
+ error: `Deploy refused: ${message}`,
118
+ fix: "The content tripped the abuse guard. Remove the flagged files and try again."
119
+ };
120
+ }
121
+ return {
122
+ ...base,
123
+ code: "unauthorized",
124
+ error: `Not authorized for site${site}.`,
125
+ fix: "Run `flypod login`, or pass --token <manage_token> for a site this machine does not remember."
126
+ };
127
+ case 404:
128
+ return ctx.siteScoped ? {
129
+ ...base,
130
+ code: "site_gone",
131
+ error: `Site${site} is gone (expired or deleted).`,
132
+ fix: "Run `flypod` to create a new site."
133
+ } : { ...base, code: "not_found", error: message };
134
+ case 409:
135
+ return {
136
+ ...base,
137
+ code: "already_claimed",
138
+ error: `Site${site} already belongs to another account.`
139
+ };
140
+ case 400:
141
+ return { ...base, code: "invalid_upload", error: `Rejected: ${message}` };
142
+ case 413:
143
+ return {
144
+ ...base,
145
+ code: "too_large",
146
+ error: `Upload too large: ${message}`,
147
+ fix: "Shrink the build (fewer files, smaller assets) or split it. See flypod.dev/limits."
148
+ };
149
+ case 429:
150
+ return {
151
+ ...base,
152
+ code: "rate_limited",
153
+ error: "Too many requests from this network right now.",
154
+ fix: "Wait a minute and retry the same command.",
155
+ extra: retryAfter(res)
156
+ };
157
+ default:
158
+ if (status >= 500) {
159
+ return {
160
+ ...base,
161
+ code: "server_error",
162
+ error: `${ctx.verb}: the server returned ${status}.`,
163
+ fix: "Retry in a moment; if it keeps failing, check https://flypod.dev/status."
164
+ };
165
+ }
166
+ return { ...base, code: "bad_request", error: `${ctx.verb}: ${message}` };
167
+ }
168
+ }
169
+ function retryAfter(res) {
170
+ const raw = res.headers.get("retry-after");
171
+ const seconds = raw ? Number(raw) : Number.NaN;
172
+ return Number.isFinite(seconds) ? { retry_after_s: seconds } : {};
173
+ }
174
+ function networkError(e, baseUrl) {
175
+ const reason = e instanceof Error ? e.message : String(e);
176
+ const host = baseUrl ? ` ${safeHost(baseUrl)}` : "";
177
+ return {
178
+ code: "network",
179
+ error: `Could not reach the flypod server${host}: ${reason}`,
180
+ fix: "Check your connection (and DEPLOY_URL, if set), then retry."
181
+ };
182
+ }
183
+ function safeHost(url) {
184
+ try {
185
+ return new URL(url).host;
186
+ } catch {
187
+ return url;
188
+ }
189
+ }
190
+ var NO_SITE = {
191
+ code: "no_site",
192
+ error: "No flypod site is linked to this folder.",
193
+ fix: "Run `flypod` here to create one, or pass --site <id>."
194
+ };
195
+ var NOT_SIGNED_IN = {
196
+ code: "not_signed_in",
197
+ error: "Not signed in.",
198
+ fix: "Run `flypod login`, or set FLYPOD_TOKEN."
199
+ };
200
+ function unexpectedError(e) {
201
+ const reason = e instanceof Error ? e.message : String(e);
202
+ return { code: "unexpected", error: `unexpected error: ${reason}` };
203
+ }
204
+
22
205
  // src/cli/projects.ts
23
206
  import { readFile } from "node:fs/promises";
24
207
  var MAX_PROJECTS = 64;
@@ -185,16 +368,21 @@ function relinkNotice(prev, style) {
185
368
  function agentNext(opts) {
186
369
  const now = opts.now ?? Date.now();
187
370
  const expiring = opts.expiresAt !== null;
371
+ const linked = opts.linkSaved !== false;
372
+ const target = linked ? "" : ` --site ${opts.siteId}`;
373
+ const update = `flypod update${target}`;
374
+ const linkNote = linked ? `This folder is linked to ${opts.siteId}.` : `The folder → site link could not be saved, so every command needs --site ${opts.siteId}.`;
375
+ const expiryNote = expiring ? "The site stops serving on the date above unless `flypod login` claims it, which removes the expiry and changes nothing else." : "This site does not expire.";
188
376
  return {
189
377
  expires_in_days: expiring ? daysUntil(opts.expiresAt, now) : null,
190
378
  expires_at_iso: expiring ? new Date(opts.expiresAt).toISOString() : null,
191
379
  next: {
192
- update: "flypod update",
193
- versions: "flypod versions",
194
- rollback: "flypod rollback",
380
+ update,
381
+ versions: `flypod versions${target}`,
382
+ rollback: `flypod rollback${target}`,
195
383
  ...expiring ? { keep: "flypod login" } : {}
196
384
  },
197
- next_note: expiring ? `This folder is linked to ${opts.siteId}. Run \`flypod update\` to publish changes to this same URL — running \`flypod\` again creates a different site at a different URL. The site stops serving on the date above unless \`flypod login\` claims it, which removes the expiry and changes nothing else.` : `This folder is linked to ${opts.siteId}. Run \`flypod update\` to publish changes to this same URL — running \`flypod\` again creates a different site at a different URL. This site does not expire.`
385
+ next_note: `${linkNote} Run \`${update}\` to publish changes to this same URL — running \`flypod\` again creates a different site at a different URL. ${expiryNote}`
198
386
  };
199
387
  }
200
388
 
@@ -254,6 +442,7 @@ Drop this folder's remembered site link.
254
442
 
255
443
  Flags:
256
444
  --site <id> Forget all links to this site.
445
+ --json Emit JSON on stdout.
257
446
  -h, --help Show this help.`,
258
447
  token: `flypod token [flags]
259
448
 
@@ -274,24 +463,33 @@ The token goes to stdout, so it pipes:
274
463
 
275
464
  Flags:
276
465
  --site <id> Reveal the token for this site id instead of this folder.
466
+ --json Emit {"ok":true,"site_id":…,"manage_token":…} on stdout.
277
467
  -h, --help Show this help.`,
278
468
  login: `flypod login [flags]
279
469
 
280
470
  Authenticate with flypod via the browser (device authorization).
281
471
 
282
- flypod login Start the device sign-in (open a browser).
472
+ flypod login Start the device sign-in: prints a URL and a
473
+ code, then waits for the browser confirmation.
283
474
  flypod login --token <t> Save a session token directly (for agents/CI).
475
+ flypod login --json Agents: print the URL, code, and device_code as
476
+ JSON and exit at once instead of waiting.
477
+ flypod login --device-code <c>
478
+ Finish a --json login once the user confirmed.
284
479
 
285
480
  Flags:
286
- --token <t> Save this session token instead of opening a browser.
287
- -h, --help Show this help.`,
288
- logout: `flypod logout
481
+ --token <t> Save this session token instead of opening a browser.
482
+ --device-code <c> Poll once for the approval of a sign-in started with --json.
483
+ --json Emit JSON on stdout; never blocks waiting for a browser.
484
+ -h, --help Show this help.`,
485
+ logout: `flypod logout [--json]
289
486
 
290
487
  Forget the saved session token. Doesn't affect the server.`,
291
- list: `flypod list
488
+ list: `flypod list [--json]
292
489
 
293
- List sites you own (requires login or FLYPOD_TOKEN). Outputs JSON on stdout.`,
294
- claim: `flypod claim <site_id> <claim_token>
490
+ List sites you own (requires login or FLYPOD_TOKEN). Outputs JSON on stdout —
491
+ {"ok":true,"sites":[]} when there are none yet.`,
492
+ claim: `flypod claim <site_id> <claim_token> [--json]
295
493
 
296
494
  Attach an anonymous deploy to your account (requires login or FLYPOD_TOKEN). Outputs JSON on stdout.`
297
495
  };
@@ -302,18 +500,33 @@ function showSubHelp(name, io) {
302
500
  else
303
501
  io.err(`No help available for "${name}". Run \`flypod --help\` for usage.`);
304
502
  }
305
- function failJson(error, io) {
306
- io.out(JSON.stringify({ ok: false, error }));
307
- return 1;
308
- }
309
- function fail(msg, args, io, opts = {}) {
503
+ var POLL_MAX_ATTEMPTS = 120;
504
+ async function pollDeviceToken(client, deviceCode) {
505
+ const res = await client.deviceToken(deviceCode);
506
+ if (res.ok) {
507
+ const { access_token } = await res.json();
508
+ return { state: "approved", access_token };
509
+ }
510
+ const body = await res.json().catch(() => ({}));
511
+ if (body.error === "authorization_pending")
512
+ return { state: "pending" };
513
+ if (body.error === "slow_down")
514
+ return { state: "slow_down" };
515
+ if (body.error === "access_denied")
516
+ return { state: "denied" };
517
+ if (body.error === "expired_token")
518
+ return { state: "expired" };
519
+ return { state: "error", res };
520
+ }
521
+ async function finishLogin(accessToken, baseUrl, args, io, env) {
522
+ await saveSession({ session_token: accessToken, base_url: baseUrl, created_at: Date.now() }, env);
523
+ const attached = await attachAnonymousSites(accessToken, baseUrl, args, io, env);
310
524
  if (args.json)
311
- return failJson(msg, io);
312
- if (!opts.silent)
313
- io.err(msg);
314
- return 1;
525
+ io.out(JSON.stringify({ ok: true, logged_in: true, ...attached }));
526
+ else
527
+ io.err("Logged in.");
528
+ return 0;
315
529
  }
316
- var POLL_MAX_ATTEMPTS = 120;
317
530
  async function login(args, io) {
318
531
  if (args.help) {
319
532
  showSubHelp("login", io);
@@ -322,19 +535,45 @@ async function login(args, io) {
322
535
  const env = io.env ?? process.env;
323
536
  const baseUrl = resolveCredentials(env, null).baseUrl;
324
537
  if (args.token) {
325
- await saveSession({ session_token: args.token, base_url: baseUrl, created_at: Date.now() }, env);
326
- io.err("Logged in.");
327
- await attachAnonymousSites(args.token, baseUrl, io, env);
328
- return 0;
538
+ return finishLogin(args.token, baseUrl, args, io, env);
329
539
  }
330
540
  const client = await createClient({ env, fetch: io.fetch, overrides: { baseUrl } });
331
- const startRes = await client.deviceCode();
541
+ if (args.deviceCode) {
542
+ let poll;
543
+ try {
544
+ poll = await pollDeviceToken(client, args.deviceCode);
545
+ } catch (e) {
546
+ return emitError(networkError(e, baseUrl), args, io, { prefix: "flypod login" });
547
+ }
548
+ return poll.state === "approved" ? finishLogin(poll.access_token, baseUrl, args, io, env) : emitError(loginPollError(poll, args.deviceCode), args, io, { prefix: "flypod login" });
549
+ }
550
+ let startRes;
551
+ try {
552
+ startRes = await client.deviceCode();
553
+ } catch (e) {
554
+ return emitError(networkError(e, baseUrl), args, io, { prefix: "flypod login" });
555
+ }
332
556
  if (!startRes.ok) {
333
- io.err(`flypod login: server returned ${startRes.status}. Is the server running?`);
334
- return 1;
557
+ const err = await classifyResponse(startRes, { verb: "flypod login" });
558
+ return emitError({ ...err, fix: err.fix ?? "Is the server running? Check DEPLOY_URL." }, args, io, { prefix: "flypod login" });
335
559
  }
336
560
  const start = await startRes.json();
337
561
  const openUrl = start.verification_uri_complete ?? `${start.verification_uri}?user_code=${encodeURIComponent(start.user_code)}`;
562
+ if (args.json) {
563
+ return emitError({
564
+ code: "interactive_login_required",
565
+ error: "Sign-in needs a browser. Ask the user to open the URL and confirm the code.",
566
+ fix: `Open ${openUrl} (code ${start.user_code}); then run \`flypod login --device-code ${start.device_code}\` to finish.`,
567
+ extra: {
568
+ verification_uri: start.verification_uri,
569
+ verification_uri_complete: openUrl,
570
+ user_code: start.user_code,
571
+ device_code: start.device_code,
572
+ ...start.expires_in !== undefined ? { expires_in: start.expires_in } : {},
573
+ ...start.interval !== undefined ? { interval: start.interval } : {}
574
+ }
575
+ }, args, io);
576
+ }
338
577
  io.err("");
339
578
  io.err(` Open this URL in your browser to sign in:`);
340
579
  io.err(` ${openUrl}`);
@@ -344,55 +583,85 @@ async function login(args, io) {
344
583
  let pollMs = (start.interval ?? 5) * 1000;
345
584
  for (let attempt = 0;attempt < POLL_MAX_ATTEMPTS; attempt++) {
346
585
  await new Promise((r) => setTimeout(r, pollMs));
347
- const pollRes = await client.deviceToken(start.device_code);
348
- if (pollRes.ok) {
349
- const { access_token } = await pollRes.json();
350
- await saveSession({ session_token: access_token, base_url: baseUrl, created_at: Date.now() }, env);
351
- io.err("Logged in.");
352
- await attachAnonymousSites(access_token, baseUrl, io, env);
353
- return 0;
586
+ let poll;
587
+ try {
588
+ poll = await pollDeviceToken(client, start.device_code);
589
+ } catch (e) {
590
+ return emitError(networkError(e, baseUrl), args, io, { prefix: "flypod login" });
591
+ }
592
+ if (poll.state === "approved") {
593
+ return finishLogin(poll.access_token, baseUrl, args, io, env);
354
594
  }
355
- const body = await pollRes.json().catch(() => ({}));
356
- if (body.error === "authorization_pending")
595
+ if (poll.state === "pending")
357
596
  continue;
358
- if (body.error === "slow_down") {
597
+ if (poll.state === "slow_down") {
359
598
  pollMs += 5000;
360
599
  continue;
361
600
  }
362
- if (body.error === "access_denied") {
363
- io.err("Authorization denied in browser.");
364
- return 1;
365
- }
366
- if (body.error === "expired_token") {
367
- io.err("Code expired. Run `flypod login` to try again.");
368
- return 1;
369
- }
370
- io.err(`flypod login: unexpected error ${pollRes.status}.`);
371
- return 1;
601
+ return emitError(loginPollError(poll, start.device_code), args, io, {
602
+ prefix: "flypod login"
603
+ });
372
604
  }
373
- io.err("Timed out waiting for browser authorization. Run `flypod login` to try again.");
374
- return 1;
605
+ return fail("login_timeout", "Timed out waiting for browser authorization.", args, io, {
606
+ fix: "Run `flypod login` to try again."
607
+ });
375
608
  }
376
- async function attachAnonymousSites(apiKey, baseUrl, io, env) {
609
+ function loginPollError(poll, deviceCode) {
610
+ switch (poll.state) {
611
+ case "pending":
612
+ case "slow_down":
613
+ return {
614
+ code: "authorization_pending",
615
+ error: "The sign-in has not been confirmed in the browser yet.",
616
+ fix: `Wait for the user to confirm, then run \`flypod login --device-code ${deviceCode}\` again.`
617
+ };
618
+ case "denied":
619
+ return { code: "login_denied", error: "Authorization denied in browser." };
620
+ case "expired":
621
+ return {
622
+ code: "login_expired",
623
+ error: "The sign-in code expired.",
624
+ fix: "Run `flypod login` to start again."
625
+ };
626
+ case "error":
627
+ return {
628
+ code: poll.res.status >= 500 ? "server_error" : "bad_request",
629
+ error: `unexpected response ${poll.res.status} while polling for approval.`,
630
+ status: poll.res.status
631
+ };
632
+ }
633
+ }
634
+ async function attachAnonymousSites(apiKey, baseUrl, args, io, env) {
635
+ const none = { attached: [], skipped: [] };
377
636
  const projects = await loadProjects(env);
378
637
  const candidates = Object.entries(projects).filter(([, rec]) => rec.base_url === baseUrl && rec.expires_at !== null && typeof rec.manage_token === "string");
379
638
  if (candidates.length === 0)
380
- return;
639
+ return none;
640
+ const say = (line) => {
641
+ if (!args.json)
642
+ io.err(line);
643
+ };
381
644
  const noun = candidates.length === 1 ? "site" : "sites";
382
- io.err(`Found ${candidates.length} anonymous ${noun} on this machine.`);
383
- io.err(` Attaching to your account…`);
645
+ say(`Found ${candidates.length} anonymous ${noun} on this machine.`);
646
+ say(` Attaching to your account…`);
384
647
  const client = await createClient({
385
648
  env,
386
649
  fetch: io.fetch,
387
650
  overrides: { token: apiKey, baseUrl }
388
651
  });
389
- const res = await client.bulkAttach(candidates.map(([, rec]) => ({
390
- site_id: rec.site_id,
391
- manage_token: rec.manage_token
392
- })));
652
+ let res;
653
+ try {
654
+ res = await client.bulkAttach(candidates.map(([, rec]) => ({
655
+ site_id: rec.site_id,
656
+ manage_token: rec.manage_token
657
+ })));
658
+ } catch {
659
+ say(" Could not attach (network). Run `flypod login` again later.");
660
+ return none;
661
+ }
393
662
  if (!res.ok) {
394
- io.err(` Could not attach (${res.status}). Try again later.`);
395
- return;
663
+ say(` Could not attach (${res.status}). Try again later.`);
664
+ return none;
396
665
  }
397
666
  const body = await res.json().catch(() => ({}));
398
667
  const attached = new Set(body.attached ?? []);
@@ -408,57 +677,66 @@ async function attachAnonymousSites(apiKey, baseUrl, io, env) {
408
677
  }
409
678
  if (attached.size > 0) {
410
679
  const word = attached.size === 1 ? "site" : "sites";
411
- io.err(` Attached ${attached.size} ${word} — no expiry now, same URLs.`);
680
+ say(` Attached ${attached.size} ${word} — no expiry now, same URLs.`);
412
681
  }
413
682
  if (skipped.length > 0) {
414
- io.err(` Skipped ${skipped.length} (already owned or expired).`);
683
+ say(` Skipped ${skipped.length} (already owned or expired).`);
415
684
  }
685
+ return { attached: [...attached], skipped };
416
686
  }
417
- async function logout(_args, io) {
687
+ async function logout(args, io) {
418
688
  const env = io.env ?? process.env;
419
689
  const ok = await clearSession(env);
690
+ if (args.json) {
691
+ io.out(JSON.stringify({ ok: true, signed_out: ok }));
692
+ return 0;
693
+ }
420
694
  if (ok)
421
695
  io.err("Signed out. Local session forgotten.");
422
696
  else
423
697
  io.err("Already signed out.");
424
698
  return 0;
425
699
  }
426
- async function list(_args, io) {
700
+ async function list(args, io) {
427
701
  const env = io.env ?? process.env;
428
702
  const client = await createClient({ env, fetch: io.fetch });
429
- if (!client.token) {
430
- io.err("Not signed in. Run `flypod login` first or set FLYPOD_TOKEN.");
431
- return 1;
703
+ if (!client.token)
704
+ return emitError(NOT_SIGNED_IN, args, io, { prefix: "flypod list" });
705
+ let res;
706
+ try {
707
+ res = await client.listSites();
708
+ } catch (e) {
709
+ return emitError(networkError(e, client.baseUrl), args, io, { prefix: "flypod list" });
432
710
  }
433
- const res = await client.listSites();
434
711
  if (!res.ok) {
435
- io.err(`flypod list: server returned ${res.status}.`);
436
- return 1;
712
+ return emitError(await classifyResponse(res, { verb: "flypod list" }), args, io, {
713
+ prefix: "flypod list"
714
+ });
437
715
  }
438
716
  const body = await res.json();
439
717
  const sites = body.sites ?? [];
440
- if (sites.length === 0) {
718
+ io.out(JSON.stringify({ ok: true, sites }));
719
+ if (sites.length === 0 && !args.json) {
441
720
  io.err("No sites yet. Run `flypod` in a folder to deploy one.");
442
- return 0;
443
721
  }
444
- io.out(JSON.stringify({ ok: true, sites }));
445
722
  return 0;
446
723
  }
447
724
  async function claim(args, io) {
448
725
  const env = io.env ?? process.env;
449
726
  const client = await createClient({ env, fetch: io.fetch });
450
- if (!client.token) {
451
- io.err("Not signed in. Run `flypod login` first or set FLYPOD_TOKEN.");
452
- return 1;
453
- }
727
+ if (!client.token)
728
+ return emitError(NOT_SIGNED_IN, args, io, { prefix: "flypod claim" });
454
729
  if (!args.site_id || !args.token) {
455
- io.err("Usage: flypod claim <site_id> <claim_token>");
456
- return 2;
730
+ return fail("usage", "Usage: flypod claim <site_id> <claim_token>", args, io);
731
+ }
732
+ let res;
733
+ try {
734
+ res = await client.claimSite(args.site_id, args.token);
735
+ } catch (e) {
736
+ return emitError(networkError(e, client.baseUrl), args, io, { prefix: "flypod claim" });
457
737
  }
458
- const res = await client.claimSite(args.site_id, args.token);
459
738
  if (!res.ok) {
460
- io.err(res.status === 409 ? `flypod claim: ${args.site_id} already belongs to another account.` : `flypod claim: server returned ${res.status}.`);
461
- return 1;
739
+ return emitError(await classifyResponse(res, { verb: "flypod claim", siteId: args.site_id }), args, io, { prefix: "flypod claim" });
462
740
  }
463
741
  const body = await res.json();
464
742
  try {
@@ -483,7 +761,6 @@ async function claim(args, io) {
483
761
  io.err(`Claimed ${body.site_id} — the expiry is gone. Same URL, same versions.`);
484
762
  return 0;
485
763
  }
486
- var NO_SITE = "No flypod site is linked to this folder. Run 'flypod' here to create one, or pass --site <id>.";
487
764
  async function resolveTarget(args, io) {
488
765
  const env = io.env ?? process.env;
489
766
  if (args.site)
@@ -500,7 +777,7 @@ async function withTarget(name, args, io) {
500
777
  const env = io.env ?? process.env;
501
778
  const target = await resolveTarget(args, io);
502
779
  if (!target)
503
- return fail(NO_SITE, args, io);
780
+ return emitError(NO_SITE, args, io, { prefix: `flypod ${name}` });
504
781
  return { env, target };
505
782
  }
506
783
  function clientForTarget(target, args, io) {
@@ -515,29 +792,22 @@ function clientForTarget(target, args, io) {
515
792
  }
516
793
  });
517
794
  }
518
- async function healGone(target, io, env) {
519
- if (target.dir)
795
+ async function failSiteRequest(verb, res, target, args, io, env) {
796
+ if (res.status === 404 && target.dir)
520
797
  await forgetDir(target.dir, env);
521
- io.err(`Site ${target.site_id} is gone (expired or deleted). Run 'flypod' to create a new one.`);
798
+ const err = await classifyResponse(res, { verb, siteId: target.site_id, siteScoped: true });
799
+ return emitError(err, args, io, { prefix: verb });
522
800
  }
523
- function unauthorized(target, io) {
524
- io.err(`Unauthorized for ${target.site_id}. Run \`flypod login\` or pass --token <manage_token>.`);
525
- }
526
- async function fetchSite(target, args, io, env) {
801
+ async function fetchSite(verb, target, args, io, env) {
527
802
  const client = await clientForTarget(target, args, io);
528
- const res = await client.getSite(target.site_id);
529
- if (res.status === 401 || res.status === 403) {
530
- unauthorized(target, io);
531
- return { error: 1 };
532
- }
533
- if (res.status === 404) {
534
- await healGone(target, io, env);
535
- return { error: 1 };
536
- }
537
- if (!res.ok) {
538
- io.err(`flypod: server returned ${res.status}.`);
539
- return { error: 1 };
803
+ let res;
804
+ try {
805
+ res = await client.getSite(target.site_id);
806
+ } catch (e) {
807
+ return { error: emitError(networkError(e, client.baseUrl), args, io, { prefix: verb }) };
540
808
  }
809
+ if (!res.ok)
810
+ return { error: await failSiteRequest(verb, res, target, args, io, env) };
541
811
  return { data: await res.json() };
542
812
  }
543
813
  async function touchLink(target, version_id, env) {
@@ -555,31 +825,26 @@ async function update(args, io) {
555
825
  try {
556
826
  dir = await resolveDeployDir({ cwd, explicit: args.path });
557
827
  } catch (e) {
558
- return fail(e.message, args, io);
828
+ return fail("no_build_dir", e.message, args, io);
559
829
  }
560
830
  let files;
561
831
  try {
562
832
  files = await collectDist(dir);
563
833
  } catch (e) {
564
- return fail(`Could not read ${dir}: ${e.message}`, args, io);
834
+ return fail("no_files", `Could not read ${dir}: ${e.message}`, args, io);
565
835
  }
566
836
  const client = await clientForTarget(target, args, io);
567
- const res = await client.redeploy(target.site_id, zipSync(files));
568
- if (res.status === 401 || res.status === 403) {
569
- unauthorized(target, io);
570
- return 1;
571
- }
572
- if (res.status === 404) {
573
- await healGone(target, io, env);
574
- return 1;
575
- }
576
- if (!res.ok) {
577
- io.err(`flypod update: server returned ${res.status}.`);
578
- return 1;
837
+ let res;
838
+ try {
839
+ res = await client.redeploy(target.site_id, packDeploy(files));
840
+ } catch (e) {
841
+ return emitError(networkError(e, client.baseUrl), args, io, { prefix: "flypod update" });
579
842
  }
843
+ if (!res.ok)
844
+ return failSiteRequest("flypod update", res, target, args, io, env);
580
845
  const body = await res.json();
581
846
  await touchLink(target, body.version_id, env);
582
- const expiresAt = target.rec?.expires_at ?? null;
847
+ const expiresAt = body.expires_at !== undefined ? body.expires_at : target.rec?.expires_at ?? null;
583
848
  if (args.json) {
584
849
  io.out(JSON.stringify({
585
850
  ok: true,
@@ -617,7 +882,7 @@ async function versions(args, io) {
617
882
  if (typeof pre === "number")
618
883
  return pre;
619
884
  const { env, target } = pre;
620
- const site = await fetchSite(target, args, io, env);
885
+ const site = await fetchSite("flypod versions", target, args, io, env);
621
886
  if ("error" in site)
622
887
  return site.error;
623
888
  const { live_version_id, versions: vers } = site.data;
@@ -645,10 +910,11 @@ async function rollback(args, io) {
645
910
  if (typeof pre === "number")
646
911
  return pre;
647
912
  const { env, target } = pre;
648
- const site = await fetchSite(target, args, io, env);
913
+ const site = await fetchSite("flypod rollback", target, args, io, env);
649
914
  if ("error" in site)
650
915
  return site.error;
651
916
  const { live_version_id, versions: vers } = site.data;
917
+ const listThem = "Run `flypod versions` to see them.";
652
918
  let chosen;
653
919
  if (args.version) {
654
920
  const exact = vers.find((v) => v.version_id === args.version);
@@ -658,29 +924,33 @@ async function rollback(args, io) {
658
924
  else if (prefixed.length === 1)
659
925
  chosen = prefixed[0]?.version_id;
660
926
  else if (prefixed.length === 0) {
661
- return fail(`No version matches '${args.version}'.`, args, io);
927
+ return fail("no_such_version", `No version matches '${args.version}'.`, args, io, {
928
+ fix: listThem
929
+ });
662
930
  } else {
663
- return fail(`'${args.version}' is ambiguous — it matches ${prefixed.length} versions.`, args, io);
931
+ return fail("usage", `'${args.version}' is ambiguous — it matches ${prefixed.length} versions.`, args, io, { fix: `Pass a longer prefix. ${listThem}` });
664
932
  }
665
933
  } else {
666
934
  if (vers.length < 2) {
667
- return fail("Only one version exists — nothing to roll back to.", args, io);
935
+ return fail("no_such_version", "Only one version exists — nothing to roll back to.", args, io);
668
936
  }
669
937
  const liveIdx = vers.findIndex((v) => v.version_id === live_version_id);
670
938
  if (liveIdx <= 0) {
671
- return fail("Already at the oldest version.", args, io);
939
+ return fail("no_such_version", "Already at the oldest version.", args, io, {
940
+ fix: `Pass a version id to roll forward. ${listThem}`
941
+ });
672
942
  }
673
943
  chosen = vers[liveIdx - 1]?.version_id;
674
944
  }
675
945
  const client = await clientForTarget(target, args, io);
676
- const res = await client.rollback(target.site_id, chosen);
677
- if (res.status === 404) {
678
- await healGone(target, io, env);
679
- return fail(`Site ${target.site_id} not found.`, args, io, { silent: true });
680
- }
681
- if (!res.ok) {
682
- return fail(`flypod rollback: server returned ${res.status}.`, args, io);
946
+ let res;
947
+ try {
948
+ res = await client.rollback(target.site_id, chosen);
949
+ } catch (e) {
950
+ return emitError(networkError(e, client.baseUrl), args, io, { prefix: "flypod rollback" });
683
951
  }
952
+ if (!res.ok)
953
+ return failSiteRequest("flypod rollback", res, target, args, io, env);
684
954
  const body = await res.json();
685
955
  await touchLink(target, body.live_version_id, env);
686
956
  const url = target.rec?.url ?? siteUrlFrom(target.site_id, client.baseUrl);
@@ -711,12 +981,18 @@ async function token(args, io) {
711
981
  const env = io.env ?? process.env;
712
982
  const record = args.site ? Object.values(await loadProjects(env)).find((p) => p.site_id === args.site) : await projectForDir(io.cwd ?? process.cwd(), env);
713
983
  if (!record) {
714
- io.err(args.site ? `No remembered site ${args.site}. Tokens are only stored for sites deployed from this machine.` : "Nothing linked to this folder. Deploy first, or pass --site <id>.");
715
- return 1;
984
+ return args.site ? fail("no_site", `No remembered site ${args.site}.`, args, io, {
985
+ fix: "Tokens are only stored for sites deployed from this machine."
986
+ }) : emitError(NO_SITE, args, io, { prefix: "flypod token" });
716
987
  }
717
988
  if (!record.manage_token) {
718
- io.err(`Site ${record.site_id} has no stored manage token. If you claimed it, it authenticates with your account — run \`flypod login\`.`);
719
- return 1;
989
+ return fail("no_token", `Site ${record.site_id} has no stored manage token.`, args, io, {
990
+ fix: "If you claimed it, it authenticates with your account — run `flypod login`."
991
+ });
992
+ }
993
+ if (args.json) {
994
+ io.out(JSON.stringify({ ok: true, site_id: record.site_id, manage_token: record.manage_token }));
995
+ return 0;
720
996
  }
721
997
  io.err(`Manage token for ${record.site_id} — treat it like a password.
722
998
  `);
@@ -731,12 +1007,24 @@ async function forget(args, io) {
731
1007
  const env = io.env ?? process.env;
732
1008
  if (args.site) {
733
1009
  const n = await forgetSite(args.site, env);
734
- io.err(n ? `Forgot ${n} link${n === 1 ? "" : "s"} to ${args.site}.` : `No links to ${args.site}.`);
1010
+ if (args.json)
1011
+ io.out(JSON.stringify({ ok: true, site_id: args.site, forgotten: n }));
1012
+ else {
1013
+ io.err(n ? `Forgot ${n} link${n === 1 ? "" : "s"} to ${args.site}.` : `No links to ${args.site}.`);
1014
+ }
735
1015
  return 0;
736
1016
  }
737
1017
  const cwd = io.cwd ?? process.cwd();
738
1018
  const rec = await projectForDir(cwd, env);
739
1019
  const removed = await forgetDir(cwd, env);
1020
+ if (args.json) {
1021
+ io.out(JSON.stringify({
1022
+ ok: true,
1023
+ forgotten: removed && rec ? 1 : 0,
1024
+ ...removed && rec ? { site_id: rec.site_id } : {}
1025
+ }));
1026
+ return 0;
1027
+ }
740
1028
  io.err(removed && rec ? `Forgot ${rec.site_id} for this folder.` : "Nothing linked to this folder.");
741
1029
  return 0;
742
1030
  }
@@ -787,20 +1075,17 @@ function parseFlags(argv, spec) {
787
1075
  }
788
1076
 
789
1077
  // src/cli/comments.ts
790
- var NO_SITE2 = "No site given, and no flypod site is linked to this folder. " + "Pass --site <id>, or run this from a folder you have deployed from.";
791
1078
  async function resolveCommentsSite(explicit, io) {
792
1079
  if (explicit)
793
1080
  return explicit;
794
1081
  const rec = await projectForDir(io.cwd ?? process.cwd(), io.env ?? process.env);
795
1082
  return rec?.site_id;
796
1083
  }
797
- function failNoSite(json, io) {
798
- if (json) {
799
- io.out(JSON.stringify({ ok: false, error: "no_site" }));
800
- return 1;
801
- }
802
- io.err(NO_SITE2);
803
- return 2;
1084
+ function failNoSite(verb, json, io) {
1085
+ return fail("no_site", "No site given, and no flypod site is linked to this folder.", { json }, io, {
1086
+ prefix: `flypod comments ${verb}`,
1087
+ fix: "Pass --site <id>, or run this from a folder you have deployed from."
1088
+ });
804
1089
  }
805
1090
  async function resolveSiteAndThread(f, io) {
806
1091
  if (f.site)
@@ -813,101 +1098,105 @@ async function resolveSiteAndThread(f, io) {
813
1098
  thread_id: f.positionals[0]
814
1099
  };
815
1100
  }
816
- function requireCommentWriteToken(token2, io) {
817
- if (!token2) {
818
- io.err("Not signed in. Run `flypod login` or set FLYPOD_TOKEN.");
819
- return 3;
820
- }
1101
+ function requireCommentWriteToken(verb, token2, args, io) {
1102
+ const prefix = `flypod comments ${verb}`;
1103
+ if (!token2)
1104
+ return emitError(NOT_SIGNED_IN, args, io, { prefix });
821
1105
  if (token2.startsWith("fk_")) {
822
- io.err("comments operations require an account session or agent token");
823
- return 3;
1106
+ return fail("unauthorized", "Comments operations require an account session or agent token; a deploy key (fk_) only authorizes deploys.", args, io, { prefix, fix: "Run `flypod login`, or set FLYPOD_TOKEN to a session token." });
824
1107
  }
825
1108
  return null;
826
1109
  }
827
- async function readErrorBody(res) {
1110
+ async function send(verb, client, siteId, call, args, io) {
1111
+ const prefix = `flypod comments ${verb}`;
1112
+ let res;
828
1113
  try {
829
- const body = await res.json();
830
- if (body?.code)
831
- return body.code;
832
- if (body?.error)
833
- return body.error;
834
- } catch {}
835
- return `HTTP ${res.status}`;
1114
+ res = await call();
1115
+ } catch (e) {
1116
+ return { code: emitError(networkError(e, client.baseUrl), args, io, { prefix }) };
1117
+ }
1118
+ if (!res.ok) {
1119
+ const err = await classifyResponse(res, { verb: prefix, siteId });
1120
+ return { code: emitError(err, args, io, { prefix }) };
1121
+ }
1122
+ return { res };
1123
+ }
1124
+ var USAGE = {
1125
+ enable: `Usage: flypod comments enable [--site <id>] [--mode anonymous|passcode|approved] [--passcode <s>]
1126
+ ` + " --site defaults to the site linked to this folder.",
1127
+ mode: `Usage: flypod comments mode <anonymous|passcode|approved> [--site <id>] [--passcode <s>]
1128
+ ` + " --site defaults to the site linked to this folder.",
1129
+ off: "Usage: flypod comments off [--site <id>]",
1130
+ list: "Usage: flypod comments list [<site>] [--page <p>] [--open|--resolved|--all] [--limit N] [--json]",
1131
+ show: "Usage: flypod comments show [<site>] <thread_id>",
1132
+ post: "Usage: flypod comments post [<site>] --page <path> --target <json> --body <text>",
1133
+ resolve: `Usage: flypod comments resolve [<site>] <thread_id>
1134
+ ` + " The site defaults to the one linked to this folder.",
1135
+ reopen: `Usage: flypod comments reopen [<site>] <thread_id>
1136
+ ` + " The site defaults to the one linked to this folder."
1137
+ };
1138
+ function usage(verb, args, io) {
1139
+ return fail("usage", USAGE[verb] ?? `Usage: flypod comments ${verb}`, args, io);
836
1140
  }
837
1141
  async function commentsMode(args, io) {
838
- if (!args.mode) {
839
- io.err(`Usage: flypod comments mode <anonymous|passcode|approved> [--site <id>] [--passcode <s>]
840
- ` + " --site defaults to the site linked to this folder.");
841
- return 2;
842
- }
1142
+ if (!args.mode)
1143
+ return usage("mode", args, io);
843
1144
  const allowed = new Set(["anonymous", "passcode", "approved", "open", "review", "members"]);
844
1145
  if (!allowed.has(args.mode)) {
845
- io.err(`Unknown mode "${args.mode}". Expected anonymous|passcode|approved.`);
846
- return 2;
847
- }
848
- if (!args.site) {
849
- io.err("Missing --site <id>.");
850
- return 2;
1146
+ return fail("usage", `Unknown mode "${args.mode}". Expected anonymous|passcode|approved.`, args, io);
851
1147
  }
1148
+ if (!args.site)
1149
+ return usage("mode", args, io);
852
1150
  const env = io.env ?? process.env;
853
1151
  const client = await createClient({ env, fetch: io.fetch });
854
1152
  if (!client.token) {
855
- io.err("Not signed in. Run `flypod login` or set FLYPOD_TOKEN.");
856
- return 3;
1153
+ return emitError(NOT_SIGNED_IN, args, io, { prefix: "flypod comments mode" });
857
1154
  }
858
1155
  const body = { enabled: true, mode: args.mode };
859
1156
  if (args.passcode)
860
1157
  body.passcode = args.passcode;
861
- const res = await client.setCommentsMode(args.site, body);
862
- if (!res.ok) {
863
- io.err(`flypod comments mode: ${await readErrorBody(res)}`);
864
- return res.status >= 500 ? 4 : 1;
865
- }
1158
+ const site = args.site;
1159
+ const sent = await send("mode", client, site, () => client.setCommentsMode(site, body), args, io);
1160
+ if ("code" in sent)
1161
+ return sent.code;
866
1162
  if (args.json)
867
- io.out(JSON.stringify({ ok: true, site_id: args.site, mode: args.mode }));
1163
+ io.out(JSON.stringify({ ok: true, site_id: site, mode: args.mode }));
868
1164
  else
869
- io.err(`Comments mode set to ${args.mode} on ${args.site}.`);
1165
+ io.err(`Comments mode set to ${args.mode} on ${site}.`);
870
1166
  return 0;
871
1167
  }
872
1168
  async function commentsOff(args, io) {
873
- if (!args.site) {
874
- io.err("Missing --site <id>.");
875
- return 2;
876
- }
1169
+ if (!args.site)
1170
+ return usage("off", args, io);
877
1171
  const env = io.env ?? process.env;
878
1172
  const client = await createClient({ env, fetch: io.fetch });
879
1173
  if (!client.token) {
880
- io.err("Not signed in. Run `flypod login` or set FLYPOD_TOKEN.");
881
- return 3;
882
- }
883
- const res = await client.setCommentsMode(args.site, { enabled: false });
884
- if (!res.ok) {
885
- io.err(`flypod comments off: ${await readErrorBody(res)}`);
886
- return res.status >= 500 ? 4 : 1;
1174
+ return emitError(NOT_SIGNED_IN, args, io, { prefix: "flypod comments off" });
887
1175
  }
1176
+ const site = args.site;
1177
+ const sent = await send("off", client, site, () => client.setCommentsMode(site, { enabled: false }), args, io);
1178
+ if ("code" in sent)
1179
+ return sent.code;
888
1180
  if (args.json)
889
- io.out(JSON.stringify({ ok: true, site_id: args.site, enabled: false }));
1181
+ io.out(JSON.stringify({ ok: true, site_id: site, enabled: false }));
890
1182
  else
891
- io.err(`Comments disabled on ${args.site}.`);
1183
+ io.err(`Comments disabled on ${site}.`);
892
1184
  return 0;
893
1185
  }
894
1186
  async function commentsList(args, io) {
895
- if (!args.site) {
896
- io.err("Usage: flypod comments list <site> [--page <p>] [--open|--resolved|--all] [--limit N]");
897
- return 2;
898
- }
1187
+ if (!args.site)
1188
+ return usage("list", args, io);
899
1189
  const env = io.env ?? process.env;
900
1190
  const client = await createClient({ env, fetch: io.fetch });
901
- const res = await client.listComments(args.site, {
1191
+ const site = args.site;
1192
+ const sent = await send("list", client, site, () => client.listComments(site, {
902
1193
  page: args.page,
903
1194
  status: args.status,
904
1195
  limit: args.limit !== undefined ? String(args.limit) : undefined
905
- });
906
- if (!res.ok) {
907
- io.err(`flypod comments list: ${await readErrorBody(res)}`);
908
- return res.status >= 500 ? 4 : 1;
909
- }
910
- const body = await res.json();
1196
+ }), args, io);
1197
+ if ("code" in sent)
1198
+ return sent.code;
1199
+ const body = await sent.res.json();
911
1200
  const threads = Array.isArray(body.threads) ? body.threads : [];
912
1201
  if (args.json) {
913
1202
  for (const t of threads)
@@ -920,72 +1209,60 @@ async function commentsList(args, io) {
920
1209
  return 0;
921
1210
  }
922
1211
  async function commentsShow(args, io) {
923
- if (!args.site || !args.thread_id) {
924
- io.err("Usage: flypod comments show <site> <thread_id>");
925
- return 2;
926
- }
1212
+ if (!args.site || !args.thread_id)
1213
+ return usage("show", args, io);
927
1214
  const env = io.env ?? process.env;
928
1215
  const client = await createClient({ env, fetch: io.fetch });
929
- const res = await client.getThread(args.site, args.thread_id);
930
- if (!res.ok) {
931
- io.err(`flypod comments show: ${await readErrorBody(res)}`);
932
- return res.status >= 500 ? 4 : 1;
933
- }
934
- const body = await res.json();
1216
+ const { site, thread_id } = args;
1217
+ const sent = await send("show", client, site, () => client.getThread(site, thread_id), args, io);
1218
+ if ("code" in sent)
1219
+ return sent.code;
1220
+ const body = await sent.res.json();
935
1221
  io.out(JSON.stringify(body));
936
1222
  return 0;
937
1223
  }
938
1224
  async function commentsPost(args, io) {
939
- if (!args.site || !args.page || !args.target || !args.body) {
940
- io.err("Usage: flypod comments post <site> --page <path> --target <json> --body <text>");
941
- return 2;
942
- }
1225
+ if (!args.site || !args.page || !args.target || !args.body)
1226
+ return usage("post", args, io);
943
1227
  const env = io.env ?? process.env;
944
1228
  const client = await createClient({ env, fetch: io.fetch });
945
- const reject = requireCommentWriteToken(client.token, io);
1229
+ const reject = requireCommentWriteToken("post", client.token, args, io);
946
1230
  if (reject !== null)
947
1231
  return reject;
948
1232
  let target;
949
1233
  try {
950
1234
  target = JSON.parse(args.target);
951
1235
  } catch {
952
- io.err("Invalid --target JSON.");
953
- return 2;
954
- }
955
- const res = await client.postComment(args.site, {
956
- page_path: args.page,
957
- anchor: target,
958
- body: args.body
959
- });
960
- if (!res.ok) {
961
- io.err(`flypod comments post: ${await readErrorBody(res)}`);
962
- return res.status >= 500 ? 4 : res.status === 401 || res.status === 403 ? 3 : 1;
1236
+ return fail("usage", "Invalid --target JSON.", args, io, {
1237
+ fix: `Pass a W3C selector object, e.g. --target '{"source":"…","selector":[…]}'.`
1238
+ });
963
1239
  }
964
- const body = await res.json();
1240
+ const site = args.site;
1241
+ const payload = { page_path: args.page, anchor: target, body: args.body };
1242
+ const sent = await send("post", client, site, () => client.postComment(site, payload), args, io);
1243
+ if ("code" in sent)
1244
+ return sent.code;
1245
+ const body = await sent.res.json();
965
1246
  io.out(JSON.stringify(body));
966
1247
  return 0;
967
1248
  }
968
1249
  async function setThreadStatus(endpoint, args, io) {
969
- if (!args.site || !args.thread_id) {
970
- io.err(`Usage: flypod comments ${endpoint} [<site>] <thread_id>
971
- ` + " The site defaults to the one linked to this folder.");
972
- return 2;
973
- }
1250
+ if (!args.site || !args.thread_id)
1251
+ return usage(endpoint, args, io);
974
1252
  const env = io.env ?? process.env;
975
1253
  const client = await createClient({ env, fetch: io.fetch });
976
- const reject = requireCommentWriteToken(client.token, io);
1254
+ const reject = requireCommentWriteToken(endpoint, client.token, args, io);
977
1255
  if (reject !== null)
978
1256
  return reject;
979
- const res = await client.setThreadStatus(args.site, args.thread_id, endpoint);
980
- if (!res.ok) {
981
- io.err(`flypod comments ${endpoint}: ${await readErrorBody(res)}`);
982
- return res.status >= 500 ? 4 : res.status === 401 || res.status === 403 ? 3 : 1;
983
- }
984
- const body = await res.json().catch(() => ({}));
1257
+ const { site, thread_id } = args;
1258
+ const sent = await send(endpoint, client, site, () => client.setThreadStatus(site, thread_id, endpoint), args, io);
1259
+ if ("code" in sent)
1260
+ return sent.code;
1261
+ const body = await sent.res.json().catch(() => ({}));
985
1262
  if (args.json)
986
1263
  io.out(JSON.stringify({ ok: true, ...body }));
987
1264
  else
988
- io.err(`Thread ${args.thread_id} ${endpoint === "resolve" ? "resolved" : "reopened"}.`);
1265
+ io.err(`Thread ${thread_id} ${endpoint === "resolve" ? "resolved" : "reopened"}.`);
989
1266
  return 0;
990
1267
  }
991
1268
  function commentsResolve(args, io) {
@@ -995,11 +1272,8 @@ function commentsReopen(args, io) {
995
1272
  return setThreadStatus("reopen", args, io);
996
1273
  }
997
1274
  async function commentsEnable(args, io) {
998
- if (!args.site) {
999
- io.err(`Usage: flypod comments enable [--site <id>] [--mode anonymous|passcode|approved] [--passcode <s>]
1000
- ` + " --site defaults to the site linked to this folder.");
1001
- return 2;
1002
- }
1275
+ if (!args.site)
1276
+ return usage("enable", args, io);
1003
1277
  return commentsMode({ mode: args.mode ?? "anonymous", site: args.site, passcode: args.passcode, json: args.json }, io);
1004
1278
  }
1005
1279
  var COMMENTS_FLAG_SPEC = {
@@ -1015,14 +1289,17 @@ var COMMENTS_FLAG_SPEC = {
1015
1289
  "--open": "bool",
1016
1290
  "--resolved": "bool",
1017
1291
  "--all": "bool",
1018
- "--json": "bool"
1292
+ "--json": "bool",
1293
+ "-h": "bool",
1294
+ "--help": "bool"
1019
1295
  };
1020
1296
  function parseCommentFlags(tail) {
1021
- const { flags, positionals } = parseFlags(tail, COMMENTS_FLAG_SPEC);
1297
+ const { flags, positionals, unknown } = parseFlags(tail, COMMENTS_FLAG_SPEC);
1022
1298
  const limitRaw = flags["--limit"];
1023
1299
  const status = flags["--all"] ? "all" : flags["--resolved"] ? "resolved" : flags["--open"] ? "open" : undefined;
1024
1300
  return {
1025
1301
  positionals,
1302
+ unknown,
1026
1303
  site: flags["--site"],
1027
1304
  mode: flags["--mode"],
1028
1305
  page: flags["--page"],
@@ -1033,77 +1310,91 @@ function parseCommentFlags(tail) {
1033
1310
  passcode: flags["--passcode"],
1034
1311
  limit: limitRaw ? Number(limitRaw) : undefined,
1035
1312
  status,
1036
- json: Boolean(flags["--json"])
1313
+ json: Boolean(flags["--json"]),
1314
+ help: Boolean(flags["-h"] || flags["--help"])
1037
1315
  };
1038
1316
  }
1317
+ var VERBS = ["enable", "mode", "off", "list", "show", "post", "resolve", "reopen"];
1039
1318
  async function commentsCommand(argv, io) {
1319
+ const json = argv.includes("--json");
1040
1320
  if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
1041
- io.err("Usage: flypod comments <enable|mode|off|list|show|post|resolve|reopen> [args]");
1042
- return argv[0] === "-h" || argv[0] === "--help" ? 0 : 2;
1321
+ const line = `Usage: flypod comments <${VERBS.join("|")}> [args]`;
1322
+ if (argv[0] === "-h" || argv[0] === "--help") {
1323
+ io.err(line);
1324
+ return 0;
1325
+ }
1326
+ return fail("usage", line, { json }, io);
1043
1327
  }
1044
1328
  const verb = argv[0];
1045
1329
  const rest = argv.slice(1);
1330
+ if (!VERBS.includes(verb)) {
1331
+ return fail("unknown_command", `flypod comments: unknown verb "${verb}"`, { json }, io, {
1332
+ fix: `Expected one of: ${VERBS.join(", ")}.`
1333
+ });
1334
+ }
1335
+ const f = parseCommentFlags(rest);
1336
+ if (f.help) {
1337
+ io.err(USAGE[verb] ?? `Usage: flypod comments ${verb}`);
1338
+ return 0;
1339
+ }
1340
+ if (f.unknown.length > 0) {
1341
+ return fail("unknown_flag", `unknown flag "${f.unknown[0]}"`, f, io, {
1342
+ prefix: `flypod comments ${verb}`,
1343
+ fix: `Run \`flypod comments ${verb} --help\` for the flags this verb takes.`
1344
+ });
1345
+ }
1046
1346
  switch (verb) {
1047
1347
  case "enable": {
1048
- const f = parseCommentFlags(rest);
1049
1348
  const site = await resolveCommentsSite(f.site ?? f.positionals[0], io);
1050
1349
  if (!site)
1051
- return failNoSite(f.json, io);
1350
+ return failNoSite(verb, f.json, io);
1052
1351
  return commentsEnable({ site, mode: f.mode, passcode: f.passcode, json: f.json }, io);
1053
1352
  }
1054
1353
  case "mode": {
1055
- const f = parseCommentFlags(rest);
1056
1354
  const mode = f.positionals[0];
1057
1355
  const site = await resolveCommentsSite(f.site ?? f.positionals[1], io);
1058
1356
  if (!site)
1059
- return failNoSite(f.json, io);
1357
+ return failNoSite(verb, f.json, io);
1060
1358
  return commentsMode({ mode, site, passcode: f.passcode, json: f.json }, io);
1061
1359
  }
1062
1360
  case "off": {
1063
- const f = parseCommentFlags(rest);
1064
1361
  const site = await resolveCommentsSite(f.site ?? f.positionals[0], io);
1065
1362
  if (!site)
1066
- return failNoSite(f.json, io);
1363
+ return failNoSite(verb, f.json, io);
1067
1364
  return commentsOff({ site, json: f.json }, io);
1068
1365
  }
1069
1366
  case "list": {
1070
- const f = parseCommentFlags(rest);
1071
1367
  const site = await resolveCommentsSite(f.positionals[0] ?? f.site, io);
1072
1368
  if (!site)
1073
- return failNoSite(f.json, io);
1369
+ return failNoSite(verb, f.json, io);
1074
1370
  return commentsList({ site, page: f.page, status: f.status, limit: f.limit, json: f.json }, io);
1075
1371
  }
1076
1372
  case "show": {
1077
- const f = parseCommentFlags(rest);
1078
1373
  const { site, thread_id } = await resolveSiteAndThread(f, io);
1079
1374
  if (!site)
1080
- return failNoSite(f.json, io);
1375
+ return failNoSite(verb, f.json, io);
1081
1376
  return commentsShow({ site, thread_id, json: f.json }, io);
1082
1377
  }
1083
1378
  case "post": {
1084
- const f = parseCommentFlags(rest);
1085
1379
  const site = await resolveCommentsSite(f.positionals[0] ?? f.site, io);
1086
1380
  if (!site)
1087
- return failNoSite(f.json, io);
1381
+ return failNoSite(verb, f.json, io);
1088
1382
  return commentsPost({ site, page: f.page, target: f.target, body: f.body, json: f.json }, io);
1089
1383
  }
1090
1384
  case "resolve": {
1091
- const f = parseCommentFlags(rest);
1092
1385
  const { site, thread_id } = await resolveSiteAndThread(f, io);
1093
1386
  if (!site)
1094
- return failNoSite(f.json, io);
1387
+ return failNoSite(verb, f.json, io);
1095
1388
  return commentsResolve({ site, thread_id, json: f.json }, io);
1096
1389
  }
1097
1390
  case "reopen": {
1098
- const f = parseCommentFlags(rest);
1099
1391
  const { site, thread_id } = await resolveSiteAndThread(f, io);
1100
1392
  if (!site)
1101
- return failNoSite(f.json, io);
1393
+ return failNoSite(verb, f.json, io);
1102
1394
  return commentsReopen({ site, thread_id, json: f.json }, io);
1103
1395
  }
1104
1396
  default:
1105
- io.err(`flypod comments: unknown verb "${verb}"`);
1106
- return 2;
1397
+ return fail("unknown_command", `flypod comments: unknown verb "${verb}"`, f, io);
1107
1398
  }
1108
1399
  }
1109
1400
 
@@ -1354,14 +1645,26 @@ var TOP_LEVEL_FLAG_SPEC = {
1354
1645
  "--comments": "bool",
1355
1646
  "--mode": "value"
1356
1647
  };
1357
- function parseArgs(argv) {
1358
- const { flags, positionals, unknown } = parseFlags(argv, TOP_LEVEL_FLAG_SPEC);
1359
- if (unknown.length > 0) {
1360
- process.stderr.write(`flypod: unknown flag "${unknown[0]}"
1361
- Run \`flypod --help\` for usage.
1648
+ function rejectUnknownFlag(unknown, argv, helpCmd) {
1649
+ const err = {
1650
+ code: "unknown_flag",
1651
+ error: `unknown flag "${unknown}"`,
1652
+ fix: `Run \`${helpCmd}\` for usage.`
1653
+ };
1654
+ if (argv.includes("--json")) {
1655
+ process.stdout.write(`${JSON.stringify(errorEnvelope(err))}
1656
+ `);
1657
+ } else {
1658
+ process.stderr.write(`flypod: ${err.error}
1659
+ ${err.fix}
1362
1660
  `);
1363
- process.exit(2);
1364
1661
  }
1662
+ process.exit(exitCodeFor(err.code));
1663
+ }
1664
+ function parseArgs(argv) {
1665
+ const { flags, positionals, unknown } = parseFlags(argv, TOP_LEVEL_FLAG_SPEC);
1666
+ if (unknown[0])
1667
+ rejectUnknownFlag(unknown[0], argv, "flypod --help");
1365
1668
  return {
1366
1669
  path: positionals[0],
1367
1670
  json: Boolean(flags["--json"]),
@@ -1383,11 +1686,20 @@ var SUB_FLAG_SPEC = {
1383
1686
  };
1384
1687
  var LOGIN_FLAG_SPEC = {
1385
1688
  "--token": "value",
1689
+ "--device-code": "value",
1690
+ "--json": "bool",
1691
+ "-h": "bool",
1692
+ "--help": "bool"
1693
+ };
1694
+ var ACCOUNT_FLAG_SPEC = {
1695
+ "--json": "bool",
1386
1696
  "-h": "bool",
1387
1697
  "--help": "bool"
1388
1698
  };
1389
- function parseSub(argv) {
1390
- const { flags, positionals } = parseFlags(argv, SUB_FLAG_SPEC);
1699
+ function parseSub(name, argv) {
1700
+ const { flags, positionals, unknown } = parseFlags(argv, SUB_FLAG_SPEC);
1701
+ if (unknown[0])
1702
+ rejectUnknownFlag(unknown[0], argv, `flypod ${name} --help`);
1391
1703
  return {
1392
1704
  positionals,
1393
1705
  site: flags["--site"],
@@ -1407,39 +1719,53 @@ async function runSubcommand(name, argv) {
1407
1719
  };
1408
1720
  switch (name) {
1409
1721
  case "update": {
1410
- const { positionals, site, token: token2, json, quiet, help } = parseSub(argv);
1722
+ const { positionals, site, token: token2, json, quiet, help } = parseSub(name, argv);
1411
1723
  return update({ path: positionals[0], site, token: token2, json, quiet, help }, io);
1412
1724
  }
1413
1725
  case "versions": {
1414
- const { site, token: token2, json, help } = parseSub(argv);
1726
+ const { site, token: token2, json, help } = parseSub(name, argv);
1415
1727
  return versions({ site, token: token2, json, help }, io);
1416
1728
  }
1417
1729
  case "rollback": {
1418
- const { positionals, site, token: token2, json, help } = parseSub(argv);
1730
+ const { positionals, site, token: token2, json, help } = parseSub(name, argv);
1419
1731
  return rollback({ version: positionals[0], site, token: token2, json, help }, io);
1420
1732
  }
1421
1733
  case "forget": {
1422
- const { site, help } = parseSub(argv);
1423
- return forget({ site, help }, io);
1734
+ const { site, json, help } = parseSub(name, argv);
1735
+ return forget({ site, json, help }, io);
1424
1736
  }
1425
1737
  case "token": {
1426
- const { site, help } = parseSub(argv);
1427
- return token({ site, help }, io);
1738
+ const { site, json, help } = parseSub(name, argv);
1739
+ return token({ site, json, help }, io);
1428
1740
  }
1429
1741
  case "login": {
1430
- const { flags } = parseFlags(argv, LOGIN_FLAG_SPEC);
1742
+ const { flags, unknown } = parseFlags(argv, LOGIN_FLAG_SPEC);
1743
+ if (unknown[0])
1744
+ rejectUnknownFlag(unknown[0], argv, "flypod login --help");
1431
1745
  return login({
1432
1746
  token: flags["--token"],
1747
+ deviceCode: flags["--device-code"],
1748
+ json: Boolean(flags["--json"]),
1433
1749
  help: Boolean(flags["-h"] || flags["--help"])
1434
1750
  }, io);
1435
1751
  }
1436
- case "logout":
1437
- return logout({}, io);
1438
- case "list":
1439
- return list({}, io);
1752
+ case "logout": {
1753
+ const { flags, unknown } = parseFlags(argv, ACCOUNT_FLAG_SPEC);
1754
+ if (unknown[0])
1755
+ rejectUnknownFlag(unknown[0], argv, "flypod --help");
1756
+ return logout({ json: Boolean(flags["--json"]) }, io);
1757
+ }
1758
+ case "list": {
1759
+ const { flags, unknown } = parseFlags(argv, ACCOUNT_FLAG_SPEC);
1760
+ if (unknown[0])
1761
+ rejectUnknownFlag(unknown[0], argv, "flypod --help");
1762
+ return list({ json: Boolean(flags["--json"]) }, io);
1763
+ }
1440
1764
  case "claim": {
1441
- const { positionals } = parseFlags(argv, {});
1442
- return claim({ site_id: positionals[0], token: positionals[1] }, io);
1765
+ const { flags, positionals, unknown } = parseFlags(argv, ACCOUNT_FLAG_SPEC);
1766
+ if (unknown[0])
1767
+ rejectUnknownFlag(unknown[0], argv, "flypod --help");
1768
+ return claim({ site_id: positionals[0], token: positionals[1], json: Boolean(flags["--json"]) }, io);
1443
1769
  }
1444
1770
  case "install":
1445
1771
  return runInstall(argv, io);
@@ -1464,12 +1790,8 @@ async function runInstall(argv, io) {
1464
1790
  return 2;
1465
1791
  }
1466
1792
  const { flags, unknown } = parseFlags(argv, INSTALL_FLAG_SPEC);
1467
- const unknownFlag = unknown[0];
1468
- if (unknownFlag) {
1469
- io.err(`flypod: unknown flag "${unknownFlag}"`);
1470
- io.err("Run `flypod install skill --list` to see available targets and flags.");
1471
- return 2;
1472
- }
1793
+ if (unknown[0])
1794
+ rejectUnknownFlag(unknown[0], argv, "flypod install skill --list");
1473
1795
  const targets = [];
1474
1796
  for (const [flag, id] of Object.entries(TARGET_FLAGS)) {
1475
1797
  if (flags[flag] && !targets.includes(id))
@@ -1516,7 +1838,7 @@ async function readVersion() {
1516
1838
  return "0.0.0";
1517
1839
  }
1518
1840
  function showHelp(version) {
1519
- const usage = `flypod v${version}
1841
+ const usage2 = `flypod v${version}
1520
1842
  Drop files, get a live URL. Every deploy is versioned, so you can roll back.
1521
1843
 
1522
1844
  THE LOOP (this is all most agents need):
@@ -1629,26 +1951,25 @@ When no path is given, flypod looks for a build folder in the current directory:
1629
1951
 
1630
1952
  Docs: https://flypod.dev
1631
1953
  `;
1632
- process.stdout.write(usage);
1954
+ process.stdout.write(usage2);
1633
1955
  }
1634
1956
  function shortDir(dir) {
1635
1957
  const rel = relative(process.cwd(), dir);
1636
1958
  return rel === "" || rel.startsWith("..") ? dir : rel || ".";
1637
1959
  }
1638
- function fail2(msg, args, style, opts = {}) {
1960
+ function fail2(err, args, style, opts = {}) {
1639
1961
  if (args.json) {
1640
- process.stdout.write(`${JSON.stringify({ ok: false, error: msg })}
1641
- `);
1642
- } else if (opts.dimOnly) {
1643
- process.stderr.write(` ${style.dim(msg)}
1644
-
1962
+ process.stdout.write(`${JSON.stringify(errorEnvelope(err))}
1645
1963
  `);
1646
1964
  } else {
1647
- process.stderr.write(` ${style.err("✗")} ${msg}
1648
-
1965
+ const head = opts.dimOnly ? style.dim(err.error) : `${style.err("✗")} ${err.error}`;
1966
+ const fix = err.fix ? ` ${style.dim(err.fix)}
1967
+ ` : "";
1968
+ process.stderr.write(` ${head}
1969
+ ${fix}
1649
1970
  `);
1650
1971
  }
1651
- process.exit(1);
1972
+ process.exit(exitCodeFor(err.code));
1652
1973
  }
1653
1974
  async function main() {
1654
1975
  const rawArgv = process.argv.slice(2);
@@ -1696,18 +2017,26 @@ async function main() {
1696
2017
  try {
1697
2018
  dir = await resolveDeployDir({ explicit: args.path });
1698
2019
  } catch (error) {
1699
- fail2(error.message, args, style);
2020
+ fail2({ code: "no_build_dir", error: error.message }, args, style);
1700
2021
  }
1701
2022
  let files;
1702
2023
  try {
1703
2024
  files = await collectDist(dir);
1704
2025
  } catch (error) {
1705
- fail2(`Could not read ${shortDir(dir)}: ${error.message}`, args, style);
2026
+ fail2({
2027
+ code: "no_files",
2028
+ error: `Could not read ${shortDir(dir)}: ${error.message}`,
2029
+ fix: "Pass the folder of built files, e.g. `flypod ./dist`."
2030
+ }, args, style);
1706
2031
  }
1707
2032
  const fileNames = Object.keys(files);
1708
2033
  const totalBytes = fileNames.reduce((sum, name) => sum + (files[name]?.byteLength ?? 0), 0);
1709
2034
  if (fileNames.length === 0) {
1710
- fail2(`No files found in ${shortDir(dir)}.`, args, style);
2035
+ fail2({
2036
+ code: "no_files",
2037
+ error: `No files found in ${shortDir(dir)}.`,
2038
+ fix: "Build the site first, then deploy the output folder."
2039
+ }, args, style);
1711
2040
  }
1712
2041
  if (useUI) {
1713
2042
  process.stderr.write(` ${style.muted("source")} ${style.bold(shortDir(dir))} ${style.dim(`${fmtCount(fileNames.length, "file")} · ${fmtBytes(totalBytes)}`)}
@@ -1721,7 +2050,8 @@ async function main() {
1721
2050
  result = await deploySite({ baseUrl, files, apiKey, source: client.source });
1722
2051
  } catch (error) {
1723
2052
  spinner.fail("Deploy failed.");
1724
- fail2(error.message, args, style, { dimOnly: true });
2053
+ const err = error instanceof DeployError ? await classifyResponse(error.toResponse(), { verb: "flypod" }) : networkError(error, baseUrl);
2054
+ fail2(err, args, style, { dimOnly: true });
1725
2055
  }
1726
2056
  const elapsed = Date.now() - started;
1727
2057
  spinner.success(`Deployed in ${fmtSeconds(elapsed)}`);
@@ -1781,10 +2111,12 @@ async function main() {
1781
2111
  elapsed_ms: elapsed,
1782
2112
  healed: result.healed ?? [],
1783
2113
  warnings: result.warnings ?? [],
2114
+ link_saved: linkSaved,
1784
2115
  ...agentNext({
1785
2116
  siteId: result.site_id,
1786
2117
  expiresAt: result.expires_at,
1787
- owned
2118
+ owned,
2119
+ linkSaved
1788
2120
  }),
1789
2121
  ...priorLink && priorLink.site_id !== result.site_id ? { replaced_link: { site_id: priorLink.site_id, url: priorLink.url } } : {},
1790
2122
  ...args.comments ? { comments_enabled: commentsEnabled, comments_mode: args.commentsMode } : {}
@@ -1831,10 +2163,15 @@ async function main() {
1831
2163
  `);
1832
2164
  }
1833
2165
  main().catch((error) => {
1834
- process.stderr.write(`
1835
- flypod: unexpected error
1836
- ${error.message}
2166
+ const err = unexpectedError(error);
2167
+ if (process.argv.includes("--json")) {
2168
+ process.stdout.write(`${JSON.stringify(errorEnvelope(err))}
2169
+ `);
2170
+ } else {
2171
+ process.stderr.write(`
2172
+ flypod: ${err.error}
1837
2173
 
1838
2174
  `);
1839
- process.exit(1);
2175
+ }
2176
+ process.exit(exitCodeFor(err.code));
1840
2177
  });