flypod 0.8.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-g2wb2hxm.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;
@@ -94,6 +277,115 @@ async function forgetSite(site_id, env) {
94
277
  return removed;
95
278
  }
96
279
 
280
+ // src/cli/receipt.ts
281
+ var DAY_MS = 86400000;
282
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g");
283
+ var LABEL = 15;
284
+ var COMMAND = 18;
285
+ function daysUntil(expiresAt, now) {
286
+ return Math.max(0, Math.round((expiresAt - now) / DAY_MS));
287
+ }
288
+ var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
289
+ function expiryDate(expiresAt) {
290
+ const d = new Date(expiresAt);
291
+ return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}`;
292
+ }
293
+ function timestamp(ms) {
294
+ const d = new Date(ms);
295
+ const hh = String(d.getUTCHours()).padStart(2, "0");
296
+ const mm = String(d.getUTCMinutes()).padStart(2, "0");
297
+ return `${expiryDate(ms)} ${hh}:${mm} UTC`;
298
+ }
299
+ var LOOP = [
300
+ { label: "ship a change", command: "flypod update", effect: "new version, same URL" },
301
+ { label: "undo", command: "flypod rollback", effect: "previous version, instantly" },
302
+ { label: "history", command: "flypod versions", effect: "every version, newest first" }
303
+ ];
304
+ var PLAIN = {
305
+ dim: (s) => s,
306
+ bold: (s) => s,
307
+ muted: (s) => s,
308
+ accent: (s) => s,
309
+ ok: (s) => s
310
+ };
311
+ function gutter(label) {
312
+ return label.padEnd(LABEL, " ");
313
+ }
314
+ function row(label, command, effect, s) {
315
+ return ` ${s.muted(gutter(label))}${s.bold(command.padEnd(COMMAND, " "))}${s.dim(effect)}`;
316
+ }
317
+ function wrap(effect, s) {
318
+ return ` ${" ".repeat(LABEL + COMMAND)}${s.dim(effect)}`;
319
+ }
320
+ function note(label, text, s) {
321
+ return ` ${s.muted(gutter(label))}${s.dim(text)}`;
322
+ }
323
+ function expiryLines(opts) {
324
+ if (opts.expiresAt === null)
325
+ return [];
326
+ const s = opts.style ?? PLAIN;
327
+ const days = daysUntil(opts.expiresAt, opts.now ?? Date.now());
328
+ const when = `${expiryDate(opts.expiresAt)} · ${days} day${days === 1 ? "" : "s"}`;
329
+ return [
330
+ opts.check === false ? note("expires", when, s) : ` ${s.muted(gutter("expires"))}${s.dim(`${when} · `)}${s.bold("flypod versions")}`,
331
+ row("keep it", "flypod login", "drops the expiry from this URL", s),
332
+ wrap("and every site on this machine", s)
333
+ ];
334
+ }
335
+ function deployTail(opts) {
336
+ const style = opts.style ?? PLAIN;
337
+ const lines = LOOP.map((step) => row(step.label, step.command, step.effect, style));
338
+ lines.push("");
339
+ if (opts.expiresAt === null) {
340
+ lines.push(note("expires", opts.owned ? "never · attributed to your account" : "never", style));
341
+ return lines;
342
+ }
343
+ lines.push(...expiryLines({ expiresAt: opts.expiresAt, now: opts.now, style }));
344
+ return lines;
345
+ }
346
+ function updateTail(opts) {
347
+ const s = opts.style ?? PLAIN;
348
+ return [
349
+ ` ${s.ok("✓")} ${s.dim(`version ${opts.versionId} is now live`)}`,
350
+ ` ${s.accent(opts.url)}`,
351
+ ...(opts.warnings ?? []).map((w) => ` ! ${w.code} — ${w.fix_recipe}`),
352
+ row("undo", "flypod rollback", "previous version, instantly", s),
353
+ ...expiryLines({ expiresAt: opts.expiresAt, now: opts.now, style: s })
354
+ ];
355
+ }
356
+ function rollbackTail(opts) {
357
+ const s = opts.style ?? PLAIN;
358
+ return [` ${s.ok("✓")} ${s.dim(`rolled back to ${opts.versionId}`)}`, ` ${s.accent(opts.url)}`];
359
+ }
360
+ function relinkNotice(prev, style) {
361
+ const s = style ?? PLAIN;
362
+ return [
363
+ ` ${s.muted(gutter("linked"))}${s.bold("flypod update")}${s.dim(" ships to")}`,
364
+ ` ${s.muted(gutter(""))}${s.accent(prev.url)}`,
365
+ note("", "this run makes a second site instead", s)
366
+ ];
367
+ }
368
+ function agentNext(opts) {
369
+ const now = opts.now ?? Date.now();
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.";
376
+ return {
377
+ expires_in_days: expiring ? daysUntil(opts.expiresAt, now) : null,
378
+ expires_at_iso: expiring ? new Date(opts.expiresAt).toISOString() : null,
379
+ next: {
380
+ update,
381
+ versions: `flypod versions${target}`,
382
+ rollback: `flypod rollback${target}`,
383
+ ...expiring ? { keep: "flypod login" } : {}
384
+ },
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}`
386
+ };
387
+ }
388
+
97
389
  // src/cli/commands.ts
98
390
  function siteUrlFrom(site_id, baseUrl) {
99
391
  const host = new URL(baseUrl).host;
@@ -150,6 +442,7 @@ Drop this folder's remembered site link.
150
442
 
151
443
  Flags:
152
444
  --site <id> Forget all links to this site.
445
+ --json Emit JSON on stdout.
153
446
  -h, --help Show this help.`,
154
447
  token: `flypod token [flags]
155
448
 
@@ -170,24 +463,33 @@ The token goes to stdout, so it pipes:
170
463
 
171
464
  Flags:
172
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.
173
467
  -h, --help Show this help.`,
174
468
  login: `flypod login [flags]
175
469
 
176
470
  Authenticate with flypod via the browser (device authorization).
177
471
 
178
- 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.
179
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.
180
479
 
181
480
  Flags:
182
- --token <t> Save this session token instead of opening a browser.
183
- -h, --help Show this help.`,
184
- 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]
185
486
 
186
487
  Forget the saved session token. Doesn't affect the server.`,
187
- list: `flypod list
488
+ list: `flypod list [--json]
188
489
 
189
- List sites you own (requires login or FLYPOD_TOKEN). Outputs JSON on stdout.`,
190
- 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]
191
493
 
192
494
  Attach an anonymous deploy to your account (requires login or FLYPOD_TOKEN). Outputs JSON on stdout.`
193
495
  };
@@ -198,18 +500,33 @@ function showSubHelp(name, io) {
198
500
  else
199
501
  io.err(`No help available for "${name}". Run \`flypod --help\` for usage.`);
200
502
  }
201
- function failJson(error, io) {
202
- io.out(JSON.stringify({ ok: false, error }));
203
- return 1;
204
- }
205
- 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);
206
524
  if (args.json)
