@firstdraft.com/cli 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.js CHANGED
@@ -8,13 +8,17 @@ import {
8
8
  } from "./application-identity.js";
9
9
  import {
10
10
  ApiAuthenticationRequiredError,
11
+ STAGING_API_URL,
11
12
  authenticateApiCommand,
13
+ environmentTokenFor,
12
14
  isAuthenticationProblem,
13
15
  } from "./api-authentication.js";
14
16
  import {
15
17
  CompilationArtifactInvalidError,
16
18
  CompilationArtifactResponseInvalidError,
17
19
  CompilationArtifactUnavailableError,
20
+ CompilationCancelRejectedError,
21
+ CompilationCancelUnavailableError,
18
22
  CompilationCancelledError,
19
23
  CompilationChangedError,
20
24
  CompilationFailedError,
@@ -30,6 +34,7 @@ import {
30
34
  CompilationStatusInvalidError,
31
35
  CompilationStatusUnavailableError,
32
36
  CompilationTimeoutError,
37
+ cancelCompilation,
33
38
  downloadCompilation,
34
39
  readCompilation,
35
40
  } from "./commands/compilation.js";
@@ -42,6 +47,14 @@ import {
42
47
  compilePlanToGitHub,
43
48
  compilePlanToDirectory,
44
49
  } from "./commands/plan-compile.js";
50
+ import {
51
+ LoginDeniedError,
52
+ LoginExpiredError,
53
+ LoginFailedError,
54
+ login,
55
+ resolveLoginOrigin,
56
+ } from "./commands/login.js";
57
+ import { LogoutFailedError, logout } from "./commands/logout.js";
45
58
  import { initializePlan } from "./commands/plan-init.js";
46
59
  import {
47
60
  PublicationCancelledError,
@@ -70,6 +83,7 @@ import {
70
83
  PlanStatusTimeoutError,
71
84
  readPlanStatus,
72
85
  } from "./commands/plan-status.js";
86
+ import { storedTokenReader } from "./credentials.js";
73
87
  import { isFileSystemError } from "./file-system.js";
74
88
  import { createPlanCompileProgressReporter } from "./plan-compile-progress.js";
75
89
  import { isUuidV7 } from "./plan-state.js";
@@ -83,8 +97,10 @@ Usage:
83
97
  firstdraft [options]
84
98
 
85
99
  Commands:
86
- compilation Inspect and download Compilations
100
+ compilation Inspect, download, and cancel Compilations
87
101
  generate Generate local values
102
+ login Log in to First Draft and save a token
103
+ logout Revoke and remove the saved token
88
104
  plan Work with Foundation Plans
89
105
 
90
106
  Options:
@@ -217,6 +233,7 @@ Usage:
217
233
  Commands:
218
234
  status Read one retained Compilation
219
235
  download Download one successful Compilation artifact
236
+ cancel Cancel one queued or running Compilation
220
237
 
221
238
  Options:
222
239
  -h, --help Show help
@@ -261,6 +278,25 @@ materializes it into an absent output path or adopts the current directory
261
278
  while preserving existing material under .firstdraft/design. It never starts work.
262
279
  `;
263
280
 
281
+ const COMPILATION_CANCEL_HELP = `First Draft CLI
282
+
283
+ Usage:
284
+ firstdraft compilation cancel <compilation-id>
285
+
286
+ Options:
287
+ --staging Use staging; reject a different saved origin
288
+ -h, --help Show help
289
+
290
+ Environment:
291
+ FIRSTDRAFT_API_TOKEN Authenticate production or custom API origins
292
+ FIRSTDRAFT_STAGING_API_TOKEN Authenticate staging.firstdraft.com
293
+
294
+ The command asks First Draft once to cancel a queued or running Compilation of
295
+ the local Project and prints the cancelled Compilation. Cancelling it again
296
+ prints the same result; a succeeded or failed Compilation is not changed.
297
+ Once cancelled, it no longer blocks plan push or plan compile.
298
+ `;
299
+
264
300
  const PLAN_INIT_HELP = `First Draft CLI
265
301
 
266
302
  Usage:
@@ -275,6 +311,45 @@ Provide at least one of --application-key or --name. The command derives a
275
311
  missing key from the name or a missing display name from the key.
276
312
  `;
277
313
 
314
+ const LOGIN_HELP = `First Draft CLI
315
+
316
+ Usage:
317
+ firstdraft login [--interactive]
318
+
319
+ Options:
320
+ --staging Log in to staging
321
+ -i, --interactive Approve with a code on another device (no local browser)
322
+ --device Same as --interactive
323
+ -h, --help Show help
324
+
325
+ Environment:
326
+ FIRSTDRAFT_API_URL Log in to a custom API origin
327
+ XDG_CONFIG_HOME Credentials directory base (default: ~/.config)
328
+
329
+ By default the command prints a URL to open in a browser on this machine, then
330
+ waits up to five minutes for First Draft to redirect to a one-time listener on
331
+ 127.0.0.1. The token is saved for the selected origin in
332
+ firstdraft/credentials.json under the configuration directory and is never
333
+ printed. Token environment variables take precedence over a saved login.
334
+ `;
335
+
336
+ const LOGOUT_HELP = `First Draft CLI
337
+
338
+ Usage:
339
+ firstdraft logout
340
+
341
+ Options:
342
+ --staging Log out of staging
343
+ -h, --help Show help
344
+
345
+ Environment:
346
+ FIRSTDRAFT_API_URL Log out of a custom API origin
347
+
348
+ The command asks First Draft to revoke the saved token for the selected origin,
349
+ then removes it from the credentials file even if revocation is not confirmed.
350
+ Token environment variables are not changed.
351
+ `;
352
+
278
353
  const ROOT_USAGE_ERROR =
279
354
  "Invalid arguments.\nRun 'firstdraft --help' for usage.\n";
280
355
  const ROOT_UNKNOWN_COMMAND =
@@ -304,7 +379,23 @@ const PLAN_PUSH_REQUEST_OUTCOME_UNKNOWN_DETAIL =
304
379
  "The Plan may have been accepted, but the response could not be verified. Stop and reconcile before pushing again; local state was not changed.";
305
380
  const PLAN_PUSH_SERVER_REJECTED_DETAIL = "First Draft rejected the Plan.";
306
381
  const AUTHENTICATION_REQUIRED_DETAIL =
307
- "First Draft authentication is required. Set FIRSTDRAFT_API_TOKEN for production or custom origins, or FIRSTDRAFT_STAGING_API_TOKEN for staging.";
382
+ "First Draft authentication is required. Run 'firstdraft login' for the same environment, or set FIRSTDRAFT_API_TOKEN for production or custom origins, or FIRSTDRAFT_STAGING_API_TOKEN for staging.";
383
+ const LOGIN_INVALID_ARGUMENTS_DETAIL =
384
+ "Invalid arguments. Run 'firstdraft login --help' for usage.";
385
+ const LOGOUT_INVALID_ARGUMENTS_DETAIL =
386
+ "Invalid arguments. Run 'firstdraft logout --help' for usage.";
387
+ const LOGIN_DENIED_DETAIL =
388
+ "The login was denied in the browser. No credential was saved. Run 'firstdraft login' again to retry.";
389
+ const LOGIN_EXPIRED_DETAIL =
390
+ "The login was not approved before it expired. No credential was saved. Run 'firstdraft login' again to retry.";
391
+ const LOGIN_FAILED_DETAIL =
392
+ "The login could not be completed. No credential was saved. Run 'firstdraft login' again, or use 'firstdraft login --interactive' if this machine has no browser.";
393
+ const LOGIN_CREDENTIALS_DETAIL =
394
+ "The credentials file could not be read. No network request was made. Repair or remove it, then run 'firstdraft login' again.";
395
+ const CREDENTIALS_LOCKED_RECOVERY =
396
+ "if no other firstdraft command is running, delete credentials.json.lock next to credentials_path";
397
+ const LOGOUT_FAILED_DETAIL =
398
+ "The credentials file could not be read, so no token was revoked or removed. Repair or remove it, then retry.";
308
399
  const PLAN_STATUS_INVALID_ARGUMENTS_DETAIL =
309
400
  "Invalid arguments. Run 'firstdraft plan status --help' for usage.";
310
401
  const PLAN_STATUS_LOCAL_INPUT_UNREADABLE_DETAIL =
@@ -378,6 +469,8 @@ const COMPILATION_STATUS_INVALID_ARGUMENTS_DETAIL =
378
469
  "Invalid arguments. Run 'firstdraft compilation status --help' for usage.";
379
470
  const COMPILATION_DOWNLOAD_INVALID_ARGUMENTS_DETAIL =
380
471
  "Invalid arguments. Run 'firstdraft compilation download --help' for usage.";
472
+ const COMPILATION_CANCEL_INVALID_ARGUMENTS_DETAIL =
473
+ "Invalid arguments. Run 'firstdraft compilation cancel --help' for usage.";
381
474
  const COMPILATION_LOCAL_INPUT_UNREADABLE_DETAIL =
382
475
  "Could not read valid local First Draft state. No network request was made.";
383
476
  const COMPILATION_NOT_PUSHED_DETAIL =
@@ -392,6 +485,12 @@ const COMPILATION_TIMEOUT_DETAIL =
392
485
  "The retained Compilation is still processing after the bounded ten-minute wait.";
393
486
  const COMPILATION_NOT_SUCCEEDED_DETAIL =
394
487
  "The requested Compilation has not succeeded, so no artifact was downloaded.";
488
+ const COMPILATION_CANCEL_REJECTED_DETAIL =
489
+ "First Draft rejected the cancellation, so nothing was cancelled. response.code compilation_not_cancellable means the Compilation already succeeded or failed; compilation_not_found or project_not_found means First Draft found no such Compilation for this Project and account.";
490
+ const COMPILATION_CANCEL_UNAVAILABLE_DETAIL =
491
+ "Could not confirm the cancellation. Cancelling again is safe: rerun 'firstdraft compilation cancel', or check the Compilation with 'firstdraft compilation status'.";
492
+ const COMPILATION_CANCEL_INVALID_DETAIL =
493
+ "First Draft returned an invalid response to the cancellation, so its outcome is unconfirmed. Check the Compilation with 'firstdraft compilation status'; retrying unchanged will not repair this protocol mismatch.";
395
494
  const COMPILATION_ARTIFACT_UNAVAILABLE_DETAIL =
396
495
  "Could not download the requested Compilation artifact. No files were materialized.";
397
496
  const COMPILATION_ARTIFACT_INVALID_DETAIL =
@@ -445,6 +544,14 @@ const GENERATE_APPLICATION_KEY_INVALID_ARGUMENTS_DETAIL =
445
544
  * @property {string} [apiUrl]
446
545
  * @property {string} [apiToken]
447
546
  * @property {string} [stagingApiToken]
547
+ * @property {Readonly<Record<string, string | undefined>>} [env] Locates the credentials file (XDG_CONFIG_HOME)
548
+ * @property {() => string} [homedir]
549
+ * @property {import("./credentials.js").CredentialsFileSystem} [credentialsFileSystem]
550
+ * @property {number} [credentialsLockTimeoutMs]
551
+ * @property {() => string} [hostname]
552
+ * @property {(delayMs: number, signal?: AbortSignal) => Promise<void>} [loginSleep]
553
+ * @property {() => number} [loginNow]
554
+ * @property {import("./oauth.js").StartLoopbackServer} [startLoopbackServer]
448
555
  */
449
556
 
450
557
  /**
@@ -476,6 +583,11 @@ const GENERATE_APPLICATION_KEY_INVALID_ARGUMENTS_DETAIL =
476
583
  * @property {string} [apiToken]
477
584
  * @property {string} [stagingApiToken]
478
585
  * @property {boolean} [staging]
586
+ * @property {import("./credentials.js").CredentialStore} [credentials]
587
+ * @property {() => string} [hostname]
588
+ * @property {(delayMs: number, signal?: AbortSignal) => Promise<void>} [loginSleep]
589
+ * @property {() => number} [loginNow]
590
+ * @property {import("./oauth.js").StartLoopbackServer} [startLoopbackServer]
479
591
  */
480
592
 
481
593
  /**
@@ -490,6 +602,10 @@ const GENERATE_APPLICATION_KEY_INVALID_ARGUMENTS_DETAIL =
490
602
  * @typedef {Omit<CommandOptions, "cwd" | "createProjectId" | "createUuid" | "fileSystem" | "createTemporaryId" | "planStatusSleep" | "planStatusNow" | "planCompileSleep" | "planCompileNow" | "planPublishSleep" | "planPublishNow" | "planCompilePush" | "planCompileReadStatus" | "planCompilePublish" | "planCompileDownload"> & {cwd?: string, getCwd: () => string}} CompilationCommandOptions
491
603
  */
492
604
 
605
+ /**
606
+ * @typedef {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "fetchFunction" | "createRequestSignal" | "credentials" | "hostname" | "loginSleep" | "loginNow" | "startLoopbackServer" | "apiUrl" | "apiToken" | "stagingApiToken" | "staging">} LoginCommandOptions
607
+ */
608
+
493
609
  /** @param {RunOptions} options */
494
610
  export async function run({
495
611
  argv,
@@ -519,9 +635,43 @@ export async function run({
519
635
  apiUrl = process.env.FIRSTDRAFT_API_URL,
520
636
  apiToken = process.env.FIRSTDRAFT_API_TOKEN,
521
637
  stagingApiToken = process.env.FIRSTDRAFT_STAGING_API_TOKEN,
638
+ env = process.env,
639
+ homedir,
640
+ credentialsFileSystem,
641
+ credentialsLockTimeoutMs,
642
+ hostname,
643
+ loginSleep,
644
+ loginNow,
645
+ startLoopbackServer,
522
646
  }) {
523
647
  const staging = argv[0] === "--staging";
524
648
  if (staging) argv = argv.slice(1);
649
+ /** @type {import("./credentials.js").CredentialStore} */
650
+ const credentials = {
651
+ env,
652
+ homedir,
653
+ fileSystem: credentialsFileSystem,
654
+ lockTimeoutMs: credentialsLockTimeoutMs,
655
+ };
656
+
657
+ if (argv[0] === "login" || argv[0] === "logout") {
658
+ return (argv[0] === "login" ? runLogin : runLogout)({
659
+ argv: argv.slice(1),
660
+ stdout,
661
+ stderr,
662
+ fetchFunction,
663
+ createRequestSignal,
664
+ credentials,
665
+ hostname,
666
+ loginSleep,
667
+ loginNow,
668
+ startLoopbackServer,
669
+ apiUrl,
670
+ apiToken,
671
+ stagingApiToken,
672
+ staging,
673
+ });
674
+ }
525
675
 
526
676
  if (argv[0] === "generate") {
527
677
  return runGenerate({
@@ -561,6 +711,7 @@ export async function run({
561
711
  apiToken,
562
712
  stagingApiToken,
563
713
  staging,
714
+ credentials,
564
715
  });
565
716
  }
566
717
 
@@ -580,6 +731,7 @@ export async function run({
580
731
  apiToken,
581
732
  stagingApiToken,
582
733
  staging,
734
+ credentials,
583
735
  });
584
736
  }
585
737
 
@@ -658,6 +810,7 @@ async function runPlan({
658
810
  apiToken,
659
811
  stagingApiToken,
660
812
  staging,
813
+ credentials,
661
814
  }) {
662
815
  if (argv[0] === "init") {
663
816
  return runPlanInit({
@@ -684,6 +837,7 @@ async function runPlan({
684
837
  apiToken,
685
838
  stagingApiToken,
686
839
  staging,
840
+ credentials,
687
841
  });
688
842
  }
689
843
 
@@ -702,6 +856,7 @@ async function runPlan({
702
856
  apiToken,
703
857
  stagingApiToken,
704
858
  staging,
859
+ credentials,
705
860
  });
706
861
  }
707
862
 
@@ -729,6 +884,7 @@ async function runPlan({
729
884
  apiToken,
730
885
  stagingApiToken,
731
886
  staging,
887
+ credentials,
732
888
  });
733
889
  }
734
890
 
@@ -776,6 +932,7 @@ async function runCompilation({
776
932
  apiToken,
777
933
  stagingApiToken,
778
934
  staging,
935
+ credentials,
779
936
  }) {
780
937
  if (argv[0] === "status") {
781
938
  return runCompilationStatus({
@@ -792,6 +949,7 @@ async function runCompilation({
792
949
  apiToken,
793
950
  stagingApiToken,
794
951
  staging,
952
+ credentials,
795
953
  });
796
954
  }
797
955
 
@@ -808,6 +966,24 @@ async function runCompilation({
808
966
  apiToken,
809
967
  stagingApiToken,
810
968
  staging,
969
+ credentials,
970
+ });
971
+ }
972
+
973
+ if (argv[0] === "cancel") {
974
+ return runCompilationCancel({
975
+ argv: argv.slice(1),
976
+ stdout,
977
+ stderr,
978
+ cwd: cwd ?? getCwd(),
979
+ fetchFunction,
980
+ planPushFileSystem,
981
+ createRequestSignal,
982
+ apiUrl,
983
+ apiToken,
984
+ stagingApiToken,
985
+ staging,
986
+ credentials,
811
987
  });
812
988
  }
813
989
 
@@ -840,7 +1016,7 @@ async function runCompilation({
840
1016
  }
841
1017
 
842
1018
  /**
843
- * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createRequestSignal" | "compilationSleep" | "compilationNow" | "apiUrl" | "apiToken" | "stagingApiToken" | "staging">} options
1019
+ * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createRequestSignal" | "compilationSleep" | "compilationNow" | "apiUrl" | "apiToken" | "stagingApiToken" | "staging" | "credentials">} options
844
1020
  */
845
1021
  async function runCompilationStatus({
846
1022
  argv,
@@ -856,6 +1032,7 @@ async function runCompilationStatus({
856
1032
  apiToken,
857
1033
  stagingApiToken,
858
1034
  staging,
1035
+ credentials,
859
1036
  }) {
860
1037
  const parsed = parseArguments(() =>
861
1038
  parseArgs({
@@ -900,6 +1077,7 @@ async function runCompilationStatus({
900
1077
  apiToken,
901
1078
  stagingApiToken,
902
1079
  staging: staging || parsed.values.staging,
1080
+ readStoredTokens: storedTokenReader(credentials),
903
1081
  });
904
1082
  if (authentication === null) {
905
1083
  writeAuthenticationRequired(stderr);
@@ -925,7 +1103,7 @@ async function runCompilationStatus({
925
1103
  }
926
1104
 
927
1105
  /**
928
- * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createRequestSignal" | "apiUrl" | "apiToken" | "stagingApiToken" | "staging">} options
1106
+ * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createRequestSignal" | "apiUrl" | "apiToken" | "stagingApiToken" | "staging" | "credentials">} options
929
1107
  */
930
1108
  async function runCompilationDownload({
931
1109
  argv,
@@ -939,6 +1117,7 @@ async function runCompilationDownload({
939
1117
  apiToken,
940
1118
  stagingApiToken,
941
1119
  staging,
1120
+ credentials,
942
1121
  }) {
943
1122
  const parsed = parseArguments(() =>
944
1123
  parseArgs({
@@ -989,6 +1168,7 @@ async function runCompilationDownload({
989
1168
  apiToken,
990
1169
  stagingApiToken,
991
1170
  staging: staging || parsed.values.staging,
1171
+ readStoredTokens: storedTokenReader(credentials),
992
1172
  });
993
1173
  if (authentication === null) {
994
1174
  writeAuthenticationRequired(stderr);
@@ -1072,6 +1252,120 @@ async function runCompilationDownload({
1072
1252
  }
1073
1253
  }
1074
1254
 
1255
+ /**
1256
+ * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createRequestSignal" | "apiUrl" | "apiToken" | "stagingApiToken" | "staging" | "credentials">} options
1257
+ */
1258
+ async function runCompilationCancel({
1259
+ argv,
1260
+ stdout,
1261
+ stderr,
1262
+ cwd,
1263
+ fetchFunction,
1264
+ planPushFileSystem,
1265
+ createRequestSignal,
1266
+ apiUrl,
1267
+ apiToken,
1268
+ stagingApiToken,
1269
+ staging,
1270
+ credentials,
1271
+ }) {
1272
+ const parsed = parseArguments(() =>
1273
+ parseArgs({
1274
+ args: [...argv],
1275
+ options: {
1276
+ staging: { type: "boolean" },
1277
+ help: { type: "boolean", short: "h" },
1278
+ },
1279
+ allowPositionals: true,
1280
+ strict: true,
1281
+ tokens: true,
1282
+ }),
1283
+ );
1284
+
1285
+ if (!parsed || repeatedValueOption(parsed.tokens)) {
1286
+ writeCompilationInvalidArguments(
1287
+ stderr,
1288
+ COMPILATION_CANCEL_INVALID_ARGUMENTS_DETAIL,
1289
+ );
1290
+ return 2;
1291
+ }
1292
+
1293
+ if (parsed.values.help) {
1294
+ stdout.write(COMPILATION_CANCEL_HELP);
1295
+ return 0;
1296
+ }
1297
+
1298
+ const [compilationId] = parsed.positionals;
1299
+ if (parsed.positionals.length !== 1 || !isUuidV7(compilationId)) {
1300
+ writeCompilationInvalidArguments(
1301
+ stderr,
1302
+ COMPILATION_CANCEL_INVALID_ARGUMENTS_DETAIL,
1303
+ );
1304
+ return 2;
1305
+ }
1306
+
1307
+ try {
1308
+ const authentication = authenticateApiCommand({
1309
+ fetchFunction,
1310
+ apiUrl,
1311
+ apiToken,
1312
+ stagingApiToken,
1313
+ staging: staging || parsed.values.staging,
1314
+ readStoredTokens: storedTokenReader(credentials),
1315
+ });
1316
+ if (authentication === null) {
1317
+ writeAuthenticationRequired(stderr);
1318
+ return 1;
1319
+ }
1320
+ const result = await cancelCompilation({
1321
+ cwd,
1322
+ compilationId,
1323
+ fetchFunction: authentication.fetchFunction,
1324
+ fileSystem: planPushFileSystem,
1325
+ createRequestSignal,
1326
+ });
1327
+ writeJson(stdout, result);
1328
+ return 0;
1329
+ } catch (error) {
1330
+ if (error instanceof CompilationCancelRejectedError) {
1331
+ if (isAuthenticationProblem(error.status, error.response)) {
1332
+ writeAuthenticationRequired(stderr, error.status, error.response);
1333
+ return 1;
1334
+ }
1335
+ writeJson(stderr, {
1336
+ error: "compilation_cancel_rejected",
1337
+ detail: COMPILATION_CANCEL_REJECTED_DETAIL,
1338
+ status: error.status,
1339
+ response: error.response,
1340
+ });
1341
+ return 1;
1342
+ }
1343
+
1344
+ if (error instanceof CompilationCancelUnavailableError) {
1345
+ writeJson(stderr, {
1346
+ error: "compilation_cancel_unavailable",
1347
+ detail: COMPILATION_CANCEL_UNAVAILABLE_DETAIL,
1348
+ ...(typeof error.status === "number" ? { status: error.status } : {}),
1349
+ ...(error.response ? { response: error.response } : {}),
1350
+ });
1351
+ return 1;
1352
+ }
1353
+
1354
+ if (error instanceof CompilationStatusInvalidError) {
1355
+ writeJson(stderr, {
1356
+ error: "invalid_compilation_status",
1357
+ detail: COMPILATION_CANCEL_INVALID_DETAIL,
1358
+ status: error.status,
1359
+ });
1360
+ return 1;
1361
+ }
1362
+
1363
+ const status = writeCompilationReadError(stderr, error, false);
1364
+ if (status !== null) return status;
1365
+ throw error;
1366
+ }
1367
+ }
1368
+
1075
1369
  /** @param {Writer} writer @param {string} detail */
1076
1370
  function writeCompilationInvalidArguments(writer, detail) {
1077
1371
  writeJson(writer, { error: "invalid_arguments", detail });
@@ -1161,6 +1455,257 @@ function writeCompilationReadError(writer, error, throwUnknown = true) {
1161
1455
  return null;
1162
1456
  }
1163
1457
 
1458
+ /** @param {LoginCommandOptions} options */
1459
+ async function runLogin({
1460
+ argv,
1461
+ stdout,
1462
+ stderr,
1463
+ fetchFunction,
1464
+ createRequestSignal,
1465
+ credentials,
1466
+ hostname,
1467
+ loginSleep,
1468
+ loginNow,
1469
+ startLoopbackServer,
1470
+ apiUrl,
1471
+ apiToken,
1472
+ stagingApiToken,
1473
+ staging,
1474
+ }) {
1475
+ const parsed = parseArguments(() =>
1476
+ parseArgs({
1477
+ args: [...argv],
1478
+ options: {
1479
+ staging: { type: "boolean" },
1480
+ interactive: { type: "boolean", short: "i" },
1481
+ device: { type: "boolean" },
1482
+ help: { type: "boolean", short: "h" },
1483
+ },
1484
+ allowPositionals: false,
1485
+ strict: true,
1486
+ tokens: true,
1487
+ }),
1488
+ );
1489
+
1490
+ if (
1491
+ !parsed ||
1492
+ repeatedValueOption(parsed.tokens) ||
1493
+ (parsed.values.interactive && parsed.values.device)
1494
+ ) {
1495
+ writeJson(stderr, {
1496
+ error: "invalid_arguments",
1497
+ detail: LOGIN_INVALID_ARGUMENTS_DETAIL,
1498
+ });
1499
+ return 2;
1500
+ }
1501
+
1502
+ if (parsed.values.help) {
1503
+ stdout.write(LOGIN_HELP);
1504
+ return 0;
1505
+ }
1506
+
1507
+ const origin = selectLoginOrigin(stderr, {
1508
+ apiUrl,
1509
+ staging: staging || parsed.values.staging,
1510
+ });
1511
+ if (origin === null) return 2;
1512
+
1513
+ try {
1514
+ await login({
1515
+ origin,
1516
+ device: parsed.values.interactive || parsed.values.device,
1517
+ prompt: (text) => stderr.write(text),
1518
+ fetchFunction,
1519
+ createRequestSignal,
1520
+ sleep: loginSleep,
1521
+ now: loginNow,
1522
+ hostname,
1523
+ startLoopback: startLoopbackServer,
1524
+ credentials,
1525
+ });
1526
+ } catch (error) {
1527
+ if (error instanceof LoginDeniedError) {
1528
+ writeJson(stderr, {
1529
+ error: "authorization_denied",
1530
+ detail: LOGIN_DENIED_DETAIL,
1531
+ });
1532
+ return 1;
1533
+ }
1534
+
1535
+ if (error instanceof LoginExpiredError) {
1536
+ writeJson(stderr, {
1537
+ error: "authorization_expired",
1538
+ detail: LOGIN_EXPIRED_DETAIL,
1539
+ });
1540
+ return 1;
1541
+ }
1542
+
1543
+ if (error instanceof LoginFailedError) {
1544
+ writeJson(stderr, {
1545
+ error: "login_failed",
1546
+ detail:
1547
+ error.credentialsPath === undefined
1548
+ ? LOGIN_FAILED_DETAIL
1549
+ : error.phase === "write"
1550
+ ? `First Draft issued a token, but it could not be saved. Revoke the new token at ${origin}/api-tokens, then ${credentialsRecovery(error.reason)} and retry login.`
1551
+ : LOGIN_CREDENTIALS_DETAIL,
1552
+ ...(error.phase === undefined ? {} : { phase: error.phase }),
1553
+ ...(error.reason === undefined ? {} : { reason: error.reason }),
1554
+ ...(error.status === undefined ? {} : { status: error.status }),
1555
+ ...(error.credentialsPath === undefined
1556
+ ? {}
1557
+ : { credentials_path: error.credentialsPath }),
1558
+ });
1559
+ return 1;
1560
+ }
1561
+
1562
+ throw error;
1563
+ }
1564
+
1565
+ stdout.write(`Logged in to ${origin}\n`);
1566
+ writeEnvironmentTokenNote(stderr, origin, { apiToken, stagingApiToken });
1567
+ return 0;
1568
+ }
1569
+
1570
+ /** @param {LoginCommandOptions} options */
1571
+ async function runLogout({
1572
+ argv,
1573
+ stdout,
1574
+ stderr,
1575
+ fetchFunction,
1576
+ createRequestSignal,
1577
+ credentials,
1578
+ apiUrl,
1579
+ apiToken,
1580
+ stagingApiToken,
1581
+ staging,
1582
+ }) {
1583
+ const parsed = parseArguments(() =>
1584
+ parseArgs({
1585
+ args: [...argv],
1586
+ options: {
1587
+ staging: { type: "boolean" },
1588
+ help: { type: "boolean", short: "h" },
1589
+ },
1590
+ allowPositionals: false,
1591
+ strict: true,
1592
+ tokens: true,
1593
+ }),
1594
+ );
1595
+
1596
+ if (!parsed || repeatedValueOption(parsed.tokens)) {
1597
+ writeJson(stderr, {
1598
+ error: "invalid_arguments",
1599
+ detail: LOGOUT_INVALID_ARGUMENTS_DETAIL,
1600
+ });
1601
+ return 2;
1602
+ }
1603
+
1604
+ if (parsed.values.help) {
1605
+ stdout.write(LOGOUT_HELP);
1606
+ return 0;
1607
+ }
1608
+
1609
+ const origin = selectLoginOrigin(stderr, {
1610
+ apiUrl,
1611
+ staging: staging || parsed.values.staging,
1612
+ });
1613
+ if (origin === null) return 2;
1614
+
1615
+ let result;
1616
+ try {
1617
+ result = await logout({
1618
+ origin,
1619
+ fetchFunction,
1620
+ createRequestSignal,
1621
+ credentials,
1622
+ });
1623
+ } catch (error) {
1624
+ if (!(error instanceof LogoutFailedError)) throw error;
1625
+
1626
+ writeJson(stderr, {
1627
+ error: "logout_failed",
1628
+ detail:
1629
+ error.phase === "read"
1630
+ ? LOGOUT_FAILED_DETAIL
1631
+ : error.revoked
1632
+ ? `First Draft confirmed token revocation, but the local credential could not be removed. To remove it, ${credentialsRecovery(error.reason)} and retry logout.`
1633
+ : `First Draft did not confirm token revocation, and the local credential could not be removed. Revoke the token at ${origin}/api-tokens, then ${credentialsRecovery(error.reason)} and retry logout.`,
1634
+ phase: error.phase,
1635
+ ...(error.revoked === undefined ? {} : { revoked: error.revoked }),
1636
+ reason: error.reason,
1637
+ credentials_path: error.credentialsPath,
1638
+ });
1639
+ return 1;
1640
+ }
1641
+
1642
+ if (!result.stored) {
1643
+ stdout.write(`Not logged in to ${origin}; no saved token was found.\n`);
1644
+ } else {
1645
+ stdout.write(`Logged out of ${origin}\n`);
1646
+ if (result.changed) {
1647
+ stderr.write(
1648
+ `The saved token for ${origin} changed while logout was running, so the current saved token was left in place. Run 'firstdraft logout' again to remove it.\n`,
1649
+ );
1650
+ }
1651
+ if (!result.revoked) {
1652
+ stderr.write(
1653
+ `First Draft did not confirm that the token was revoked. The local copy was removed; revoke the token at ${new URL("/api-tokens", origin).href} if it may still be active.\n`,
1654
+ );
1655
+ }
1656
+ }
1657
+ writeEnvironmentTokenNote(stderr, origin, { apiToken, stagingApiToken });
1658
+ return 0;
1659
+ }
1660
+
1661
+ /**
1662
+ * The recovery step after a credentials update failed, phrased to follow
1663
+ * "then" in a detail message.
1664
+ *
1665
+ * @param {string | undefined} reason
1666
+ */
1667
+ function credentialsRecovery(reason) {
1668
+ return reason === "credentials_locked"
1669
+ ? CREDENTIALS_LOCKED_RECOVERY
1670
+ : "repair the credentials file";
1671
+ }
1672
+
1673
+ /**
1674
+ * @param {Writer} stderr
1675
+ * @param {{apiUrl?: string, staging?: boolean}} options
1676
+ * @returns {string | null}
1677
+ */
1678
+ function selectLoginOrigin(stderr, options) {
1679
+ try {
1680
+ return resolveLoginOrigin(options);
1681
+ } catch (error) {
1682
+ if (!(error instanceof PlanPushConfigurationError)) throw error;
1683
+
1684
+ writeJson(stderr, {
1685
+ error: "invalid_configuration",
1686
+ detail: error.message,
1687
+ });
1688
+ return null;
1689
+ }
1690
+ }
1691
+
1692
+ /**
1693
+ * @param {Writer} stderr
1694
+ * @param {string} origin
1695
+ * @param {{apiToken?: string, stagingApiToken?: string}} tokens
1696
+ */
1697
+ function writeEnvironmentTokenNote(stderr, origin, tokens) {
1698
+ if (environmentTokenFor(origin, tokens) === undefined) return;
1699
+
1700
+ const variable =
1701
+ origin === STAGING_API_URL
1702
+ ? "FIRSTDRAFT_STAGING_API_TOKEN"
1703
+ : "FIRSTDRAFT_API_TOKEN";
1704
+ stderr.write(
1705
+ `Note: ${variable} is set and takes precedence over the saved login for ${origin}.\n`,
1706
+ );
1707
+ }
1708
+
1164
1709
  /**
1165
1710
  * @param {GenerateCommandOptions} options
1166
1711
  */
@@ -1296,7 +1841,7 @@ function runGenerateApplicationKey({ argv, stdout, stderr }) {
1296
1841
  }
1297
1842
 
1298
1843
  /**
1299
- * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createTemporaryId" | "createRequestSignal" | "apiUrl" | "apiToken" | "stagingApiToken" | "staging">} options
1844
+ * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createTemporaryId" | "createRequestSignal" | "apiUrl" | "apiToken" | "stagingApiToken" | "staging" | "credentials">} options
1300
1845
  */
1301
1846
  async function runPlanPush({
1302
1847
  argv,
@@ -1311,6 +1856,7 @@ async function runPlanPush({
1311
1856
  apiToken,
1312
1857
  stagingApiToken,
1313
1858
  staging,
1859
+ credentials,
1314
1860
  }) {
1315
1861
  const parsed = parseArguments(() =>
1316
1862
  parseArgs({
@@ -1346,6 +1892,7 @@ async function runPlanPush({
1346
1892
  apiToken,
1347
1893
  stagingApiToken,
1348
1894
  staging: staging || parsed.values.staging,
1895
+ readStoredTokens: storedTokenReader(credentials),
1349
1896
  });
1350
1897
  if (authentication === null) {
1351
1898
  writeAuthenticationRequired(stderr);
@@ -1441,7 +1988,7 @@ async function runPlanPush({
1441
1988
  }
1442
1989
 
1443
1990
  /**
1444
- * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createRequestSignal" | "planStatusSleep" | "planStatusNow" | "apiUrl" | "apiToken" | "stagingApiToken" | "staging">} options
1991
+ * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createRequestSignal" | "planStatusSleep" | "planStatusNow" | "apiUrl" | "apiToken" | "stagingApiToken" | "staging" | "credentials">} options
1445
1992
  */
1446
1993
  async function runPlanStatus({
1447
1994
  argv,
@@ -1457,6 +2004,7 @@ async function runPlanStatus({
1457
2004
  apiToken,
1458
2005
  stagingApiToken,
1459
2006
  staging,
2007
+ credentials,
1460
2008
  }) {
1461
2009
  const parsed = parseArguments(() =>
1462
2010
  parseArgs({
@@ -1493,6 +2041,7 @@ async function runPlanStatus({
1493
2041
  apiToken,
1494
2042
  stagingApiToken,
1495
2043
  staging: staging || parsed.values.staging,
2044
+ readStoredTokens: storedTokenReader(credentials),
1496
2045
  });
1497
2046
  if (authentication === null) {
1498
2047
  writeAuthenticationRequired(stderr);
@@ -1605,7 +2154,7 @@ async function runPlanStatus({
1605
2154
  }
1606
2155
 
1607
2156
  /**
1608
- * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createTemporaryId" | "createRequestSignal" | "planCompileSleep" | "planCompileNow" | "planPublishSleep" | "planPublishNow" | "compilationSleep" | "compilationNow" | "planCompilePush" | "planCompileReadStatus" | "planCompilePublish" | "planCompileDownload" | "apiUrl" | "apiToken" | "stagingApiToken" | "staging">} options
2157
+ * @param {Pick<CommandOptions, "argv" | "stdout" | "stderr" | "cwd" | "fetchFunction" | "planPushFileSystem" | "createTemporaryId" | "createRequestSignal" | "planCompileSleep" | "planCompileNow" | "planPublishSleep" | "planPublishNow" | "compilationSleep" | "compilationNow" | "planCompilePush" | "planCompileReadStatus" | "planCompilePublish" | "planCompileDownload" | "apiUrl" | "apiToken" | "stagingApiToken" | "staging" | "credentials">} options
1609
2158
  */
1610
2159
  async function runPlanCompile({
1611
2160
  argv,
@@ -1630,6 +2179,7 @@ async function runPlanCompile({
1630
2179
  apiToken,
1631
2180
  stagingApiToken,
1632
2181
  staging,
2182
+ credentials,
1633
2183
  }) {
1634
2184
  const parsed = parseArguments(() =>
1635
2185
  parseArgs({
@@ -1676,6 +2226,7 @@ async function runPlanCompile({
1676
2226
  apiToken,
1677
2227
  stagingApiToken,
1678
2228
  staging: staging || parsed.values.staging,
2229
+ readStoredTokens: storedTokenReader(credentials),
1679
2230
  });
1680
2231
  if (authentication === null) {
1681
2232
  writeAuthenticationRequired(stderr);