@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.
@@ -6,10 +6,12 @@ import { isAuthenticationProblem } from "../api-authentication.js";
6
6
  import {
7
7
  FirstDraftNetworkError,
8
8
  FirstDraftProtocolError,
9
+ SERVICE_ROUTES,
9
10
  isProblemBody,
10
11
  readResponseBody,
11
12
  responseMediaType,
12
13
  sendRequest,
14
+ serviceEndpoint,
13
15
  } from "../api-response.js";
14
16
  import { isUuidV7, readLocalFile, readPlanState } from "../plan-state.js";
15
17
 
@@ -284,10 +286,7 @@ export async function publishPlan({
284
286
  );
285
287
  }
286
288
 
287
- const endpoint = new URL(
288
- `/v1/projects/${state.project_id}/github-publication`,
289
- state.api_url,
290
- );
289
+ const apiUrl = state.api_url;
291
290
  const deadline = now() + WAIT_TIMEOUT_MS;
292
291
  let initial;
293
292
 
@@ -295,7 +294,7 @@ export async function publishPlan({
295
294
 
296
295
  try {
297
296
  initial = await startPublication({
298
- endpoint,
297
+ apiUrl,
299
298
  projectId: state.project_id,
300
299
  headSourceSha256,
301
300
  etag: publicationEtag,
@@ -307,7 +306,7 @@ export async function publishPlan({
307
306
 
308
307
  try {
309
308
  initial = await readPublicationStatus({
310
- endpoint,
309
+ apiUrl,
311
310
  projectId: state.project_id,
312
311
  headSourceSha256,
313
312
  fetchFunction,
@@ -359,7 +358,7 @@ export async function publishPlan({
359
358
  if (now() >= deadline) throw new PublicationTimeoutError(current);
360
359
 
361
360
  const next = await readPublicationStatus({
362
- endpoint,
361
+ apiUrl,
363
362
  projectId: state.project_id,
364
363
  headSourceSha256,
365
364
  fetchFunction,
@@ -391,7 +390,7 @@ export async function publishPlan({
391
390
 
392
391
  /**
393
392
  * @param {object} options
394
- * @param {URL} options.endpoint
393
+ * @param {string} options.apiUrl
395
394
  * @param {string} options.projectId
396
395
  * @param {string} options.headSourceSha256
397
396
  * @param {string} options.etag
@@ -399,18 +398,20 @@ export async function publishPlan({
399
398
  * @param {(timeoutMs: number) => AbortSignal} options.createRequestSignal
400
399
  */
401
400
  async function startPublication({
402
- endpoint,
401
+ apiUrl,
403
402
  projectId,
404
403
  headSourceSha256,
405
404
  etag,
406
405
  fetchFunction,
407
406
  createRequestSignal,
408
407
  }) {
408
+ const endpoint = serviceEndpoint(SERVICE_ROUTES.startPublication, apiUrl, {
409
+ project_id: projectId,
410
+ });
409
411
  let response;
410
412
  let body;
411
413
  try {
412
414
  response = await sendRequest(fetchFunction, endpoint, {
413
- method: "PUT",
414
415
  headers: {
415
416
  Accept: "application/json, application/problem+json",
416
417
  "If-Match": etag,
@@ -452,7 +453,7 @@ async function startPublication({
452
453
 
453
454
  /**
454
455
  * @param {object} options
455
- * @param {URL} options.endpoint
456
+ * @param {string} options.apiUrl
456
457
  * @param {string} options.projectId
457
458
  * @param {string} options.headSourceSha256
458
459
  * @param {typeof globalThis.fetch} options.fetchFunction
@@ -460,18 +461,20 @@ async function startPublication({
460
461
  * @param {number} options.requestTimeout
461
462
  */
462
463
  async function readPublicationStatus({
463
- endpoint,
464
+ apiUrl,
464
465
  projectId,
465
466
  headSourceSha256,
466
467
  fetchFunction,
467
468
  createRequestSignal,
468
469
  requestTimeout,
469
470
  }) {
471
+ const endpoint = serviceEndpoint(SERVICE_ROUTES.readPublication, apiUrl, {
472
+ project_id: projectId,
473
+ });
470
474
  let response;
471
475
  let body;
472
476
  try {
473
477
  response = await sendRequest(fetchFunction, endpoint, {
474
- method: "GET",
475
478
  headers: { Accept: "application/json, application/problem+json" },
476
479
  redirect: "error",
477
480
  signal: createRequestSignal(requestTimeout),
@@ -4,11 +4,13 @@ import path from "node:path";
4
4
 
5
5
  import {
6
6
  FirstDraftProtocolError,
7
+ SERVICE_ROUTES,
7
8
  isDiagnostic,
8
9
  isProblemBody,
9
10
  readResponseBody,
10
11
  responseMediaType,
11
12
  sendRequest,
13
+ serviceEndpoint,
12
14
  } from "../api-response.js";
13
15
  import { isFileSystemError } from "../file-system.js";
14
16
  import {
@@ -109,10 +111,9 @@ export async function pushPlan({
109
111
  const statePath = path.join(directory, "state.json");
110
112
  const planSource = readLocalFile(planPath, MAX_PLAN_BYTES, fileSystem);
111
113
  const origin = resolveApiUrl(apiUrl, state.api_url);
112
- const endpoint = new URL(
113
- `/v1/projects/${state.project_id}/foundation-plan`,
114
- origin,
115
- );
114
+ const endpoint = serviceEndpoint(SERVICE_ROUTES.pushPlan, origin, {
115
+ project_id: state.project_id,
116
+ });
116
117
  const headers = {
117
118
  Accept: "application/json, application/problem+json",
118
119
  "Content-Type": FOUNDATION_PLAN_MEDIA_TYPE,
@@ -122,7 +123,6 @@ export async function pushPlan({
122
123
  };
123
124
 
124
125
  const response = await sendRequest(fetchFunction, endpoint, {
125
- method: "PUT",
126
126
  headers,
127
127
  body: planSource,
128
128
  redirect: "error",
@@ -4,10 +4,12 @@ import { lstatSync, readFileSync } from "node:fs";
4
4
  import {
5
5
  FirstDraftNetworkError,
6
6
  FirstDraftProtocolError,
7
+ SERVICE_ROUTES,
7
8
  isProblemBody,
8
9
  readResponseBody,
9
10
  responseMediaType,
10
11
  sendRequest,
12
+ serviceEndpoint,
11
13
  } from "../api-response.js";
12
14
  import { isUuidV7, readPlanState } from "../plan-state.js";
13
15
 
@@ -166,10 +168,9 @@ export async function readPlanStatus({
166
168
  );
167
169
  }
168
170
 
169
- const endpoint = new URL(
170
- `/v1/projects/${state.project_id}/analysis`,
171
- state.api_url,
172
- );
171
+ const endpoint = serviceEndpoint(SERVICE_ROUTES.readAnalysis, state.api_url, {
172
+ project_id: state.project_id,
173
+ });
173
174
  const deadline = wait ? now() + WAIT_TIMEOUT_MS : null;
174
175
  /** @type {AnalysisResponse | null} */
175
176
  let first = null;
@@ -189,7 +190,6 @@ export async function readPlanStatus({
189
190
  let body;
190
191
  try {
191
192
  response = await sendRequest(fetchFunction, endpoint, {
192
- method: "GET",
193
193
  headers: { Accept: "application/json, application/problem+json" },
194
194
  redirect: "error",
195
195
  signal: createRequestSignal(requestTimeout),
@@ -0,0 +1,343 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import {
3
+ mkdirSync,
4
+ readFileSync,
5
+ renameSync,
6
+ rmSync,
7
+ statSync,
8
+ writeFileSync,
9
+ } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import path from "node:path";
12
+
13
+ import { isFileSystemError } from "./file-system.js";
14
+
15
+ export const CREDENTIALS_FORMAT = "firstdraft.cli-credentials/1";
16
+ const MAX_CREDENTIALS_BYTES = 256 * 1024;
17
+ const LOCK_TIMEOUT_MS = 10_000;
18
+ const LOCK_RETRY_MS = 25;
19
+
20
+ /**
21
+ * @typedef {object} CredentialsFileSystem
22
+ * @property {typeof mkdirSync} mkdirSync
23
+ * @property {typeof readFileSync} readFileSync
24
+ * @property {typeof renameSync} renameSync
25
+ * @property {typeof rmSync} rmSync
26
+ * @property {typeof statSync} statSync
27
+ * @property {typeof writeFileSync} writeFileSync
28
+ */
29
+
30
+ /**
31
+ * Where and how the CLI stores login credentials. Every member is injectable so
32
+ * tests never touch the real configuration directory.
33
+ *
34
+ * @typedef {object} CredentialStore
35
+ * @property {Readonly<Record<string, string | undefined>>} [env]
36
+ * @property {() => string} [homedir]
37
+ * @property {CredentialsFileSystem} [fileSystem]
38
+ * @property {() => string} [createTemporaryId]
39
+ * @property {number} [lockTimeoutMs] how long an update waits for another
40
+ * process's lock before failing
41
+ */
42
+
43
+ /**
44
+ * @typedef {object} CredentialEntry
45
+ * @property {string} access_token
46
+ * @property {string} token_type
47
+ * @property {string} created_at
48
+ */
49
+
50
+ /**
51
+ * @typedef {object} Credentials
52
+ * @property {typeof CREDENTIALS_FORMAT} format
53
+ * @property {Record<string, CredentialEntry>} origins
54
+ */
55
+
56
+ /** @type {CredentialsFileSystem} */
57
+ const DEFAULT_FILE_SYSTEM = {
58
+ mkdirSync,
59
+ readFileSync,
60
+ renameSync,
61
+ rmSync,
62
+ statSync,
63
+ writeFileSync,
64
+ };
65
+
66
+ export class CredentialsInvalidError extends Error {}
67
+
68
+ /**
69
+ * The credentials lock stayed held for the whole wait: another command is
70
+ * updating the file, or one exited while holding the lock. The lock is never
71
+ * removed automatically, because no file-system check can tell an abandoned
72
+ * lock from one another command has just taken. Its `code` lets callers treat
73
+ * it like any other unavailable credentials file.
74
+ */
75
+ export class CredentialsLockedError extends Error {
76
+ code = "ELOCKED";
77
+ }
78
+
79
+ /**
80
+ * `$XDG_CONFIG_HOME/firstdraft/credentials.json`, falling back to
81
+ * `~/.config/firstdraft/credentials.json`. A relative XDG_CONFIG_HOME is
82
+ * ignored, as the XDG Base Directory specification requires.
83
+ *
84
+ * @param {CredentialStore} [store]
85
+ */
86
+ export function credentialsPath(store = {}) {
87
+ const env = store.env ?? process.env;
88
+ const configHome = env.XDG_CONFIG_HOME;
89
+ const base =
90
+ configHome !== undefined && path.isAbsolute(configHome)
91
+ ? configHome
92
+ : path.join((store.homedir ?? homedir)(), ".config");
93
+ return path.join(base, "firstdraft", "credentials.json");
94
+ }
95
+
96
+ /**
97
+ * Reads the credentials file. A missing file is an empty store; an unreadable
98
+ * or malformed file throws.
99
+ *
100
+ * @param {CredentialStore} [store]
101
+ * @returns {Credentials}
102
+ */
103
+ export function readCredentials(store = {}) {
104
+ const fileSystem = store.fileSystem ?? DEFAULT_FILE_SYSTEM;
105
+ let source;
106
+ try {
107
+ source = fileSystem.readFileSync(credentialsPath(store));
108
+ } catch (error) {
109
+ if (isMissingFileError(error)) return emptyCredentials();
110
+ throw error;
111
+ }
112
+
113
+ if (source.byteLength > MAX_CREDENTIALS_BYTES) {
114
+ throw new CredentialsInvalidError("The credentials file is too large.");
115
+ }
116
+
117
+ let parsed;
118
+ try {
119
+ parsed = JSON.parse(
120
+ new TextDecoder("utf-8", { fatal: true }).decode(source),
121
+ );
122
+ } catch (error) {
123
+ if (!(error instanceof SyntaxError) && !(error instanceof TypeError))
124
+ throw error;
125
+ throw new CredentialsInvalidError("The credentials file is invalid.");
126
+ }
127
+
128
+ if (
129
+ !isRecord(parsed) ||
130
+ parsed.format !== CREDENTIALS_FORMAT ||
131
+ !isRecord(parsed.origins)
132
+ ) {
133
+ throw new CredentialsInvalidError("The credentials file is invalid.");
134
+ }
135
+
136
+ const origins = emptyOrigins();
137
+ for (const [origin, entry] of Object.entries(parsed.origins)) {
138
+ if (!isCredentialEntry(entry)) {
139
+ throw new CredentialsInvalidError("The credentials file is invalid.");
140
+ }
141
+ origins[origin] = {
142
+ access_token: entry.access_token,
143
+ token_type: entry.token_type,
144
+ created_at: entry.created_at,
145
+ };
146
+ }
147
+ return { format: CREDENTIALS_FORMAT, origins };
148
+ }
149
+
150
+ /**
151
+ * Stores (or replaces) the credential for one origin, keeping the others.
152
+ *
153
+ * @param {CredentialStore} store
154
+ * @param {string} origin
155
+ * @param {CredentialEntry} entry
156
+ */
157
+ export function writeCredential(store, origin, entry) {
158
+ withStoreLock(store, () => {
159
+ const credentials = readCredentials(store);
160
+ credentials.origins[origin] = entry;
161
+ saveCredentials(store, credentials);
162
+ });
163
+ }
164
+
165
+ /**
166
+ * Removes the credential for one origin. With `accessToken`, removes it only
167
+ * while it still holds that token, so a newer login saved in the meantime is
168
+ * kept.
169
+ *
170
+ * @param {CredentialStore} store
171
+ * @param {string} origin
172
+ * @param {{accessToken?: string}} [options]
173
+ * @returns {boolean} whether an entry was removed
174
+ */
175
+ export function deleteCredential(store, origin, { accessToken } = {}) {
176
+ if (!Object.hasOwn(readCredentials(store).origins, origin)) return false;
177
+
178
+ return withStoreLock(store, () => {
179
+ const credentials = readCredentials(store);
180
+ const entry = credentials.origins[origin];
181
+ if (
182
+ entry === undefined ||
183
+ (accessToken !== undefined && entry.access_token !== accessToken)
184
+ )
185
+ return false;
186
+ delete credentials.origins[origin];
187
+ saveCredentials(store, credentials);
188
+ return true;
189
+ });
190
+ }
191
+
192
+ /**
193
+ * Returns a memoized, never-throwing reader of stored access tokens keyed by
194
+ * origin. An unreadable or malformed file reads as empty.
195
+ *
196
+ * @param {CredentialStore} [store]
197
+ * @returns {() => Readonly<Record<string, string>>}
198
+ */
199
+ export function storedTokenReader(store = {}) {
200
+ /** @type {Record<string, string> | undefined} */
201
+ let tokens;
202
+ return () => {
203
+ if (tokens !== undefined) return tokens;
204
+ /** @type {Record<string, string>} */
205
+ const loaded = Object.create(null);
206
+ try {
207
+ for (const [origin, entry] of Object.entries(
208
+ readCredentials(store).origins,
209
+ )) {
210
+ loaded[origin] = entry.access_token;
211
+ }
212
+ } catch (error) {
213
+ if (
214
+ !(error instanceof CredentialsInvalidError) &&
215
+ !isFileSystemError(error)
216
+ )
217
+ throw error;
218
+ }
219
+ tokens = loaded;
220
+ return tokens;
221
+ };
222
+ }
223
+
224
+ /**
225
+ * Runs `callback` while holding `credentials.json.lock`, so concurrent
226
+ * processes cannot interleave a read-modify-write and lose each other's
227
+ * entries. Reads need no lock because each save is an atomic rename.
228
+ *
229
+ * @template T
230
+ * @param {CredentialStore} store
231
+ * @param {() => T} callback
232
+ * @returns {T}
233
+ */
234
+ function withStoreLock(store, callback) {
235
+ const fileSystem = store.fileSystem ?? DEFAULT_FILE_SYSTEM;
236
+ const directory = path.dirname(credentialsPath(store));
237
+ const lock = path.join(directory, "credentials.json.lock");
238
+ const deadline = Date.now() + (store.lockTimeoutMs ?? LOCK_TIMEOUT_MS);
239
+
240
+ fileSystem.mkdirSync(directory, { recursive: true, mode: 0o700 });
241
+ while (true) {
242
+ try {
243
+ fileSystem.writeFileSync(lock, `${process.pid}\n`, {
244
+ flag: "wx",
245
+ mode: 0o600,
246
+ });
247
+ break;
248
+ } catch (error) {
249
+ if (!isExistingFileError(error)) throw error;
250
+ }
251
+ if (Date.now() >= deadline) {
252
+ throw new CredentialsLockedError(
253
+ "Another process is updating the credentials file.",
254
+ );
255
+ }
256
+ sleep(LOCK_RETRY_MS);
257
+ }
258
+
259
+ try {
260
+ return callback();
261
+ } finally {
262
+ try {
263
+ fileSystem.rmSync(lock, { force: true });
264
+ } catch {
265
+ // The callback's outcome matters more; a leftover lock is reported later.
266
+ }
267
+ }
268
+ }
269
+
270
+ /** @param {number} milliseconds */
271
+ function sleep(milliseconds) {
272
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
273
+ }
274
+
275
+ /** @param {CredentialStore} store @param {Credentials} credentials */
276
+ function saveCredentials(store, credentials) {
277
+ const fileSystem = store.fileSystem ?? DEFAULT_FILE_SYSTEM;
278
+ const target = credentialsPath(store);
279
+ const directory = path.dirname(target);
280
+ const temporaryId =
281
+ store.createTemporaryId?.() ?? randomBytes(8).toString("hex");
282
+ const temporary = path.join(
283
+ directory,
284
+ `.credentials.json.${temporaryId}.tmp`,
285
+ );
286
+
287
+ try {
288
+ fileSystem.writeFileSync(
289
+ temporary,
290
+ `${JSON.stringify(credentials, null, 2)}\n`,
291
+ { flag: "wx", mode: 0o600, flush: true },
292
+ );
293
+ fileSystem.renameSync(temporary, target);
294
+ } catch (error) {
295
+ try {
296
+ fileSystem.rmSync(temporary, { force: true });
297
+ } catch {
298
+ // The original failure is the useful one.
299
+ }
300
+ throw error;
301
+ }
302
+ }
303
+
304
+ /** @returns {Credentials} */
305
+ function emptyCredentials() {
306
+ return { format: CREDENTIALS_FORMAT, origins: emptyOrigins() };
307
+ }
308
+
309
+ /**
310
+ * Origins are keyed by URL origin; a null prototype keeps keys such as
311
+ * `__proto__` inert.
312
+ *
313
+ * @returns {Record<string, CredentialEntry>}
314
+ */
315
+ function emptyOrigins() {
316
+ return Object.create(null);
317
+ }
318
+
319
+ /** @param {unknown} value @returns {value is CredentialEntry} */
320
+ function isCredentialEntry(value) {
321
+ return (
322
+ isRecord(value) &&
323
+ typeof value.access_token === "string" &&
324
+ value.access_token.length > 0 &&
325
+ typeof value.token_type === "string" &&
326
+ typeof value.created_at === "string"
327
+ );
328
+ }
329
+
330
+ /** @param {unknown} error */
331
+ function isExistingFileError(error) {
332
+ return error instanceof Error && "code" in error && error.code === "EEXIST";
333
+ }
334
+
335
+ /** @param {unknown} error */
336
+ function isMissingFileError(error) {
337
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
338
+ }
339
+
340
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
341
+ function isRecord(value) {
342
+ return typeof value === "object" && value !== null && !Array.isArray(value);
343
+ }