207
- return failJson(msg, io);
208
- if (!opts.silent)
209
- io.err(msg);
210
- return 1;
525
+ io.out(JSON.stringify({ ok: true, logged_in: true, ...attached }));
526
+ else
527
+ io.err("Logged in.");
528
+ return 0;
211
529
  }
212
- var POLL_MAX_ATTEMPTS = 120;
213
530
  async function login(args, io) {
214
531
  if (args.help) {
215
532
  showSubHelp("login", io);
@@ -218,19 +535,45 @@ async function login(args, io) {
218
535
  const env = io.env ?? process.env;
219
536
  const baseUrl = resolveCredentials(env, null).baseUrl;
220
537
  if (args.token) {
221
- await saveSession({ session_token: args.token, base_url: baseUrl, created_at: Date.now() }, env);
222
- io.err("Logged in.");
223
- await attachAnonymousSites(args.token, baseUrl, io, env);
224
- return 0;
538
+ return finishLogin(args.token, baseUrl, args, io, env);
225
539
  }
226
540
  const client = await createClient({ env, fetch: io.fetch, overrides: { baseUrl } });
227
- 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
+ }
228
556
  if (!startRes.ok) {
229
- io.err(`flypod login: server returned ${startRes.status}. Is the server running?`);
230
- 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" });
231
559
  }
232
560
  const start = await startRes.json();
233
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
+ }
234
577
  io.err("");
235
578
  io.err(` Open this URL in your browser to sign in:`);
236
579
  io.err(` ${openUrl}`);
@@ -240,55 +583,85 @@ async function login(args, io) {
240
583
  let pollMs = (start.interval ?? 5) * 1000;
241
584
  for (let attempt = 0;attempt < POLL_MAX_ATTEMPTS; attempt++) {
242
585
  await new Promise((r) => setTimeout(r, pollMs));
243
- const pollRes = await client.deviceToken(start.device_code);
244
- if (pollRes.ok) {
245
- const { access_token } = await pollRes.json();
246
- await saveSession({ session_token: access_token, base_url: baseUrl, created_at: Date.now() }, env);
247
- io.err("Logged in.");
248
- await attachAnonymousSites(access_token, baseUrl, io, env);
249
- 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);
250
594
  }
251
- const body = await pollRes.json().catch(() => ({}));
252
- if (body.error === "authorization_pending")
595
+ if (poll.state === "pending")
253
596
  continue;
254
- if (body.error === "slow_down") {
597
+ if (poll.state === "slow_down") {
255
598
  pollMs += 5000;
256
599
  continue;
257
600
  }
258
- if (body.error === "access_denied") {
259
- io.err("Authorization denied in browser.");
260
- return 1;
261
- }
262
- if (body.error === "expired_token") {
263
- io.err("Code expired. Run `flypod login` to try again.");
264
- return 1;
265
- }
266
- io.err(`flypod login: unexpected error ${pollRes.status}.`);
267
- return 1;
601
+ return emitError(loginPollError(poll, start.device_code), args, io, {
602
+ prefix: "flypod login"
603
+ });
268
604
  }
269
- io.err("Timed out waiting for browser authorization. Run `flypod login` to try again.");
270
- return 1;
605
+ return fail("login_timeout", "Timed out waiting for browser authorization.", args, io, {
606
+ fix: "Run `flypod login` to try again."
607
+ });
271
608
  }
272
- 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: [] };
273
636
  const projects = await loadProjects(env);
274
637
  const candidates = Object.entries(projects).filter(([, rec]) => rec.base_url === baseUrl && rec.expires_at !== null && typeof rec.manage_token === "string");
275
638
  if (candidates.length === 0)
276
- return;
639
+ return none;
640
+ const say = (line) => {
641
+ if (!args.json)
642
+ io.err(line);
643
+ };
277
644
  const noun = candidates.length === 1 ? "site" : "sites";
278
- io.err(`Found ${candidates.length} anonymous ${noun} on this machine.`);
279
- io.err(` Attaching to your account…`);
645
+ say(`Found ${candidates.length} anonymous ${noun} on this machine.`);
646
+ say(` Attaching to your account…`);
280
647
  const client = await createClient({
281
648
  env,
282
649
  fetch: io.fetch,
283
650
  overrides: { token: apiKey, baseUrl }
284
651
  });
285
- const res = await client.bulkAttach(candidates.map(([, rec]) => ({
286
- site_id: rec.site_id,
287
- manage_token: rec.manage_token
288
- })));
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
+ }
289
662
  if (!res.ok) {
290
- io.err(` Could not attach (${res.status}). Try again later.`);
291
- return;
663
+ say(` Could not attach (${res.status}). Try again later.`);
664
+ return none;
292
665
  }
293
666
  const body = await res.json().catch(() => ({}));
294
667
  const attached = new Set(body.attached ?? []);
@@ -304,57 +677,66 @@ async function attachAnonymousSites(apiKey, baseUrl, io, env) {
304
677
  }
305
678
  if (attached.size > 0) {
306
679
  const word = attached.size === 1 ? "site" : "sites";
307
- io.err(` Attached ${attached.size} ${word}.`);
680
+ say(` Attached ${attached.size} ${word} — no expiry now, same URLs.`);
308
681
  }
309
682
  if (skipped.length > 0) {
310
- io.err(` Skipped ${skipped.length} (already owned or expired).`);
683
+ say(` Skipped ${skipped.length} (already owned or expired).`);
311
684
  }
685
+ return { attached: [...attached], skipped };
312
686
  }
