@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/docs/errors.md CHANGED
@@ -7,7 +7,8 @@ This page owns handled-error interpretation, retry safety, and recovery guidance
7
7
 
8
8
  Every handled subcommand failure ends with exactly one JSON object on standard error. `plan compile` may first write
9
9
  progress lines; machine consumers can remove only lines beginning with the exact `First Draft: ` prefix and parse the
10
- remaining JSON document. Branch on the stable `error` value rather than the human-readable `detail`.
10
+ remaining JSON document. `login` may first write its human-readable authorization instructions; its JSON object
11
+ starts on the line after them. Branch on the stable `error` value rather than the human-readable `detail`.
11
12
 
12
13
  Handled output never includes command arguments, local Plan bytes, raw artifact bytes, raw filesystem or network
13
14
  errors, or unvalidated response bodies. `local_state_not_saved` is the sole exception to private-state redaction:
@@ -19,12 +20,44 @@ remain human-readable text on standard error with exit 2. Unexpected programming
19
20
  `invalid_configuration` stops before a request when `--staging` conflicts with `FIRSTDRAFT_API_URL` or a Project's
20
21
  saved origin. Push and Compile also reject any URL override that differs from that pin. Unset the conflicting
21
22
  override or use a separate initialized project directory for the other environment; do not redirect existing
22
- private Project state. Status and retained download commands continue using their pin.
23
-
24
- `authentication_required` means the selected environment's token is missing or rejected. Staging requires
25
- `FIRSTDRAFT_STAGING_API_TOKEN`, including old staging Projects with no flag. Production and custom origins require
26
- `FIRSTDRAFT_API_TOKEN`. The CLI never substitutes one for the other. Obtain or refresh the credential from the
27
- same environment, then follow the command's recovery instructions below.
23
+ private Project state. Status, retained download, and cancel commands continue using their pin.
24
+
25
+ `authentication_required` means the selected environment's token is missing or rejected with `401`. Staging uses
26
+ `FIRSTDRAFT_STAGING_API_TOKEN`, including old staging Projects with no flag. Production and custom origins use
27
+ `FIRSTDRAFT_API_TOKEN`. When that variable is unset, the token saved by `firstdraft login` for the exact origin is
28
+ used. The CLI never substitutes one environment's credential for another's. Run `firstdraft login` for the same
29
+ environment (with `--staging` or the same `FIRSTDRAFT_API_URL`), or refresh the environment token, then follow the
30
+ command's recovery instructions below. If a saved login is rejected, run `firstdraft login` again.
31
+
32
+ ## Login and logout errors
33
+
34
+ `login` and `logout` never print a token. A local credential failure can occur after the server has issued or revoked a token.
35
+
36
+ - `authorization_denied`: the approval was denied in the browser. Run `firstdraft login` again to retry.
37
+ - `authorization_expired`: no loopback callback arrived within five minutes, or the device code expired before
38
+ approval. Run `firstdraft login` again. Use `--interactive` if no browser on this machine can reach the printed URL.
39
+ - `login_failed`: the login could not be completed. `reason`, when present, is the server's OAuth error code (for
40
+ example `invalid_grant` for a used, expired, or mismatched code), `loopback_unavailable` when the local listener
41
+ could not start, `credentials_invalid` / `credentials_unavailable` when the credentials file could not be read or
42
+ written, or `credentials_locked` when another command held its lock for 10 seconds. `status` is the HTTP status
43
+ when one was received. Credentials failures include `credentials_path` and `phase`. With `phase: "read"`, no
44
+ request was made; repair or remove the file and retry. With `phase: "write"`, First Draft issued a token but the
45
+ CLI could not save it. Revoke that new token on the selected origin's `/api-tokens` page, then repair the
46
+ credentials file and retry login. Any previously saved token remains unchanged when the replacement fails.
47
+ - `logout_failed`: the credentials file could not be read or updated. It carries `reason`, `credentials_path`,
48
+ and `phase`. With `phase: "read"`, no token was revoked or removed; repair or remove the file and retry. With
49
+ `phase: "write"`, local removal failed after the revocation attempt. `revoked: true` means First Draft confirmed
50
+ revocation; repair the file and retry logout to remove the stale entry. `revoked: false` means revocation was not
51
+ confirmed, so the token may still be active; revoke it on the selected origin's `/api-tokens` page, then repair
52
+ the file and retry logout. Preserve entries for other origins when repairing the file.
53
+ - With reason `credentials_locked`, from either command: wait for any other `firstdraft` command to finish and
54
+ retry. If none is running, the lock was left by a command that exited mid-update; delete `credentials.json.lock`
55
+ next to `credentials_path` instead of repairing the file, and retry. The CLI never removes the lock itself,
56
+ because it cannot tell an abandoned lock from one another command has just taken.
57
+
58
+ `invalid_configuration` from `login` or `logout` means `--staging` conflicts with `FIRSTDRAFT_API_URL`, or the URL is
59
+ invalid. A logout whose server revocation is not confirmed still succeeds after removing the local entry. It
60
+ writes a note on standard error; revoke the token on `/api-tokens` if it may still be active.
28
61
 
