@firstdraft.com/cli 0.9.0 → 0.11.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.
package/src/plan-state.js CHANGED
@@ -1,7 +1,18 @@
1
- import { lstatSync, readFileSync } from "node:fs";
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ unlinkSync,
4
+ mkdirSync,
5
+ rmdirSync,
6
+ lstatSync,
7
+ readFileSync,
8
+ renameSync,
9
+ rmSync,
10
+ writeFileSync,
11
+ } from "node:fs";
2
12
  import path from "node:path";
3
13
 
4
14
  import { isFileSystemError } from "./file-system.js";
15
+ import { ROOT_TRANSACTION_NAME, HOSTED_WRITER_NAME } from "./root-output.js";
5
16
 
6
17
  const STATE_FORMAT = "firstdraft.cli-state/1";
7
18
  export const MAX_STATE_BYTES = 4096;
@@ -21,6 +32,8 @@ const DEFAULT_FILE_SYSTEM = { lstatSync, readFileSync };
21
32
 
22
33
  export class PlanStateConfigurationError extends Error {}
23
34
  export class PlanStateLocalError extends Error {}
35
+ export class PlanStateBusyError extends PlanStateLocalError {}
36
+ export class PlanStateNotPushedError extends Error {}
24
37
 
25
38
  /**
26
39
  * @param {object} options
@@ -39,6 +52,224 @@ export function readPlanState({ cwd, fileSystem = DEFAULT_FILE_SYSTEM }) {
39
52
  return parsePlanState(source);
40
53
  }
41
54
 
55
+ /**
56
+ * The Project and API origin that a successful plan push pinned, read from
57
+ * the Project's directory or, in an application that adopted the current
58
+ * directory, from the planning state archived at .firstdraft/design.
59
+ *
60
+ * @param {object} options
61
+ * @param {string} options.cwd
62
+ * @param {PlanStateFileSystem} [options.fileSystem]
63
+ */
64
+ export function readPinnedProject({ cwd, fileSystem }) {
65
+ const projectDirectory = pinnedProjectDirectory(cwd, fileSystem);
66
+ const state = readPlanState({ cwd: projectDirectory, fileSystem });
67
+ if (state.api_url === undefined || state.foundation_plan_etag === undefined) {
68
+ throw new PlanStateNotPushedError(
69
+ "The local Foundation Plan has not been pushed.",
70
+ );
71
+ }
72
+
73
+ return {
74
+ apiUrl: state.api_url,
75
+ projectId: state.project_id,
76
+ stateDirectory: path.join(projectDirectory, ".firstdraft"),
77
+ };
78
+ }
79
+
80
+ // Every Compilation writes its GapSet into the application as
81
+ // .firstdraft/gaps.json, and the GapSet's project.id is the Project's ID,
82
+ // which no recompile changes. The service caps a GapSet at 32 MiB.
83
+ const APPLICATION_GAP_SET = path.join(".firstdraft", "gaps.json");
84
+ const MAX_GAP_SET_BYTES = 32 * 1024 * 1024;
85
+ const GAP_SET_FORMAT_PREFIX = "firstdraft.foundation-gaps/";
86
+
87
+ /**
88
+ * The Project as readPinnedProject reads it, or, where there is no Project
89
+ * state but the application's own .firstdraft/gaps.json names a Project, as
90
+ * in a fresh clone of the application, that Project at `selectOrigin()`. The
91
+ * application's files hold no origin and no Compilation record, so such a
92
+ * Project has neither a pinned origin nor a state directory.
93
+ *
94
+ * @param {object} options
95
+ * @param {string} options.cwd
96
+ * @param {PlanStateFileSystem} [options.fileSystem]
97
+ * @param {() => string} options.selectOrigin the origin `login` would use
98
+ * @returns {{apiUrl: string, projectId: string, stateDirectory: string | null, fromApplication: boolean}}
99
+ */
100
+ export function readPinnedOrApplicationProject({
101
+ cwd,
102
+ fileSystem = DEFAULT_FILE_SYSTEM,
103
+ selectOrigin,
104
+ }) {
105
+ const stateFile = path.join(
106
+ pinnedProjectDirectory(cwd, fileSystem),
107
+ ".firstdraft",
108
+ "state.json",
109
+ );
110
+ const gapSetFile = path.join(cwd, APPLICATION_GAP_SET);
111
+ if (isAbsent(stateFile, fileSystem) && !isAbsent(gapSetFile, fileSystem)) {
112
+ assertLocalDirectory(path.join(cwd, ".firstdraft"), fileSystem);
113
+ return {
114
+ apiUrl: selectOrigin(),
115
+ projectId: readGapSetProjectId(gapSetFile, fileSystem),
116
+ stateDirectory: null,
117
+ fromApplication: true,
118
+ };
119
+ }
120
+
121
+ return { ...readPinnedProject({ cwd, fileSystem }), fromApplication: false };
122
+ }
123
+
124
+ /**
125
+ * @param {string} filePath
126
+ * @param {PlanStateFileSystem} fileSystem
127
+ */
128
+ function readGapSetProjectId(filePath, fileSystem) {
129
+ const source = readLocalFile(filePath, MAX_GAP_SET_BYTES, fileSystem);
130
+ /** @type {unknown} */
131
+ let document;
132
+ try {
133
+ document = JSON.parse(
134
+ new TextDecoder("utf-8", { fatal: true }).decode(source),
135
+ );
136
+ } catch {
137
+ throw new PlanStateLocalError(
138
+ "The application's GapSet is not UTF-8 JSON.",
139
+ );
140
+ }
141
+ const projectId =
142
+ isRecord(document) &&
143
+ typeof document.format === "string" &&
144
+ document.format.startsWith(GAP_SET_FORMAT_PREFIX) &&
145
+ isRecord(document.project)
146
+ ? document.project.id
147
+ : undefined;
148
+ if (typeof projectId !== "string" || !PROJECT_ID_PATTERN.test(projectId)) {
149
+ throw new PlanStateLocalError(
150
+ "The application's GapSet names no First Draft Project.",
151
+ );
152
+ }
153
+
154
+ return projectId;
155
+ }
156
+
157
+ /**
158
+ * The directory whose .firstdraft holds the Project's state: `cwd`, or the
159
+ * archive at .firstdraft/design when `cwd` is an adopted application root.
160
+ *
161
+ * @param {string} cwd
162
+ * @param {PlanStateFileSystem} [fileSystem]
163
+ */
164
+ function pinnedProjectDirectory(cwd, fileSystem) {
165
+ // Only an adopted root, whose real .firstdraft holds no state.json, falls
166
+ // back; any other local problem is reported for this directory.
167
+ const adoptedRoot =
168
+ isDirectory(path.join(cwd, ".firstdraft"), fileSystem) &&
169
+ isAbsent(path.join(cwd, ".firstdraft", "state.json"), fileSystem) &&
170
+ isDirectory(path.join(cwd, ".firstdraft", "design"), fileSystem);
171
+ return adoptedRoot ? path.join(cwd, ".firstdraft", "design") : cwd;
172
+ }
173
+
174
+ // The Compilation whose code the CLI last recorded writing for the Project,
175
+ // kept in its own file beside state.json so the state format stays as it
176
+ // is. It moves with the planning state into an adopted root's archive.
177
+ const COMPILATION_RECORD_NAME = "compilation.json";
178
+ const COMPILATION_RECORD_FORMAT = "firstdraft.cli-compilation/1";
179
+
180
+ export class CompilationRecordWriteError extends Error {}
181
+ export class CompilationNotRecordedError extends Error {}
182
+
183
+ /**
184
+ * Records `compilationId` as the Compilation whose code the CLI just wrote,
185
+ * beside the state of the Project found from `cwd` as readPinnedProject
186
+ * finds it, replacing any earlier record.
187
+ *
188
+ * @param {object} options
189
+ * @param {string} options.cwd
190
+ * @param {string} options.compilationId
191
+ * @param {() => string} [options.createTemporaryId]
192
+ * @returns {string} the record's path
193
+ */
194
+ export function recordCompilation({
195
+ cwd,
196
+ compilationId,
197
+ createTemporaryId = randomUUID,
198
+ }) {
199
+ const recordPath = path.join(
200
+ pinnedProjectDirectory(cwd),
201
+ ".firstdraft",
202
+ COMPILATION_RECORD_NAME,
203
+ );
204
+ const temporaryPath = `${recordPath}.${createTemporaryId()}.tmp`;
205
+ const source = `${JSON.stringify(
206
+ { format: COMPILATION_RECORD_FORMAT, compilation_id: compilationId },
207
+ null,
208
+ 2,
209
+ )}\n`;
210
+ try {
211
+ writeFileSync(temporaryPath, source, {
212
+ flag: "wx",
213
+ mode: 0o600,
214
+ flush: true,
215
+ });
216
+ renameSync(temporaryPath, recordPath);
217
+ } catch (error) {
218
+ if (!isFileSystemError(error)) throw error;
219
+
220
+ throw new CompilationRecordWriteError(
221
+ "The Compilation record could not be written.",
222
+ { cause: error },
223
+ );
224
+ }
225
+ return recordPath;
226
+ }
227
+
228
+ /**
229
+ * The Compilation that recordCompilation recorded in `stateDirectory`.
230
+ *
231
+ * @param {object} options
232
+ * @param {string} options.stateDirectory from readPinnedProject
233
+ * @param {PlanStateFileSystem} [options.fileSystem]
234
+ * @returns {string}
235
+ */
236
+ export function readRecordedCompilation({
237
+ stateDirectory,
238
+ fileSystem = DEFAULT_FILE_SYSTEM,
239
+ }) {
240
+ const recordPath = path.join(stateDirectory, COMPILATION_RECORD_NAME);
241
+ if (isAbsent(recordPath, fileSystem)) {
242
+ throw new CompilationNotRecordedError(
243
+ "No Compilation is recorded for this Project.",
244
+ );
245
+ }
246
+
247
+ const source = readLocalFile(recordPath, MAX_STATE_BYTES, fileSystem);
248
+ let record;
249
+ try {
250
+ record = JSON.parse(
251
+ new TextDecoder("utf-8", { fatal: true }).decode(source),
252
+ );
253
+ } catch (error) {
254
+ if (!(error instanceof SyntaxError || error instanceof TypeError)) {
255
+ throw error;
256
+ }
257
+
258
+ throw new PlanStateLocalError("The Compilation record is invalid.", {
259
+ cause: error,
260
+ });
261
+ }
262
+ if (
263
+ !isRecord(record) ||
264
+ !arraysEqual(Object.keys(record).sort(), ["compilation_id", "format"]) ||
265
+ record.format !== COMPILATION_RECORD_FORMAT ||
266
+ !isUuidV7(record.compilation_id)
267
+ ) {
268
+ throw new PlanStateLocalError("The Compilation record is invalid.");
269
+ }
270
+ return record.compilation_id;
271
+ }
272
+
42
273
  /** @param {string} value */