313
- async function logout(_args, io) {
687
+ async function logout(args, io) {
314
688
  const env = io.env ?? process.env;
315
689
  const ok = await clearSession(env);
690
+ if (args.json) {
691
+ io.out(JSON.stringify({ ok: true, signed_out: ok }));
692
+ return 0;
693
+ }
316
694
  if (ok)
317
695
  io.err("Signed out. Local session forgotten.");
318
696
  else
319
697
  io.err("Already signed out.");
320
698
  return 0;
321
699
  }
322
- async function list(_args, io) {
700
+ async function list(args, io) {
323
701
  const env = io.env ?? process.env;
324
702
  const client = await createClient({ env, fetch: io.fetch });
325
- if (!client.token) {
326
- io.err("Not signed in. Run `flypod login` first or set FLYPOD_TOKEN.");
327
- 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" });
328
710
  }
329
- const res = await client.listSites();
330
711
  if (!res.ok) {
331
- io.err(`flypod list: server returned ${res.status}.`);
332
- return 1;
712
+ return emitError(await classifyResponse(res, { verb: "flypod list" }), args, io, {
713
+ prefix: "flypod list"
714
+ });
333
715
  }
334
716
  const body = await res.json();
335
717
  const sites = body.sites ?? [];
336
- if (sites.length === 0) {
718
+ io.out(JSON.stringify({ ok: true, sites }));
719
+ if (sites.length === 0 && !args.json) {
337
720
  io.err("No sites yet. Run `flypod` in a folder to deploy one.");
338
- return 0;
339
721
  }
340
- io.out(JSON.stringify({ ok: true, sites }));
341
722
  return 0;
342
723
  }
343
724
  async function claim(args, io) {
344
725
  const env = io.env ?? process.env;
345
726
  const client = await createClient({ env, fetch: io.fetch });
346
- if (!client.token) {
347
- io.err("Not signed in. Run `flypod login` first or set FLYPOD_TOKEN.");
348
- return 1;
349
- }
727
+ if (!client.token)
728
+ return emitError(NOT_SIGNED_IN, args, io, { prefix: "flypod claim" });
350
729
  if (!args.site_id || !args.token) {
351
- io.err("Usage: flypod claim <site_id> <claim_token>");
352
- 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" });
353
737
  }
354
- const res = await client.claimSite(args.site_id, args.token);
355
738
  if (!res.ok) {
356
- io.err(res.status === 409 ? `flypod claim: ${args.site_id} already belongs to another account.` : `flypod claim: server returned ${res.status}.`);
357
- return 1;
739
+ return emitError(await classifyResponse(res, { verb: "flypod claim", siteId: args.site_id }), args, io, { prefix: "flypod claim" });
358
740
  }
359
741
  const body = await res.json();
360
742
  try {
@@ -370,11 +752,15 @@ async function claim(args, io) {
370
752
  if (changed)
371
753
  await saveProjects(projects, env);
372
754
  } catch {}
373
- io.out(JSON.stringify({ ok: true, site_id: body.site_id, owner_account_id: body.owner_account_id }));
374
- io.err(`Claimed. Owned by ${body.owner_account_id}.`);
755
+ io.out(JSON.stringify({
756
+ ok: true,
757
+ site_id: body.site_id,
758
+ owner_account_id: body.owner_account_id,
759
+ expires_at: null
760
+ }));
761
+ io.err(`Claimed ${body.site_id} — the expiry is gone. Same URL, same versions.`);
375
762
  return 0;
376
763
  }
377
- var NO_SITE = "No flypod site is linked to this folder. Run 'flypod' here to create one, or pass --site <id>.";
378
764
  async function resolveTarget(args, io) {
379
765
  const env = io.env ?? process.env;
380
766
  if (args.site)
@@ -391,7 +777,7 @@ async function withTarget(name, args, io) {
391
777
  const env = io.env ?? process.env;
392
778
  const target = await resolveTarget(args, io);
393
779
  if (!target)
394
- return fail(NO_SITE, args, io);
780
+ return emitError(NO_SITE, args, io, { prefix: `flypod ${name}` });
395
781
  return { env, target };
396
782
  }
397
783
  function clientForTarget(target, args, io) {
@@ -406,29 +792,22 @@ function clientForTarget(target, args, io) {
406
792
  }
407
793
  });
408
794
  }
409
- async function healGone(target, io, env) {
410
- if (target.dir)
795
+ async function failSiteRequest(verb, res, target, args, io, env) {
796
+ if (res.status === 404 && target.dir)
411
797
  await forgetDir(target.dir, env);
412
- io.err(`Site ${target.site_id} is gone (expired or deleted). Run 'flypod' to create a new one.`);
413
- }
414
- function unauthorized(target, io) {
415
- io.err(`Unauthorized for ${target.site_id}. Run \`flypod login\` or pass --token <manage_token>.`);
798
+ const err = await classifyResponse(res, { verb, siteId: target.site_id, siteScoped: true });
799
+ return emitError(err, args, io, { prefix: verb });
416
800
  }
417
- async function fetchSite(target, args, io, env) {
801
+ async function fetchSite(verb, target, args, io, env) {
418
802
  const client = await clientForTarget(target, args, io);
419
- const res = await client.getSite(target.site_id);
420
- if (res.status === 401 || res.status === 403) {
421
- unauthorized(target, io);
422
- return { error: 1 };
423
- }
424
- if (res.status === 404) {
425
- await healGone(target, io, env);
426
- return { error: 1 };
427
- }
428
- if (!res.ok) {
429
- io.err(`flypod: server returned ${res.status}.`);
430
- 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 }) };
431
808
  }
809
+ if (!res.ok)
810
+ return { error: await failSiteRequest(verb, res, target, args, io, env) };
432
811
  return { data: await res.json() };
433
812
  }
434
813
  async function touchLink(target, version_id, env) {
@@ -446,36 +825,39 @@ async function update(args, io) {
446
825
  try {
447
826
  dir = await resolveDeployDir({ cwd, explicit: args.path });
448
827
  } catch (e) {
449
- return fail(e.message, args, io);
828
+ return fail("no_build_dir", e.message, args, io);
450
829
  }
451
830
  let files;
452
831
  try {
453
832
  files = await collectDist(dir);
454
833
  } catch (e) {
455
- return fail(`Could not read ${dir}: ${e.message}`, args, io);
834
+ return fail("no_files", `Could not read ${dir}: ${e.message}`, args, io);
456
835
  }
457
836
  const client = await clientForTarget(target, args, io);
458
- const res = await client.redeploy(target.site_id, zipSync(files));
459
- if (res.status === 401 || res.status === 403) {
460
- unauthorized(target, io);
461
- return 1;
462
- }
463
- if (res.status === 404) {
464
- await healGone(target, io, env);
465
- return 1;
466
- }
467
- if (!res.ok) {
468
- io.err(`flypod update: server returned ${res.status}.`);
469
- 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" });
470
842
  }
843
+ if (!res.ok)
844
+ return failSiteRequest("flypod update", res, target, args, io, env);
471
845
  const body = await res.json();
472
846
  await touchLink(target, body.version_id, env);
847
+ const expiresAt = body.expires_at !== undefined ? body.expires_at : target.rec?.expires_at ?? null;
473
848
  if (args.json) {
474
849
  io.out(JSON.stringify({
475
850
  ok: true,
476
851
  site_id: target.site_id,
477
852
  version_id: body.version_id,
478
- url: body.url
853
+ url: body.url,
854
+ healed: body.healed ?? [],
855
+ warnings: body.warnings ?? [],
856
+ ...agentNext({
857
+ siteId: target.site_id,
858
+ expiresAt,
859
+ owned: expiresAt === null
860
+ })
479
861
  }));
480
862
  return 0;
481
863
  }
@@ -483,7 +865,15 @@ async function update(args, io) {
483
865
  io.out(body.url);
484
866
  return 0;
485
867
  }
486
- io.err(`→ version ${body.version_id} is now live`);
868
+ for (const line of updateTail({
869
+ versionId: body.version_id,
870
+ url: body.url,
871
+ expiresAt,
872
+ warnings: body.warnings,
873
+ style: io.style
874
+ })) {
875
+ io.err(line);
876
+ }
487
877
  io.out(body.url);
488
878
  return 0;
489
879
  }
@@ -492,17 +882,27 @@ async function versions(args, io) {
492
882
  if (typeof pre === "number")
493
883
  return pre;
494
884
  const { env, target } = pre;
495
- const site = await fetchSite(target, args, io, env);
885
+ const site = await fetchSite("flypod versions", target, args, io, env);
496
886
  if ("error" in site)
497
887
  return site.error;
498
888
  const { live_version_id, versions: vers } = site.data;
889
+ const expiresAt = site.data.expires_at ?? null;
499
890
  if (args.json) {
500
- io.out(JSON.stringify({ ok: true, site_id: target.site_id, live_version_id, versions: vers }));
891
+ io.out(JSON.stringify({
892
+ ok: true,
893
+ site_id: target.site_id,
894
+ live_version_id,
895
+ versions: vers,
896
+ expires_at: expiresAt,
897
+ ...agentNext({ siteId: target.site_id, expiresAt, owned: expiresAt === null })
898
+ }));
501
899
  return 0;
502
900
  }
503
901
  for (const v of [...vers].reverse()) {
504
- io.out(`${v.version_id} ${v.created_at} ${v.version_id === live_version_id ? "live" : ""}`);
902
+ io.out(`${v.version_id} ${timestamp(v.created_at)} ${v.version_id === live_version_id ? "live" : ""}`);
505
903
  }
904
+ for (const line of expiryLines({ expiresAt, style: io.style, check: false }))
905
+ io.err(line);
506
906
  return 0;
507
907
  }
508
908
  async function rollback(args, io) {
@@ -510,10 +910,11 @@ async function rollback(args, io) {
510
910
  if (typeof pre === "number")
511
911
  return pre;
512
912
  const { env, target } = pre;
513
- const site = await fetchSite(target, args, io, env);
913
+ const site = await fetchSite("flypod rollback", target, args, io, env);
514
914
  if ("error" in site)
515
915
  return site.error;
516
916
  const { live_version_id, versions: vers } = site.data;
917
+ const listThem = "Run `flypod versions` to see them.";
517
918
  let chosen;
518
919
  if (args.version) {
519
920
  const exact = vers.find((v) => v.version_id === args.version);
@@ -523,29 +924,33 @@ async function rollback(args, io) {
523
924
  else if (prefixed.length === 1)
524
925
  chosen = prefixed[0]?.version_id;
525
926
  else if (prefixed.length === 0) {
526
- 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
+ });
527
930
  } else {
528
- 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}` });
529
932
  }
530
933
  } else {
531
934
  if (vers.length < 2) {
532
- 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);
533
936
  }
534
937
  const liveIdx = vers.findIndex((v) => v.version_id === live_version_id);
535
938
  if (liveIdx <= 0) {
536
- 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
+ });
537
942
  }
538
943
  chosen = vers[liveIdx - 1]?.version_id;
539
944
  }
540
945
  const client = await clientForTarget(target, args, io);
541
- const res = await client.rollback(target.site_id, chosen);
542
- if (res.status === 404) {
543
- await healGone(target, io, env);
544
- return fail(`Site ${target.site_id} not found.`, args, io, { silent: true });
545
- }
546
- if (!res.ok) {
547
- 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" });
548
951
  }
952
+ if (!res.ok)
953
+ return failSiteRequest("flypod rollback", res, target, args, io, env);
549
954
  const body = await res.json();
550
955
  await touchLink(target, body.live_version_id, env);
551
956
  const url = target.rec?.url ?? siteUrlFrom(target.site_id, client.baseUrl);
@@ -558,7 +963,13 @@ async function rollback(args, io) {
558
963
  }));
559
964
  return 0;
560
965
  }
561
- io.err(`→ rolled back to ${body.live_version_id}`);
966
+ for (const line of rollbackTail({
967
+ versionId: body.live_version_id,
968
+ url,
969
+ style: io.style
970
+ })) {
971
+ io.err(line);
972
+ }
562
973
  io.out(url);
563
974
  return 0;
564
975
  }
@@ -570,12 +981,18 @@ async function token(args, io) {
570
981
  const env = io.env ?? process.env;
571
982
  const record = args.site ? Object.values(await loadProjects(env)).find((p) => p.site_id === args.site) : await projectForDir(io.cwd ?? process.cwd(), env);
572
983
  if (!record) {
573
- 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>.");
574
- 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" });
575
987
  }
576
988
  if (!record.manage_token) {
577
- io.err(`Site ${record.site_id} has no stored manage token. If you claimed it, it authenticates with your account — run \`flypod login\`.`);
578
- 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;
579
996
  }
580
997
  io.err(`Manage token for ${record.site_id} — treat it like a password.
581
998
  `);
@@ -590,12 +1007,24 @@ async function forget(args, io) {
590
1007
  const env = io.env ?? process.env;
591
1008
  if (args.site) {
592
1009
  const n = await forgetSite(args.site, env);
593
- 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
+ }
594
1015
  return 0;
595
1016
  }
596
1017
  const cwd = io.cwd ?? process.cwd();
597
1018
  const rec = await projectForDir(cwd, env);
598
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
+ }
599
1028
  io.err(removed && rec ? `Forgot ${rec.site_id} for this folder.` : "Nothing linked to this folder.");
600
1029
  return 0;
601
1030
  }
@@ -646,20 +1075,17 @@ function parseFlags(argv, spec) {
646
1075
  }
647
1076
 
648
1077
  // src/cli/comments.ts
649
- 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.";
650
1078
  async function resolveCommentsSite(explicit, io) {
651
1079
  if (explicit)
652
1080
  return explicit;
653
1081
  const rec = await projectForDir(io.cwd ?? process.cwd(), io.env ?? process.env);
654
1082
  return rec?.site_id;
655
1083
  }
656
- function failNoSite(json, io) {
657
- if (json) {
658
- io.out(JSON.stringify({ ok: false, error: "no_site" }));
659
- return 1;
660
- }
661
- io.err(NO_SITE2);
662
- 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
+ });
663
1089
  }