29
62
  ## Ambiguous mutations
30
63
 
@@ -97,10 +130,37 @@ operation is safe to remove. After successful adoption, run retained status and
97
130
 
98
131
  After `compilation_wait_timed_out`, retained work may still continue. Use
99
132
  `firstdraft compilation status <current.compilation.id>` for one read-only status check; do not rerun
100
- `plan compile`. `compilation_failed`, `compilation_cancelled`, and `compilation_changed` already carry the
133
+ `plan compile`. If it stays `queued` or `running`, follow [stuck Compilation recovery](#stuck-compilation-recovery).
134
+ `compilation_failed`, `compilation_cancelled`, and `compilation_changed` already carry the
101
135
  validated `current` projection appropriate to their stopping boundary. Authentication recovery may refresh the
102
136
  credential, but it must continue from the retained ID rather than starting another Compilation.
103
137
 
138
+ ## Stuck Compilation recovery
139
+
140
+ A Project allows one active Compilation. While one is queued or running, `plan push` and `plan compile` report
141
+ `server_rejected` with First Draft's `409 compilation_active` problem in `response`, because the Plan cannot be
142
+ replaced. `plan compile` can also meet it at the Compilation start, as `compilation_start_rejected`. Either problem's
143
+ `response.detail` names the active Compilation's ID.
144
+
145
+ 1. Read that Compilation once with `firstdraft compilation status <id>`. One that has reached `succeeded`, `failed`,
146
+ or `cancelled` no longer blocks; rerun `plan compile`.
147
+ 2. If it is still `queued` or `running` well after a Compilation normally finishes, for example after a
148
+ `plan compile` wait timed out, cancel it with `firstdraft compilation cancel <id>`. Cancelling throws away any
149
+ work it is still doing.
150
+ 3. After the cancel succeeds, rerun `plan compile`.
151
+
152
+ Cancel never changes a succeeded or failed Compilation, and repeating it is safe:
153
+
154
+ - `compilation_cancel_rejected` means First Draft refused and nothing was cancelled; `response.code` says why.
155
+ `409 compilation_not_cancellable` means the Compilation already succeeded or failed, so it no longer blocks; check
156
+ it with `compilation status`. `404 compilation_not_found` or `404 project_not_found` means First Draft found no
157
+ such Compilation for this Project and account. Check the ID, the directory, and that the environment and login
158
+ match the ones that started it.
159
+ - `compilation_cancel_unavailable` means a network failure, timeout, or server error left the outcome unconfirmed.
160
+ Rerun `compilation cancel`, or check the result with `compilation status`.
161
+ - `invalid_compilation_status` means the response violated the Compilation contract, so the cancellation may or may
162
+ not have happened. Check with `compilation status` rather than repeating the unchanged request.
163
+
104
164
  ## Publication recovery
105
165
 
106
166
  The Publication is a Project singleton. If its initial conditional `PUT` is ambiguous, the CLI attempts one
@@ -123,7 +183,10 @@ stopped without following the replacement.
123
183
  | Any leaf command | `invalid_arguments` | 2 | Syntax was invalid; no request was made. |
124
184
  | `plan init` | `local_initialization_failed` | 1 | Initialization failed without overwriting an existing path. |
125
185
  | Network commands | `invalid_configuration` | 2 | API origin or saved Head state is incompatible. |
126
- | Network commands | `authentication_required` | 1 | The token is missing or First Draft returned a validated authentication problem. |
186
+ | `login` | `authorization_denied`, `authorization_expired` | 1 | The approval was denied, or not granted before the callback wait or device code expired. |
187
+ | `login` | `login_failed` | 1 | Nothing was saved; `phase: "write"` means a token was issued ([recovery](#login-and-logout-errors)). |
188
+ | `logout` | `logout_failed` | 1 | Check `phase` and `revoked`; revocation may have happened ([recovery](#login-and-logout-errors)). |
189
+ | Network commands | `authentication_required` | 1 | No environment or saved token exists for the origin, or First Draft rejected it. |
127
190
  | Plan commands, `compilation *` | `local_input_unreadable` | 1 | Required local Plan or private state could not be read. |
128
191
  | Status, Compile, Compilation commands | `project_not_pushed` | 1 | No API origin is pinned for the local Project. |
129
192
  | `plan push`, `plan compile` | `request_outcome_unknown` | 1 | A mutation or its response could not be verified; `plan compile` identifies its mutation phase. |
@@ -142,6 +205,9 @@ stopped without following the replacement.
142
205
  | `compilation status`, `compilation download` | `compilation_status_unavailable`, `invalid_compilation_status` | 1 | The retained status could not be read or violated its exact contract. |
143
206
  | `compilation status --wait` | `compilation_changed`, `compilation_wait_timed_out` | 1 | Retained identity/provenance changed or the wait ended. |
144
207
  | `compilation download` | `compilation_not_succeeded` | 1 | Status was not `succeeded`; no artifact request was made. |
208
+ | `compilation cancel` | `compilation_cancel_rejected` | 1 | Nothing was cancelled; `response.code` says why ([recovery](#stuck-compilation-recovery)). |
209
+ | `compilation cancel` | `compilation_cancel_unavailable` | 1 | The cancellation could not be confirmed; repeating it is safe. |
210
+ | `compilation cancel` | `invalid_compilation_status` | 1 | The response violated the Compilation contract; check status before repeating. |
145
211
  | Download commands | `artifact_unavailable`, `invalid_artifact` | 1 | Artifact transport or integrity validation failed; direct Compile post-start errors include `current`. |
146
212
  | Download commands | `invalid_output_path` | 2 | The absent destination or root-adoption preconditions failed; `reason` identifies the stable refusal. |
147
213
  | Download commands | `materialization_failed` | 1 | The output changed or its transaction failed; `reason` identifies incomplete rollback when applicable. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@firstdraft.com/cli",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "description": "Command-line interface for First Draft",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -9,9 +9,10 @@
9
9
  },
10
10
  "files": [
11
11
  "bin",
12
- "docs",
12
+ "docs/README.md",
13
+ "docs/commands.md",
14
+ "docs/errors.md",
13
15
  "src",
14
- "RELEASING.md",
15
16
  "SECURITY.md"
16
17
  ],
17
18
  "engines": {
@@ -39,7 +40,8 @@
39
40
  "pack:check": "node scripts/check-pack.js",
40
41
  "pack:smoke": "node scripts/smoke-package.js",
41
42
  "test": "node scripts/run-tests.js",
42
- "typecheck": "tsc --project jsconfig.json"
43
+ "typecheck": "tsc --project jsconfig.json",
44
+ "version": "node scripts/sync-version.js --apply"
43
45
  },
44
46
  "devDependencies": {
45
47
  "@eslint/js": "10.0.1",
@@ -4,6 +4,37 @@ export const STAGING_API_URL = "https://staging.firstdraft.com";
4
4
 
5
5
  export class ApiAuthenticationRequiredError extends Error {}
6
6
 
7
+ /**
8
+ * Rejects `--staging` together with a FIRSTDRAFT_API_URL that names another
9
+ * origin.
10
+ *
11
+ * @param {string | undefined} apiUrl
12
+ * @param {boolean} staging
13
+ */
14
+ export function assertStagingSelection(apiUrl, staging) {
15
+ if (
16
+ staging &&
17
+ apiUrl !== undefined &&
18
+ normalizeApiUrl(apiUrl) !== STAGING_API_URL
19
+ ) {
20
+ throw new PlanStateConfigurationError(
21
+ "--staging conflicts with FIRSTDRAFT_API_URL. Unset it or select the staging origin.",
22
+ );
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Selects the environment token for an origin: staging uses its own variable,
28
+ * production and custom origins share FIRSTDRAFT_API_TOKEN.
29
+ *
30
+ * @param {string} origin
31
+ * @param {{apiToken?: string, stagingApiToken?: string}} tokens
32
+ */
33
+ export function environmentTokenFor(origin, { apiToken, stagingApiToken }) {
34
+ const token = origin === STAGING_API_URL ? stagingApiToken : apiToken;
35
+ return hasToken(token) ? token : undefined;
36
+ }
37
+
7
38
  /**
8
39
  * @param {object} options
9
40
  * @param {typeof globalThis.fetch} [options.fetchFunction]
@@ -11,6 +42,9 @@ export class ApiAuthenticationRequiredError extends Error {}
11
42
  * @param {string} [options.stagingApiToken]
12
43
  * @param {string} [options.apiUrl]
13
44
  * @param {boolean} [options.staging]
45
+ * @param {() => Readonly<Record<string, string>>} [options.readStoredTokens]
46
+ * Stored `firstdraft login` tokens keyed by exact origin. Consulted only when
47
+ * the environment has no token for the requested origin.
14
48
  */
15
49
  export function authenticateApiCommand({
16
50
  fetchFunction,
@@ -18,19 +52,17 @@ export function authenticateApiCommand({
18
52
  stagingApiToken,
19
53
  apiUrl,
20
54
  staging = false,
55
+ readStoredTokens = () => ({}),
21
56
  }) {
22
- if (
23
- staging &&
24
- apiUrl !== undefined &&
25
- normalizeApiUrl(apiUrl) !== STAGING_API_URL
26
- ) {
27
- throw new PlanStateConfigurationError(
28
- "--staging conflicts with FIRSTDRAFT_API_URL. Unset it or select the staging origin.",
29
- );
30
- }
57
+ assertStagingSelection(apiUrl, staging);
31
58
 
32
59
  const configured = staging ? STAGING_API_URL : apiUrl;
33
- if (!hasToken(apiToken) && !hasToken(stagingApiToken)) return null;
60
+ if (
61
+ !hasToken(apiToken) &&
62
+ !hasToken(stagingApiToken) &&
63
+ !Object.values(readStoredTokens()).some(hasToken)
64
+ )
65
+ return null;
34
66
 
35
67
  let selectedOrigin = staging ? STAGING_API_URL : undefined;
36
68
  const request = fetchFunction ?? globalThis.fetch;
@@ -43,8 +75,9 @@ export function authenticateApiCommand({
43
75
  );
44
76
  }
45
77
  const token =
46
- endpoint.origin === STAGING_API_URL ? stagingApiToken : apiToken;
47
- if (!hasToken(token)) throw new ApiAuthenticationRequiredError();
78
+ environmentTokenFor(endpoint.origin, { apiToken, stagingApiToken }) ??
79
+ storedToken(readStoredTokens(), endpoint.origin);
80
+ if (token === undefined) throw new ApiAuthenticationRequiredError();
48
81
  selectedOrigin = endpoint.origin;
49
82
  return request(input, {
50
83
  ...init,
@@ -57,7 +90,16 @@ export function authenticateApiCommand({
57
90
  return { apiUrl: configured, fetchFunction: authorizedFetch };
58
91
  }
59
92
 
60
- /** @param {string | undefined} token */
93
+ /** @param {Readonly<Record<string, string>>} tokens @param {string} origin */
94
+ function storedToken(tokens, origin) {
95
+ const token = Object.hasOwn(tokens, origin) ? tokens[origin] : undefined;
96
+ return hasToken(token) ? token : undefined;
97
+ }
98
+
99
+ /**
100
+ * @param {string | undefined} token
101
+ * @returns {token is string}
102
+ */
61
103
  function hasToken(token) {
62
104
  return token !== undefined && token.trim().length > 0;
63
105
  }
@@ -22,14 +22,88 @@ export class FirstDraftProtocolError extends Error {
22
22
  }
23
23
  }
24
24
 
25
+ /**
26
+ * Every Service API route the CLI requests. docs/commands.md#service-endpoints
27
+ * has one row for each, and test/service-endpoints.test.js compares the two.
28
+ */
29
+ export const SERVICE_ROUTES = {
30
+ pushPlan: {
31
+ method: "PUT",
32
+ path: "/v1/projects/{project_id}/foundation-plan",
33
+ },
34
+ readAnalysis: {
35
+ method: "GET",
36
+ path: "/v1/projects/{project_id}/analysis",
37
+ },
38
+ startCompilation: {
39
+ method: "POST",
40
+ path: "/v1/projects/{project_id}/compilations",
41
+ },
42
+ readCompilation: {
43
+ method: "GET",
44
+ path: "/v1/projects/{project_id}/compilations/{compilation_id}",
45
+ },
46
+ cancelCompilation: {
47
+ method: "POST",
48
+ path: "/v1/projects/{project_id}/compilations/{compilation_id}/cancel",
49
+ },
50
+ downloadArtifact: {
51
+ method: "GET",
52
+ path: "/v1/projects/{project_id}/compilations/{compilation_id}/artifact",
53
+ },
54
+ startPublication: {
55
+ method: "PUT",
56
+ path: "/v1/projects/{project_id}/github-publication",
57
+ },
58
+ readPublication: {
59
+ method: "GET",
60
+ path: "/v1/projects/{project_id}/github-publication",
61
+ },
62
+ requestOAuthToken: {
63
+ method: "POST",
64
+ path: "/oauth/token",
65
+ },
66
+ requestDeviceAuthorization: {
67
+ method: "POST",
68
+ path: "/oauth/device_authorization",
69
+ },
70
+ revokeOAuthToken: {
71
+ method: "POST",
72
+ path: "/oauth/revoke",
73
+ },
74
+ };
75
+
76
+ /** @typedef {{method: string, url: URL}} ServiceEndpoint */
77
+
78
+ /**
79
+ * @param {{method: string, path: string}} route
80
+ * @param {string} apiUrl
81
+ * @param {Record<string, string>} parameters
82
+ * @returns {ServiceEndpoint}
83
+ */
84
+ export function serviceEndpoint(route, apiUrl, parameters) {
85
+ const endpointPath = route.path.replace(/\{(\w+)\}/g, (_, name) => {
86
+ const value = parameters[name];
87
+ if (value === undefined) {
88
+ throw new Error(`${route.path} needs a ${name} value.`);
89
+ }
90
+ return value;
91
+ });
92
+
93
+ return { method: route.method, url: new URL(endpointPath, apiUrl) };
94
+ }
95
+
25
96
  /**
26
97
  * @param {typeof globalThis.fetch} fetchFunction
27
- * @param {URL} endpoint
28
- * @param {RequestInit} request
98
+ * @param {ServiceEndpoint} endpoint
99
+ * @param {Omit<RequestInit, "method">} request
29
100
  */
30
101
  export async function sendRequest(fetchFunction, endpoint, request) {
31
102
  try {
32
- return await fetchFunction(endpoint, request);
103
+ return await fetchFunction(endpoint.url, {
104
+ ...request,
105
+ method: endpoint.method,
106
+ });
33
107
  } catch (error) {
34
108
  if (
35
109
  error instanceof PlanStateConfigurationError ||