43
274
  export function normalizeApiUrl(value) {
44
275
  let url;
@@ -72,6 +303,35 @@ export function normalizeApiUrl(value) {
72
303
  return url.origin;
73
304
  }
74
305
 
306
+ /**
307
+ * @param {string} directory
308
+ * @param {PlanStateFileSystem} [fileSystem]
309
+ */
310
+ function isDirectory(directory, fileSystem = DEFAULT_FILE_SYSTEM) {
311
+ try {
312
+ return fileSystem.lstatSync(directory).isDirectory();
313
+ } catch (error) {
314
+ if (!isFileSystemError(error)) throw error;
315
+
316
+ return false;
317
+ }
318
+ }
319
+
320
+ /**
321
+ * @param {string} filePath
322
+ * @param {PlanStateFileSystem} [fileSystem]
323
+ */
324
+ function isAbsent(filePath, fileSystem = DEFAULT_FILE_SYSTEM) {
325
+ try {
326
+ fileSystem.lstatSync(filePath);
327
+ return false;
328
+ } catch (error) {
329
+ if (!isFileSystemError(error)) throw error;
330
+
331
+ return error.code === "ENOENT";
332
+ }
333
+ }
334
+
75
335
  /** @param {unknown} value @returns {value is string} */
76
336
  export function isUuidV7(value) {
77
337
  return typeof value === "string" && PROJECT_ID_PATTERN.test(value);
@@ -82,7 +342,11 @@ export function isUuidV7(value) {
82
342
  * @param {number} maximumBytes
83
343
  * @param {PlanStateFileSystem} fileSystem
84
344
  */
85
- export function readLocalFile(filePath, maximumBytes, fileSystem) {
345
+ export function readLocalFile(
346
+ filePath,
347
+ maximumBytes,
348
+ fileSystem = DEFAULT_FILE_SYSTEM,
349
+ ) {
86
350
  try {
87
351
  const stat = fileSystem.lstatSync(filePath);
88
352
  if (!stat.isFile() || stat.size > maximumBytes) {
@@ -153,9 +417,15 @@ function parsePlanState(source) {
153
417
  const keys = Object.keys(state).sort();
154
418
  const hasRemoteState =
155
419
  state.api_url !== undefined || state.foundation_plan_etag !== undefined;
156
- const expectedKeys = hasRemoteState
157
- ? ["api_url", "format", "foundation_plan_etag", "project_id"]
158
- : ["format", "project_id"];
420
+ const expectedKeys = ["format", "project_id"];
421
+ if (hasRemoteState) expectedKeys.push("api_url");
422
+ if (
423
+ hasRemoteState &&
424
+ (state.reserved !== true || state.foundation_plan_etag !== undefined)
425
+ )
426
+ expectedKeys.push("foundation_plan_etag");
427
+ if (state.reserved === true) expectedKeys.push("reserved");
428
+ expectedKeys.sort();
159
429
  let storedApiUrl;
160
430
 
161
431
  if (typeof state.api_url === "string") {
@@ -171,6 +441,7 @@ function parsePlanState(source) {
171
441
  }
172
442
 
173
443
  if (
444
+ (state.reserved === true && !storedApiUrl) ||
174
445
  !arraysEqual(keys, expectedKeys) ||
175
446
  state.format !== STATE_FORMAT ||
176
447
  !isUuidV7(state.project_id) ||
@@ -182,6 +453,7 @@ function parsePlanState(source) {
182
453
  }
183
454
 
184
455
  return {
456
+ ...(state.reserved === true ? { reserved: true } : {}),
185
457
  format: state.format,
186
458
  project_id: state.project_id,
187
459
  ...(storedApiUrl ? { api_url: storedApiUrl } : {}),
@@ -212,3 +484,51 @@ function arraysEqual(left, right) {
212
484
  left.every((value, index) => value === right[index])
213
485
  );
214
486
  }
487
+
488
+ /**
489
+ * Serialize hosted writes from capture through durable local receipt. A response
490
+ * can arrive after a later writer commits, even when the Plan digest repeats.
491
+ * @template T
492
+ * @param {string} directory @param {() => Promise<T>} update
493
+ */
494
+ export async function withPlanStateLock(directory, update) {
495
+ assertLocalDirectory(directory, DEFAULT_FILE_SYSTEM);
496
+ const transaction = path.join(path.dirname(directory), ROOT_TRANSACTION_NAME);
497
+ try {
498
+ mkdirSync(transaction, { mode: 0o700 });
499
+ } catch (error) {
500
+ if (isFileSystemError(error) && error.code === "EEXIST")
501
+ throw new PlanStateBusyError(
502
+ "Another command is updating this Project, or a root output transaction needs recovery. Retry after the active command finishes. See the CLI's Sketch review recovery instructions if it stopped.",
503
+ );
504
+ if (isFileSystemError(error))
505
+ throw new PlanStateLocalError(
506
+ "Could not lock the local Project for writing.",
507
+ { cause: error },
508
+ );
509
+ throw error;
510
+ }
511
+ const owner = path.join(transaction, HOSTED_WRITER_NAME);
512
+ try {
513
+ try {
514
+ writeFileSync(owner, String(process.pid) + "\n", {
515
+ flag: "wx",
516
+ mode: 0o600,
517
+ });
518
+ } catch (error) {
519
+ if (!isFileSystemError(error)) throw error;
520
+ rmSync(owner, { force: true });
521
+ throw new PlanStateLocalError(
522
+ "Could not record the hosted writer in the local Project reservation.",
523
+ { cause: error },
524
+ );
525
+ }
526
+ try {
527
+ return await update();
528
+ } finally {
529
+ unlinkSync(owner);
530
+ }
531
+ } finally {
532
+ rmdirSync(transaction);
533
+ }
534
+ }
@@ -22,6 +22,7 @@ import path from "node:path";
22
22
 
23
23
  import { isFileSystemError } from "./file-system.js";
24
24
 
25
+ export const HOSTED_WRITER_NAME = "hosted-writer.pid";
25
26
  export const ROOT_TRANSACTION_NAME = ".firstdraft-root-output";
26
27
  export const ROOT_DESIGN_PATH = ".firstdraft/design";
27
28
 
@@ -268,12 +269,13 @@ export function releaseRootOutput(target) {
268
269
  * @param {object} callbacks
269
270
  * @param {(root: string) => void} callbacks.writeArtifact
270
271
  * @param {(root: string, ignoredPaths?: Set<string>) => void} callbacks.verifyArtifact
272
+ * @param {(designDirectory: string) => void} [callbacks.verifyDesign]
271
273
  * @param {(from: string, to: string) => void} [callbacks.rename]
272
274
  */
273
275
  export function materializeRootOutput(
274
276
  target,
275
277
  artifact,
276
- { writeArtifact, verifyArtifact, rename = renameSync },
278
+ { writeArtifact, verifyArtifact, verifyDesign, rename = renameSync },
277
279
  ) {
278
280
  assertOwnedTransaction(target);
279
281
  const artifactStage = path.join(target.transactionPath, ARTIFACT_STAGE_NAME);
@@ -289,6 +291,7 @@ export function materializeRootOutput(
289
291
  recheckRootSnapshot(target);
290
292
  performRootTransaction(target, artifact.files, rename);
291
293
  verifyRootResult(target, artifact.files, verifyArtifact);
294
+ verifyDesign?.(path.join(target.path, ROOT_DESIGN_PATH));
292
295
 
293
296
  target.journal.phase = "complete";
294
297
  target.journal.pending = null;
@@ -368,6 +371,15 @@ function assertDesignPathAvailable(root, name) {
368
371
  function existingTransactionError(root) {
369
372
  const journalPath = path.join(root, ROOT_TRANSACTION_NAME, JOURNAL_NAME);
370
373
  try {
374
+ if (
375
+ lstatSync(path.join(root, ROOT_TRANSACTION_NAME, HOSTED_WRITER_NAME), {
376
+ throwIfNoEntry: false,
377
+ })?.isFile()
378
+ )
379
+ return new RootOutputPathError(
380
+ "A hosted Project writer is active or retained.",
381
+ "root_busy",
382
+ );
371
383
  const journal = JSON.parse(readFileSync(journalPath, "utf8"));
372
384
  if (journal?.format === JOURNAL_FORMAT && journal?.root === root) {
373
385
  return new RootOutputPathError(