664
1090
  async function resolveSiteAndThread(f, io) {
665
1091
  if (f.site)
@@ -672,101 +1098,105 @@ async function resolveSiteAndThread(f, io) {
672
1098
  thread_id: f.positionals[0]
673
1099
  };
674
1100
  }
675
- function requireCommentWriteToken(token2, io) {
676
- if (!token2) {
677
- io.err("Not signed in. Run `flypod login` or set FLYPOD_TOKEN.");
678
- return 3;
679
- }
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 });
680
1105
  if (token2.startsWith("fk_")) {
681
- io.err("comments operations require an account session or agent token");
682
- 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." });
683
1107
  }
684
1108
  return null;
685
1109
  }
686
- async function readErrorBody(res) {
1110
+ async function send(verb, client, siteId, call, args, io) {
1111
+ const prefix = `flypod comments ${verb}`;
1112
+ let res;
687
1113
  try {
688
- const body = await res.json();
689
- if (body?.code)
690
- return body.code;
691
- if (body?.error)
692
- return body.error;
693
- } catch {}
694
- 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);
695
1140
  }
696
1141
  async function commentsMode(args, io) {
697
- if (!args.mode) {
698
- io.err(`Usage: flypod comments mode <anonymous|passcode|approved> [--site <id>] [--passcode <s>]
699
- ` + " --site defaults to the site linked to this folder.");
700
- return 2;
701
- }
1142
+ if (!args.mode)
1143
+ return usage("mode", args, io);
702
1144
  const allowed = new Set(["anonymous", "passcode", "approved", "open", "review", "members"]);
703
1145
  if (!allowed.has(args.mode)) {
704
- io.err(`Unknown mode "${args.mode}". Expected anonymous|passcode|approved.`);
705
- return 2;
706
- }
707
- if (!args.site) {
708
- io.err("Missing --site <id>.");
709
- return 2;
1146
+ return fail("usage", `Unknown mode "${args.mode}". Expected anonymous|passcode|approved.`, args, io);
710
1147
  }
1148
+ if (!args.site)
1149
+ return usage("mode", args, io);
711
1150
  const env = io.env ?? process.env;
712
1151
  const client = await createClient({ env, fetch: io.fetch });
713
1152
  if (!client.token) {
714
- io.err("Not signed in. Run `flypod login` or set FLYPOD_TOKEN.");
715
- return 3;
1153
+ return emitError(NOT_SIGNED_IN, args, io, { prefix: "flypod comments mode" });
716
1154
  }
717
1155
  const body = { enabled: true, mode: args.mode };
718
1156
  if (args.passcode)
719
1157
  body.passcode = args.passcode;
720
- const res = await client.setCommentsMode(args.site, body);
721
- if (!res.ok) {
722
- io.err(`flypod comments mode: ${await readErrorBody(res)}`);
723
- return res.status >= 500 ? 4 : 1;
724
- }
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;
725
1162
  if (args.json)
726
- 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 }));
727
1164
  else
728
- io.err(`Comments mode set to ${args.mode} on ${args.site}.`);
1165
+ io.err(`Comments mode set to ${args.mode} on ${site}.`);
729
1166
  return 0;
730
1167
  }
731
1168
  async function commentsOff(args, io) {
732
- if (!args.site) {
733
- io.err("Missing --site <id>.");
734
- return 2;
735
- }
1169
+ if (!args.site)
1170
+ return usage("off", args, io);
736
1171
  const env = io.env ?? process.env;
737
1172
  const client = await createClient({ env, fetch: io.fetch });
738
1173
  if (!client.token) {
739
- io.err("Not signed in. Run `flypod login` or set FLYPOD_TOKEN.");
740
- return 3;
741
- }
742
- const res = await client.setCommentsMode(args.site, { enabled: false });
743
- if (!res.ok) {
744
- io.err(`flypod comments off: ${await readErrorBody(res)}`);
745
- return res.status >= 500 ? 4 : 1;
1174
+ return emitError(NOT_SIGNED_IN, args, io, { prefix: "flypod comments off" });
746
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;
747
1180
  if (args.json)
748
- io.out(JSON.stringify({ ok: true, site_id: args.site, enabled: false }));
1181
+ io.out(JSON.stringify({ ok: true, site_id: site, enabled: false }));
749
1182
  else
750
- io.err(`Comments disabled on ${args.site}.`);
1183
+ io.err(`Comments disabled on ${site}.`);
751
1184
  return 0;
752
1185
  }
753
1186
  async function commentsList(args, io) {
754
- if (!args.site) {
755
- io.err("Usage: flypod comments list <site> [--page <p>] [--open|--resolved|--all] [--limit N]");
756
- return 2;
757
- }
1187
+ if (!args.site)
1188
+ return usage("list", args, io);
758
1189
  const env = io.env ?? process.env;
759
1190
  const client = await createClient({ env, fetch: io.fetch });
760
- const res = await client.listComments(args.site, {
1191
+ const site = args.site;
1192
+ const sent = await send("list", client, site, () => client.listComments(site, {
761
1193
  page: args.page,
762
1194
  status: args.status,
763
1195
  limit: args.limit !== undefined ? String(args.limit) : undefined
764
- });
765
- if (!res.ok) {
766
- io.err(`flypod comments list: ${await readErrorBody(res)}`);
767
- return res.status >= 500 ? 4 : 1;
768
- }
769
- const body = await res.json();
1196
+ }), args, io);
1197
+ if ("code" in sent)
1198
+ return sent.code;
1199
+ const body = await sent.res.json();
770
1200
  const threads = Array.isArray(body.threads) ? body.threads : [];
771
1201
  if (args.json) {
772
1202
  for (const t of threads)
@@ -779,72 +1209,60 @@ async function commentsList(args, io) {
779
1209
  return 0;
780
1210
  }
781
1211
  async function commentsShow(args, io) {
782
- if (!args.site || !args.thread_id) {
783
- io.err("Usage: flypod comments show <site> <thread_id>");
784
- return 2;
785
- }
1212
+ if (!args.site || !args.thread_id)
1213
+ return usage("show", args, io);
786
1214
  const env = io.env ?? process.env;
787
1215
  const client = await createClient({ env, fetch: io.fetch });
788
- const res = await client.getThread(args.site, args.thread_id);
789
- if (!res.ok) {
790
- io.err(`flypod comments show: ${await readErrorBody(res)}`);
791
- return res.status >= 500 ? 4 : 1;
792
- }
793
- 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();
794
1221
  io.out(JSON.stringify(body));
795
1222
  return 0;
796
1223
  }
797
1224
  async function commentsPost(args, io) {
798
- if (!args.site || !args.page || !args.target || !args.body) {
799
- io.err("Usage: flypod comments post <site> --page <path> --target <json> --body <text>");
800
- return 2;
801
- }
1225
+ if (!args.site || !args.page || !args.target || !args.body)
1226
+ return usage("post", args, io);
802
1227
  const env = io.env ?? process.env;
803
1228
  const client = await createClient({ env, fetch: io.fetch });
804
- const reject = requireCommentWriteToken(client.token, io);
1229
+ const reject = requireCommentWriteToken("post", client.token, args, io);
805
1230
  if (reject !== null)
806
1231
  return reject;
807
1232
  let target;
808
1233
  try {
809
1234
  target = JSON.parse(args.target);
810
1235
  } catch {
811
- io.err("Invalid --target JSON.");
812
- return 2;
813
- }
814
- const res = await client.postComment(args.site, {
815
- page_path: args.page,
816
- anchor: target,
817
- body: args.body
818
- });
819
- if (!res.ok) {
820
- io.err(`flypod comments post: ${await readErrorBody(res)}`);
821
- 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
+ });
822
1239
  }
823
- 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();
824
1246
  io.out(JSON.stringify(body));
825
1247
  return 0;
826
1248
  }
827
1249
  async function setThreadStatus(endpoint, args, io) {
828
- if (!args.site || !args.thread_id) {
829
- io.err(`Usage: flypod comments ${endpoint} [<site>] <thread_id>
830
- ` + " The site defaults to the one linked to this folder.");
831
- return 2;
832
- }
1250
+ if (!args.site || !args.thread_id)
1251
+ return usage(endpoint, args, io);
833
1252
  const env = io.env ?? process.env;
834
1253
  const client = await createClient({ env, fetch: io.fetch });
835
- const reject = requireCommentWriteToken(client.token, io);
1254
+ const reject = requireCommentWriteToken(endpoint, client.token, args, io);
836
1255
  if (reject !== null)
837
1256
  return reject;
838
- const res = await client.setThreadStatus(args.site, args.thread_id, endpoint);
839
- if (!res.ok) {
840
- io.err(`flypod comments ${endpoint}: ${await readErrorBody(res)}`);
841
- return res.status >= 500 ? 4 : res.status === 401 || res.status === 403 ? 3 : 1;
842
- }
843
- 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(() => ({}));
844
1262
  if (args.json)
845
1263
  io.out(JSON.stringify({ ok: true, ...body }));
846
1264
  else
847
- io.err(`Thread ${args.thread_id} ${endpoint === "resolve" ? "resolved" : "reopened"}.`);
1265
+ io.err(`Thread ${thread_id} ${endpoint === "resolve" ? "resolved" : "reopened"}.`);
848
1266
  return 0;
849
1267
  }
850
1268
  function commentsResolve(args, io) {
@@ -854,11 +1272,8 @@ function commentsReopen(args, io) {
854
1272
  return setThreadStatus("reopen", args, io);
855
1273
  }
856
1274
  async function commentsEnable(args, io) {
857
- if (!args.site) {
858
- io.err(`Usage: flypod comments enable [--site <id>] [--mode anonymous|passcode|approved] [--passcode <s>]
859
- ` + " --site defaults to the site linked to this folder.");
860
- return 2;
861
- }
1275
+ if (!args.site)
1276
+ return usage("enable", args, io);
862
1277
  return commentsMode({ mode: args.mode ?? "anonymous", site: args.site, passcode: args.passcode, json: args.json }, io);
863
1278
  }
864
1279
  var COMMENTS_FLAG_SPEC = {
@@ -874,14 +1289,17 @@ var COMMENTS_FLAG_SPEC = {
874
1289
  "--open": "bool",
875
1290
  "--resolved": "bool",
876
1291
  "--all": "bool",
877
- "--json": "bool"
1292
+ "--json": "bool",
1293
+ "-h": "bool",
1294
+ "--help": "bool"
878
1295
  };
879
1296
  function parseCommentFlags(tail) {
880
- const { flags, positionals } = parseFlags(tail, COMMENTS_FLAG_SPEC);
1297
+ const { flags, positionals, unknown } = parseFlags(tail, COMMENTS_FLAG_SPEC);
881
1298
  const limitRaw = flags["--limit"];
882
1299
  const status = flags["--all"] ? "all" : flags["--resolved"] ? "resolved" : flags["--open"] ? "open" : undefined;
883
1300
  return {
884
1301
  positionals,
1302
+ unknown,
885
1303
  site: flags["--site"],
886
1304
  mode: flags["--mode"],
887
1305
  page: flags["--page"],
@@ -892,77 +1310,91 @@ function parseCommentFlags(tail) {
892
1310
  passcode: flags["--passcode"],
893
1311
  limit: limitRaw ? Number(limitRaw) : undefined,
894
1312
  status,
895
- json: Boolean(flags["--json"])
1313
+ json: Boolean(flags["--json"]),
1314
+ help: Boolean(flags["-h"] || flags["--help"])
896
1315
  };
897
1316
  }
1317
+ var VERBS = ["enable", "mode", "off", "list", "show", "post", "resolve", "reopen"];
898
1318
  async function commentsCommand(argv, io) {
1319
+ const json = argv.includes("--json");
899
1320
  if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {
900
- io.err("Usage: flypod comments <enable|mode|off|list|show|post|resolve|reopen> [args]");
901
- 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);
902
1327
  }
903
1328
  const verb = argv[0];
904
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
+ }
905
1346
  switch (verb) {
906
1347
  case "enable": {
907
- const f = parseCommentFlags(rest);
908
1348
  const site = await resolveCommentsSite(f.site ?? f.positionals[0], io);
909
1349
  if (!site)
910
- return failNoSite(f.json, io);
1350
+ return failNoSite(verb, f.json, io);
911
1351
  return commentsEnable({ site, mode: f.mode, passcode: f.passcode, json: f.json }, io);
912
1352
  }
913
1353
  case "mode": {
914
- const f = parseCommentFlags(rest);
915
1354
  const mode = f.positionals[0];
916
1355
  const site = await resolveCommentsSite(f.site ?? f.positionals[1], io);
917
1356
  if (!site)
918
- return failNoSite(f.json, io);
1357
+ return failNoSite(verb, f.json, io);
919
1358
  return commentsMode({ mode, site, passcode: f.passcode, json: f.json }, io);
920
1359
  }
921
1360
  case "off": {
922
- const f = parseCommentFlags(rest);
923
1361
  const site = await resolveCommentsSite(f.site ?? f.positionals[0], io);
924
1362
  if (!site)
925
- return failNoSite(f.json, io);
1363
+ return failNoSite(verb, f.json, io);
926
1364
  return commentsOff({ site, json: f.json }, io);
927
1365
  }
928
1366
  case "list": {
929
- const f = parseCommentFlags(rest);
930
1367
  const site = await resolveCommentsSite(f.positionals[0] ?? f.site, io);
931
1368
  if (!site)
932
- return failNoSite(f.json, io);
1369
+ return failNoSite(verb, f.json, io);
933
1370
  return commentsList({ site, page: f.page, status: f.status, limit: f.limit, json: f.json }, io);
934
1371
  }
935
1372
  case "show": {
936
- const f = parseCommentFlags(rest);
937
1373
  const { site, thread_id } = await resolveSiteAndThread(f, io);
938
1374
  if (!site)
939
- return failNoSite(f.json, io);
1375
+ return failNoSite(verb, f.json, io);
940
1376
  return commentsShow({ site, thread_id, json: f.json }, io);
941
1377
  }
942
1378
  case "post": {
943
- const f = parseCommentFlags(rest);
944
1379
  const site = await resolveCommentsSite(f.positionals[0] ?? f.site, io);
945
1380
  if (!site)
946
- return failNoSite(f.json, io);
1381
+ return failNoSite(verb, f.json, io);
947
1382
  return commentsPost({ site, page: f.page, target: f.target, body: f.body, json: f.json }, io);
948
1383
  }
949
1384
  case "resolve": {
950
- const f = parseCommentFlags(rest);
951
1385
  const { site, thread_id } = await resolveSiteAndThread(f, io);
952
1386
  if (!site)
953
- return failNoSite(f.json, io);
1387
+ return failNoSite(verb, f.json, io);
954
1388
  return commentsResolve({ site, thread_id, json: f.json }, io);
955
1389
  }
956
1390
  case "reopen": {
957
- const f = parseCommentFlags(rest);
958
1391
  const { site, thread_id } = await resolveSiteAndThread(f, io);
959
1392
  if (!site)
960
- return failNoSite(f.json, io);
1393
+ return failNoSite(verb, f.json, io);
961
1394
  return commentsReopen({ site, thread_id, json: f.json }, io);
962
1395
  }
963
1396
  default:
964
- io.err(`flypod comments: unknown verb "${verb}"`);
965
- return 2;
1397
+ return fail("unknown_command", `flypod comments: unknown verb "${verb}"`, f, io);
966
1398
  }
967
1399
  }
968
1400
 
@@ -1213,14 +1645,26 @@ var TOP_LEVEL_FLAG_SPEC = {
1213
1645
  "--comments": "bool",
1214
1646
  "--mode": "value"
1215
1647
  };
1216
- function parseArgs(argv) {
1217
- const { flags, positionals, unknown } = parseFlags(argv, TOP_LEVEL_FLAG_SPEC);
1218
- if (unknown.length > 0) {
1219
- process.stderr.write(`flypod: unknown flag "${unknown[0]}"
1220
- 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}
1221
1660
  `);
1222
- process.exit(2);
1223
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");
1224
1668
  return {
1225
1669
  path: positionals[0],
1226
1670
  json: Boolean(flags["--json"]),
@@ -1242,11 +1686,20 @@ var SUB_FLAG_SPEC = {
1242
1686
  };
1243
1687
  var LOGIN_FLAG_SPEC = {
1244
1688
  "--token": "value",
1689
+ "--device-code": "value",
1690
+ "--json": "bool",
1245
1691
  "-h": "bool",
1246
1692
  "--help": "bool"
1247
1693
  };
1248
- function parseSub(argv) {
1249
- const { flags, positionals } = parseFlags(argv, SUB_FLAG_SPEC);
1694
+ var ACCOUNT_FLAG_SPEC = {
1695
+ "--json": "bool",
1696
+ "-h": "bool",
1697
+ "--help": "bool"
1698
+ };
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`);
1250
1703
  return {
1251
1704
  positionals,
1252
1705
  site: flags["--site"],
@@ -1261,43 +1714,58 @@ async function runSubcommand(name, argv) {
1261
1714
  out: (line) => process.stdout.write(`${line}
1262
1715
  `),
1263
1716
  err: (line) => process.stderr.write(`${line}
1264
- `)
1717
+ `),
1718
+ style: makeStyle(colorsEnabled(process.stderr))
1265
1719
  };
1266
1720
  switch (name) {
1267
1721
  case "update": {
1268
- const { positionals, site, token: token2, json, quiet, help } = parseSub(argv);
1722
+ const { positionals, site, token: token2, json, quiet, help } = parseSub(name, argv);
1269
1723
  return update({ path: positionals[0], site, token: token2, json, quiet, help }, io);
1270
1724
  }
1271
1725
  case "versions": {
1272
- const { site, token: token2, json, help } = parseSub(argv);
1726
+ const { site, token: token2, json, help } = parseSub(name, argv);
1273
1727
  return versions({ site, token: token2, json, help }, io);
1274
1728
  }
1275
1729
  case "rollback": {
1276
- const { positionals, site, token: token2, json, help } = parseSub(argv);
1730
+ const { positionals, site, token: token2, json, help } = parseSub(name, argv);
1277
1731
  return rollback({ version: positionals[0], site, token: token2, json, help }, io);
1278
1732
  }
1279
1733
  case "forget": {
1280
- const { site, help } = parseSub(argv);
1281
- return forget({ site, help }, io);
1734
+ const { site, json, help } = parseSub(name, argv);
1735
+ return forget({ site, json, help }, io);
1282
1736
  }
1283
1737
  case "token": {
1284
- const { site, help } = parseSub(argv);
1285
- return token({ site, help }, io);
1738
+ const { site, json, help } = parseSub(name, argv);
1739
+ return token({ site, json, help }, io);
1286
1740
  }
1287
1741
  case "login": {
1288
- 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");
1289
1745
  return login({
1290
1746
  token: flags["--token"],
1747
+ deviceCode: flags["--device-code"],
1748
+ json: Boolean(flags["--json"]),
1291
1749
  help: Boolean(flags["-h"] || flags["--help"])
1292
1750
  }, io);
1293
1751
  }
1294
- case "logout":
1295
- return logout({}, io);
1296
- case "list":
1297
- 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
+ }
1298
1764
  case "claim": {
1299
- const { positionals } = parseFlags(argv, {});
1300
- 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);
1301
1769
  }
1302
1770
  case "install":
1303
1771
  return runInstall(argv, io);
@@ -1322,12 +1790,8 @@ async function runInstall(argv, io) {
1322
1790
  return 2;
1323
1791
  }
1324
1792
  const { flags, unknown } = parseFlags(argv, INSTALL_FLAG_SPEC);
1325
- const unknownFlag = unknown[0];
1326
- if (unknownFlag) {
1327
- io.err(`flypod: unknown flag "${unknownFlag}"`);
1328
- io.err("Run `flypod install skill --list` to see available targets and flags.");
1329
- return 2;
1330
- }
1793
+ if (unknown[0])
1794
+ rejectUnknownFlag(unknown[0], argv, "flypod install skill --list");
1331
1795
  const targets = [];
1332
1796
  for (const [flag, id] of Object.entries(TARGET_FLAGS)) {
1333
1797
  if (flags[flag] && !targets.includes(id))
@@ -1374,7 +1838,7 @@ async function readVersion() {
1374
1838
  return "0.0.0";
1375
1839
  }
1376
1840
  function showHelp(version) {
1377
- const usage = `flypod v${version}
1841
+ const usage2 = `flypod v${version}
1378
1842
  Drop files, get a live URL. Every deploy is versioned, so you can roll back.
1379
1843
 
1380
1844
  THE LOOP (this is all most agents need):
@@ -1412,6 +1876,16 @@ Ownership — two states, one command:
1412
1876
  Logging in claims EVERY temporary site this machine remembers, not just the
1413
1877
  last one — so "deploy now, log in whenever" works. You never need a token.
1414
1878
 
1879
+ 'flypod versions' prints the expiry date any time, so the end date is never
1880
+ a surprise. Claiming changes nothing else: same URL, same versions.
1881
+
1882
+ Attribution:
1883
+ flypod adds a small block of <meta> and JSON-LD to served HTML so crawlers
1884
+ can tell what hosts the page. It renders nothing and runs no script. To turn
1885
+ it off completely, put this anywhere in your page:
1886
+
1887
+ <meta name="flypod" content="none">
1888
+
1415
1889
  flypod login Sign in (opens your browser to confirm) and
1416
1890
  keep every site deployed from this machine.
1417
1891
  flypod login --token <t> Save a session token directly (skip the browser).
@@ -1477,26 +1951,25 @@ When no path is given, flypod looks for a build folder in the current directory:
1477
1951
 
1478
1952
  Docs: https://flypod.dev
1479
1953
  `;
1480
- process.stdout.write(usage);
1954
+ process.stdout.write(usage2);
1481
1955
  }
1482
1956
  function shortDir(dir) {
1483
1957
  const rel = relative(process.cwd(), dir);
1484
1958
  return rel === "" || rel.startsWith("..") ? dir : rel || ".";
1485
1959
  }
1486
- function fail2(msg, args, style, opts = {}) {
1960
+ function fail2(err, args, style, opts = {}) {
1487
1961
  if (args.json) {
1488
- process.stdout.write(`${JSON.stringify({ ok: false, error: msg })}
1489
- `);
1490
- } else if (opts.dimOnly) {
1491
- process.stderr.write(` ${style.dim(msg)}
1492
-
1962
+ process.stdout.write(`${JSON.stringify(errorEnvelope(err))}
1493
1963
  `);
1494
1964
  } else {
1495
- process.stderr.write(` ${style.err("✗")} ${msg}
1496
-
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}
1497
1970
  `);
1498
1971
  }
1499
- process.exit(1);
1972
+ process.exit(exitCodeFor(err.code));
1500
1973
  }
1501
1974
  async function main() {
1502
1975
  const rawArgv = process.argv.slice(2);
@@ -1524,30 +1997,46 @@ async function main() {
1524
1997
  if (useUI) {
1525
1998
  process.stderr.write(`
1526
1999
  ${style.bold(style.accent("flypod"))} ${style.dim(`v${version}`)}
1527
-
1528
2000
  `);
1529
2001
  if (!apiKey) {
1530
- process.stderr.write(` ${style.muted("account")} ${style.dim("anonymous · deploy now, ")}${style.bold("flypod login")}${style.dim(" later to keep it")}
1531
-
2002
+ process.stderr.write(` ${style.muted("account")} ${style.dim("anonymous · deploy now, ")}${style.bold("flypod login")}${style.dim(" later")}
1532
2003
  `);
1533
2004
  }
2005
+ process.stderr.write(`
2006
+ `);
2007
+ }
2008
+ const priorLink = await projectForDir(process.cwd()).catch(() => null);
2009
+ if (priorLink && useUI) {
2010
+ for (const line of relinkNotice(priorLink, style))
2011
+ process.stderr.write(`${line}
2012
+ `);
2013
+ process.stderr.write(`
2014
+ `);
1534
2015
  }
1535
2016
  let dir;
1536
2017
  try {
1537
2018
  dir = await resolveDeployDir({ explicit: args.path });
1538
2019
  } catch (error) {
1539
- fail2(error.message, args, style);
2020
+ fail2({ code: "no_build_dir", error: error.message }, args, style);
1540
2021
  }
1541
2022
  let files;
1542
2023
  try {
1543
2024
  files = await collectDist(dir);
1544
2025
  } catch (error) {
1545
- 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);
1546
2031
  }
1547
2032
  const fileNames = Object.keys(files);
1548
2033
  const totalBytes = fileNames.reduce((sum, name) => sum + (files[name]?.byteLength ?? 0), 0);
1549
2034
  if (fileNames.length === 0) {
1550
- 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);
1551
2040
  }
1552
2041
  if (useUI) {
1553
2042
  process.stderr.write(` ${style.muted("source")} ${style.bold(shortDir(dir))} ${style.dim(`${fmtCount(fileNames.length, "file")} · ${fmtBytes(totalBytes)}`)}
@@ -1561,7 +2050,8 @@ async function main() {
1561
2050
  result = await deploySite({ baseUrl, files, apiKey, source: client.source });
1562
2051
  } catch (error) {
1563
2052
  spinner.fail("Deploy failed.");
1564
- 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 });
1565
2055
  }
1566
2056
  const elapsed = Date.now() - started;
1567
2057
  spinner.success(`Deployed in ${fmtSeconds(elapsed)}`);
@@ -1598,7 +2088,7 @@ async function main() {
1598
2088
  process.stderr.write(` ${style.muted("comments")} ${style.dim(`enabled (${mode})`)}
1599
2089
  `);
1600
2090
  } else {
1601
- process.stderr.write(` ${style.muted("comments")} ${style.dim(`failed to enable — run \`flypod comments enable --site ${result.site_id}\``)}
2091
+ process.stderr.write(` ${style.muted("comments")} ${style.dim("failed — run `flypod comments enable`")}
1602
2092
  `);
1603
2093
  }
1604
2094
  }
@@ -1621,6 +2111,14 @@ async function main() {
1621
2111
  elapsed_ms: elapsed,
1622
2112
  healed: result.healed ?? [],
1623
2113
  warnings: result.warnings ?? [],
2114
+ link_saved: linkSaved,
2115
+ ...agentNext({
2116
+ siteId: result.site_id,
2117
+ expiresAt: result.expires_at,
2118
+ owned,
2119
+ linkSaved
2120
+ }),
2121
+ ...priorLink && priorLink.site_id !== result.site_id ? { replaced_link: { site_id: priorLink.site_id, url: priorLink.url } } : {},
1624
2122
  ...args.comments ? { comments_enabled: commentsEnabled, comments_mode: args.commentsMode } : {}
1625
2123
  }, null, 2)}
1626
2124
  `);
@@ -1635,8 +2133,7 @@ async function main() {
1635
2133
  return;
1636
2134
  }
1637
2135
  const rule = style.dim("─".repeat(56));
1638
- process.stderr.write(`
1639
- ${rule}
2136
+ process.stderr.write(` ${rule}
1640
2137
  `);
1641
2138
  process.stderr.write(` ${style.ok("●")} ${style.bold("Live")}
1642
2139
  `);
@@ -1645,14 +2142,11 @@ async function main() {
1645
2142
  process.stderr.write(` ${rule}
1646
2143
 
1647
2144
  `);
1648
- const expiry = typeof result.expires_at === "number" ? `in ${Math.max(0, Math.round((result.expires_at - Date.now()) / 86400000))} days · \`flypod login\` keeps this and every other site you deployed here` : result.owner_account_id ? "never . attributed to your account" : "never (claimed)";
1649
- process.stderr.write(` ${style.muted("expires")} ${style.dim(expiry)}
1650
-
2145
+ for (const line of deployTail({ expiresAt: result.expires_at, owned, style })) {
2146
+ process.stderr.write(`${line}
1651
2147
  `);
1652
- process.stderr.write(` ${style.muted("ship a change")} ${style.bold("flypod update")} ${style.dim("(new version of this site)")}
1653
- ` + ` ${style.muted("roll back")} ${style.bold("flypod rollback")}
1654
- ` + ` ${style.muted("history")} ${style.bold("flypod versions")}
1655
-
2148
+ }
2149
+ process.stderr.write(`
1656
2150
  `);
1657
2151
  if (!linkSaved && !owned) {
1658
2152
  process.stderr.write(` ${style.err("!")} ${style.bold("Couldn't remember this site")} ${style.dim(`— can't write ${projectsFilePath()}`)}
@@ -1669,10 +2163,15 @@ async function main() {
1669
2163
  `);
1670
2164
  }
1671
2165
  main().catch((error) => {
1672
- process.stderr.write(`
1673
- flypod: unexpected error
1674
- ${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}
1675
2173
 
1676
2174
  `);
1677
- process.exit(1);
2175
+ }
2176
+ process.exit(exitCodeFor(err.code));
1678
2177
  });