@firstdraft.com/cli 0.10.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.
@@ -20,6 +20,7 @@ import {
20
20
  normalizeApiUrl,
21
21
  readLocalFile,
22
22
  readPlanState,
23
+ withPlanStateLock,
23
24
  } from "../plan-state.js";
24
25
 
25
26
  export {
@@ -97,15 +98,28 @@ export class PlanPushStateWriteError extends Error {
97
98
  * @param {PushPlanOptions} options
98
99
  * @returns {Promise<PushPlanResult | RejectedPushResult>}
99
100
  */
100
- export async function pushPlan({
101
- cwd,
102
- apiUrl,
103
- fetchFunction = globalThis.fetch,
104
- fileSystem = DEFAULT_FILE_SYSTEM,
105
- createTemporaryId = randomUUID,
106
- createRequestSignal = () => AbortSignal.timeout(REQUEST_TIMEOUT_MS),
107
- }) {
108
- const state = readPlanState({ cwd, fileSystem });
101
+ export async function pushPlan(options) {
102
+ const state = readPlanState(options);
103
+ if (state.reserved)
104
+ return withPlanStateLock(path.join(options.cwd, ".firstdraft"), () =>
105
+ pushCurrentPlan(options),
106
+ );
107
+ return pushCurrentPlan(options, state);
108
+ }
109
+
110
+ /** @param {PushPlanOptions} options @param {ReturnType<typeof readPlanState>} [initialState] @returns {Promise<PushPlanResult | RejectedPushResult>} */
111
+ async function pushCurrentPlan(
112
+ {
113
+ cwd,
114
+ apiUrl,
115
+ fetchFunction = globalThis.fetch,
116
+ fileSystem = DEFAULT_FILE_SYSTEM,
117
+ createTemporaryId = randomUUID,
118
+ createRequestSignal = () => AbortSignal.timeout(REQUEST_TIMEOUT_MS),
119
+ },
120
+ initialState,
121
+ ) {
122
+ const state = initialState ?? readPlanState({ cwd, fileSystem });
109
123
  const directory = path.join(cwd, ".firstdraft");
110
124
  const planPath = path.join(directory, "foundation-plan.json");
111
125
  const statePath = path.join(directory, "state.json");
@@ -115,6 +129,7 @@ export async function pushPlan({
115
129
  project_id: state.project_id,
116
130
  });
117
131
  const headers = {
132
+ ...(state.reserved ? { "FirstDraft-Require-Project": "true" } : {}),
118
133
  Accept: "application/json, application/problem+json",
119
134
  "Content-Type": FOUNDATION_PLAN_MEDIA_TYPE,
120
135
  ...(state.foundation_plan_etag
@@ -192,7 +207,7 @@ export async function pushPlan({
192
207
  }
193
208
 
194
209
  /** @param {string | undefined} configured @param {string | undefined} stored */
195
- function resolveApiUrl(configured, stored) {
210
+ export function resolveApiUrl(configured, stored) {
196
211
  const configuredOrigin =
197
212
  configured === undefined ? undefined : normalizeApiUrl(configured);
198
213
  if (
@@ -226,8 +241,7 @@ function saveState({
226
241
  temporaryId,
227
242
  }) {
228
243
  const recoveryState = {
229
- format: state.format,
230
- project_id: state.project_id,
244
+ ...state,
231
245
  api_url: apiUrl,
232
246
  foundation_plan_etag: etag,
233
247
  };
@@ -162,7 +162,7 @@ export async function readPlanStatus({
162
162
  now = Date.now,
163
163
  }) {
164
164
  const state = readPlanState({ cwd, fileSystem });
165
- if (state.api_url === undefined) {
165
+ if (state.api_url === undefined || state.foundation_plan_etag === undefined) {
166
166
  throw new PlanStatusNotPushedError(
167
167
  "The local Foundation Plan has not been pushed.",
168
168
  );
@@ -0,0 +1,388 @@
1
+ import { ApiAuthenticationRequiredError } from "../api-authentication.js";
2
+ import { isUtf8 } from "node:buffer";
3
+ import {
4
+ mkdirSync,
5
+ existsSync,
6
+ readFileSync,
7
+ writeFileSync,
8
+ renameSync,
9
+ unlinkSync,
10
+ mkdtempSync,
11
+ rmSync,
12
+ linkSync,
13
+ } from "node:fs";
14
+ import { isFileSystemError } from "../file-system.js";
15
+ import path from "node:path";
16
+ import {
17
+ SERVICE_ROUTES,
18
+ serviceEndpoint,
19
+ sendRequest,
20
+ readResponseBody,
21
+ isProblemBody,
22
+ reviewConflict,
23
+ problemProjection,
24
+ responseMediaType,
25
+ isDiagnostic,
26
+ } from "../api-response.js";
27
+ import { generateUuidV7 } from "../uuid-v7.js";
28
+ import {
29
+ withPlanStateLock,
30
+ PlanStateLocalError,
31
+ readPlanState,
32
+ isUuidV7,
33
+ readLocalFile,
34
+ } from "../plan-state.js";
35
+ import { resolveApiUrl } from "./plan-push.js";
36
+ import {
37
+ digest,
38
+ captureBoard,
39
+ loadSources,
40
+ SketchError,
41
+ } from "../sketch-capture.js";
42
+ export { SketchError };
43
+ const privateWrite = { flag: "wx", mode: 0o600, flush: true };
44
+ /** @param {string} file @param {unknown} data @param {boolean} [exclusive] */
45
+ function save(file, data, exclusive = false) {
46
+ const temp = file + "." + generateUuidV7() + ".tmp";
47
+ writeFileSync(temp, JSON.stringify(data) + "\n", privateWrite);
48
+ try {
49
+ if (exclusive) linkSync(temp, file);
50
+ else renameSync(temp, file);
51
+ } finally {
52
+ if (existsSync(temp)) unlinkSync(temp);
53
+ }
54
+ }
55
+ /** @typedef {{cwd:string,apiUrl?:string,fetchFunction:typeof globalThis.fetch,hasTokenFor?:(origin:string)=>boolean}} Options */
56
+ /** @param {Options} options */
57
+ export async function startProject({
58
+ cwd,
59
+ apiUrl,
60
+ fetchFunction,
61
+ hasTokenFor,
62
+ }) {
63
+ const dir = path.join(cwd, ".firstdraft");
64
+ const existing = existsSync(dir) ? readPlanState({ cwd }) : null;
65
+ const origin = resolveApiUrl(apiUrl, existing?.api_url);
66
+ if (hasTokenFor && !hasTokenFor(origin))
67
+ throw new ApiAuthenticationRequiredError();
68
+ if (!existing) {
69
+ const temp = mkdtempSync(path.join(cwd, ".firstdraft-start-"));
70
+ try {
71
+ writeFileSync(path.join(temp, ".gitignore"), "*\n", privateWrite);
72
+ save(path.join(temp, "state.json"), {
73
+ format: "firstdraft.cli-state/1",
74
+ project_id: generateUuidV7(),
75
+ reserved: true,
76
+ api_url: origin,
77
+ });
78
+ renameSync(temp, dir);
79
+ } finally {
80
+ rmSync(temp, { force: true, recursive: true });
81
+ }
82
+ }
83
+ const state = existing ?? readPlanState({ cwd });
84
+ if (!state.reserved)
85
+ throw new SketchError(
86
+ "This planning directory already has a Plan. Resume its existing workflow.",
87
+ );
88
+ const response = await sendRequest(
89
+ fetchFunction,
90
+ serviceEndpoint(SERVICE_ROUTES.startProject, origin, {
91
+ project_id: state.project_id,
92
+ }),
93
+ {
94
+ headers: { Accept: "application/json" },
95
+ redirect: "error",
96
+ signal: AbortSignal.timeout(30000),
97
+ },
98
+ );
99
+ const body = await readResponseBody(response);
100
+ if (![200, 201].includes(response.status))
101
+ throw new SketchError(
102
+ "First Draft could not open the Project. Check the hosted Sketches endpoint and retry in this directory.",
103
+ response.status,
104
+ problem(response, body),
105
+ );
106
+ const url = new URL("/projects/" + state.project_id, origin).href;
107
+ if (
108
+ responseMediaType(response) !== "application/json" ||
109
+ body?.project?.id !== state.project_id ||
110
+ ![url, "/projects/" + state.project_id].includes(body.project.url)
111
+ )
112
+ throw new SketchError("Unexpected Project identity in the response.");
113
+ return { project: { id: state.project_id, url } };
114
+ }
115
+
116
+ /** @param {string} cwd @param {string} [revision] */
117
+ function readReview(cwd, revision) {
118
+ const file = revision
119
+ ? path.join(cwd, ".firstdraft", "sketch-reviews", revision + ".json")
120
+ : path.join(cwd, ".firstdraft", "sketch-review.json");
121
+ if (!existsSync(file)) return null;
122
+ /** @type {{id:string,plan_sha256:string,files:Record<string,string>}} */
123
+ const receipt = JSON.parse(readLocalFile(file, 1024 * 1024).toString());
124
+ if (
125
+ !receipt ||
126
+ !isUuidV7(receipt.id) ||
127
+ !receipt.files ||
128
+ !/^[a-f0-9]{64}$/.test(receipt.plan_sha256)
129
+ )
130
+ throw new SketchError("Invalid local sketch review receipt.");
131
+ return receipt;
132
+ }
133
+ /** @typedef {Options & {capture?:typeof captureBoard, after?:string, head?:string}} PublishOptions */
134
+ /** @param {PublishOptions} options */
135
+ export async function publishSketches(options) {
136
+ return withPlanStateLock(path.join(options.cwd, ".firstdraft"), () =>
137
+ publishCurrentSketches(options),
138
+ );
139
+ }
140
+
141
+ /** @param {PublishOptions} options */
142
+ async function publishCurrentSketches({
143
+ cwd,
144
+ apiUrl,
145
+ fetchFunction,
146
+ hasTokenFor,
147
+ capture = captureBoard,
148
+ after,
149
+ head,
150
+ }) {
151
+ const dir = path.join(cwd, ".firstdraft");
152
+ const state = readPlanState({ cwd });
153
+ if (!state.reserved)
154
+ throw new SketchError(
155
+ "Use firstdraft project start in the hosted interview directory.",
156
+ );
157
+ const origin = resolveApiUrl(apiUrl, state.api_url);
158
+ if (hasTokenFor && !hasTokenFor(origin))
159
+ throw new ApiAuthenticationRequiredError();
160
+ const pendingFile = path.join(dir, "sketch-pending.json");
161
+ const replay = existsSync(pendingFile);
162
+ if (!replay) {
163
+ const previous = after === "none" ? null : (after ?? readReview(cwd)?.id);
164
+ const planBytes = readLocalFile(
165
+ path.join(dir, "foundation-plan.json"),
166
+ 1024 * 1024,
167
+ );
168
+ if (!isUtf8(planBytes))
169
+ throw new SketchError("The Foundation Plan must contain valid UTF-8.");
170
+ const plan_source = planBytes.toString("utf8");
171
+ const sources = loadSources(cwd);
172
+ const manifest = await capture(sources, plan_source);
173
+ const body = JSON.stringify({
174
+ previous_revision_id: previous ?? null,
175
+ expected_plan_sha256:
176
+ head === "none"
177
+ ? null
178
+ : (head ?? state.foundation_plan_etag?.slice(8, -1) ?? null),
179
+ plan_source,
180
+ manifest,
181
+ });
182
+ if (Buffer.byteLength(body) > 24 * 1024 * 1024)
183
+ throw new SketchError("The review bundle exceeds 24 MiB.");
184
+ save(
185
+ pendingFile,
186
+ {
187
+ id: generateUuidV7(),
188
+ local_etag: state.foundation_plan_etag,
189
+ body,
190
+ files: Object.fromEntries(
191
+ [...sources.files].map(([name, bytes]) => [name, digest(bytes)]),
192
+ ),
193
+ },
194
+ true,
195
+ );
196
+ }
197
+ const pending = JSON.parse(
198
+ readLocalFile(pendingFile, 52 * 1024 * 1024).toString(),
199
+ );
200
+ if (!isUuidV7(pending.id))
201
+ throw new SketchError("The pending review ID is invalid.");
202
+ const request = JSON.parse(pending.body);
203
+ if (
204
+ after &&
205
+ (request.previous_revision_id !== (after === "none" ? null : after) ||
206
+ request.expected_plan_sha256 !== (head === "none" ? null : head))
207
+ )
208
+ throw new SketchError(
209
+ "The pending publication has different preconditions. Run sketches publish without options to replay it.",
210
+ );
211
+ const response = await sendRequest(
212
+ fetchFunction,
213
+ serviceEndpoint(SERVICE_ROUTES.publishSketches, origin, {
214
+ project_id: state.project_id,
215
+ revision_id: pending.id,
216
+ }),
217
+ {
218
+ headers: {
219
+ Accept: "application/json",
220
+ "Content-Type": "application/vnd.firstdraft.sketch-review+json",
221
+ },
222
+ body: pending.body,
223
+ redirect: "error",
224
+ signal: AbortSignal.timeout(120000),
225
+ },
226
+ );
227
+ const body = await readResponseBody(response);
228
+ if (![200, 201].includes(response.status)) {
229
+ const rejection = problem(response, body);
230
+ const refusedThisRequest =
231
+ response.status >= 400 &&
232
+ response.status < 500 &&
233
+ response.status !== 408;
234
+ // A refused retry resolves the original ambiguity only after the Service
235
+ // has looked up its revision ID. Authorization and quotas on the endpoint
236
+ // itself run before that lookup.
237
+ const resolvedRevision =
238
+ rejection &&
239
+ (("code" in rejection &&
240
+ ((rejection.code === "invalid_sketch_review" &&
241
+ response.status === 422) ||
242
+ (rejection.code === "sketch_review_conflict" &&
243
+ response.status === 409) ||
244
+ (rejection.code === "compilation_active" &&
245
+ response.status === 409) ||
246
+ (rejection.code === "invalid_sketch_review" &&
247
+ response.status === 422) ||
248
+ (rejection.code === "sketch_quota_reached" &&
249
+ response.status === 413))) ||
250
+ ("diagnostics" in rejection && response.status === 422));
251
+ if (refusedThisRequest && (!replay || resolvedRevision))
252
+ unlinkSync(pendingFile);
253
+ throw new SketchError(
254
+ "First Draft declined the sketch review. Inspect the current review and repair the draft.",
255
+ response.status,
256
+ rejection,
257
+ );
258
+ }
259
+ const sha = request.manifest.plan_sha256;
260
+ const etag = response.headers.get("etag");
261
+ if (
262
+ responseMediaType(response) !== "application/json" ||
263
+ etag !== '"sha256:' + sha + '"' ||
264
+ body?.project?.id !== state.project_id ||
265
+ body?.review?.id !== pending.id ||
266
+ body?.review?.plan_sha256 !== sha ||
267
+ body?.foundation_plan?.source_sha256 !== sha
268
+ )
269
+ throw new SketchError(
270
+ "Unexpected review identity. Retry the same publication.",
271
+ );
272
+ const latest = readPlanState({ cwd });
273
+ const knownHead = latest.foundation_plan_etag?.slice(8, -1) ?? null;
274
+ if (
275
+ knownHead === request.expected_plan_sha256 ||
276
+ latest.foundation_plan_etag === pending.local_etag
277
+ ) {
278
+ save(path.join(dir, "state.json"), {
279
+ ...latest,
280
+ foundation_plan_etag: etag,
281
+ });
282
+ }
283
+ const receipt = { id: pending.id, plan_sha256: sha, files: pending.files };
284
+ const archive = path.join(dir, "sketch-reviews");
285
+ mkdirSync(archive, { recursive: true, mode: 0o700 });
286
+ const previous = readReview(cwd);
287
+ if (previous) {
288
+ const oldFile = path.join(archive, previous.id + ".json");
289
+ if (!existsSync(oldFile)) save(oldFile, previous);
290
+ }
291
+ save(path.join(archive, pending.id + ".json"), receipt);
292
+ save(path.join(dir, "sketch-review.json"), receipt);
293
+ unlinkSync(pendingFile);
294
+ let nextStep;
295
+ if (replay) {
296
+ try {
297
+ reviewedSources(cwd, pending.id);
298
+ } catch (error) {
299
+ if (!(
300
+ error instanceof SketchError || error instanceof PlanStateLocalError
301
+ ))
302
+ throw error;
303
+ nextStep =
304
+ "Recovered the saved publication. The current planning files do not match this review. Run firstdraft sketches publish again to capture and publish the current draft.";
305
+ }
306
+ }
307
+ return {
308
+ project: {
309
+ id: state.project_id,
310
+ url: new URL("/projects/" + state.project_id, origin).href,
311
+ },
312
+ review: { id: pending.id, plan_sha256: sha },
313
+ ...(nextStep ? { next_step: nextStep } : {}),
314
+ foundation_plan: { source_sha256: sha },
315
+ };
316
+ }
317
+
318
+ /** @param {string} cwd @param {string|undefined} revision @param {boolean} [retained] */
319
+ export function reviewedSources(cwd, revision, retained = false) {
320
+ try {
321
+ return loadReviewedSources(cwd, revision, retained);
322
+ } catch (error) {
323
+ if (!isFileSystemError(error) && !(error instanceof SyntaxError))
324
+ throw error;
325
+ throw new SketchError(
326
+ "Restore the approved board, source files and local review receipt before Compile.",
327
+ );
328
+ }
329
+ }
330
+
331
+ /** @param {string} cwd @param {string|undefined} revision @param {boolean} [retained] */
332
+ function loadReviewedSources(cwd, revision, retained) {
333
+ const receipt =
334
+ (retained && isUuidV7(revision) ? readReview(cwd, revision) : null) ??
335
+ readReview(cwd);
336
+ if (!receipt && !revision) {
337
+ if (
338
+ !retained &&
339
+ existsSync(path.join(cwd, ".firstdraft", "state.json")) &&
340
+ readPlanState({ cwd }).reserved
341
+ )
342
+ throw new SketchError(
343
+ "Publish the Sketches and obtain approval for the revision before Compile.",
344
+ );
345
+ return;
346
+ }
347
+ if (!receipt || receipt.id !== revision)
348
+ throw new SketchError(
349
+ retained
350
+ ? "Restore the local receipt for this Compilation’s sketch revision in the planning folder before downloading."
351
+ : "Compile with --revision followed by the approved sketch revision ID.",
352
+ );
353
+ const sources = loadSources(cwd);
354
+ if (
355
+ digest(
356
+ readFileSync(path.join(cwd, ".firstdraft", "foundation-plan.json")),
357
+ ) !== receipt.plan_sha256 ||
358
+ sources.files.size !== Object.keys(receipt.files).length ||
359
+ [...sources.files].some(
360
+ ([name, bytes]) => digest(bytes) !== receipt.files[name],
361
+ )
362
+ )
363
+ throw new SketchError(
364
+ "The Plan or sketch sources changed since review. Publish and review the changes before Compile.",
365
+ );
366
+ return { files: sources.files, planSha256: receipt.plan_sha256 };
367
+ }
368
+
369
+ /** @param {Response} response @param {Record<string,any>|null} body */
370
+ function problem(response, body) {
371
+ if (!body) return;
372
+ const conflict = reviewConflict(response, body);
373
+ if (conflict) return conflict;
374
+ if (isProblemBody(response, body)) return problemProjection(body);
375
+ if (
376
+ response.status === 422 &&
377
+ Array.isArray(body.diagnostics) &&
378
+ body.diagnostics.every(isDiagnostic)
379
+ )
380
+ return {
381
+ diagnostics: body.diagnostics.map(({ code, message, severity }) => ({
382
+ code,
383
+ message,
384
+ severity,
385
+ })),
386
+ };
387
+ return undefined;
388
+ }
@@ -5,6 +5,7 @@ import {
5
5
  mkdirSync,
6
6
  mkdtempSync,
7
7
  readdirSync,
8
+ realpathSync,
8
9
  readFileSync,
9
10
  renameSync,
10
11
  rmSync,
@@ -278,8 +279,9 @@ export function releaseCompilationOutputTarget(target) {
278
279
  /**
279
280
  * @param {ValidatedCompilationArtifact} artifact
280
281
  * @param {string | import("./root-output.js").RootOutputTarget} target
282
+ * @param {Map<string,Buffer>} [sketchFiles]
281
283
  */
282
- export function materializeCompilationArtifact(artifact, target) {
284
+ export function materializeCompilationArtifact(artifact, target, sketchFiles) {
283
285
  if (typeof target !== "string") {
284
286
  try {
285
287
  return materializeRootOutput(target, artifact, {
@@ -287,10 +289,29 @@ export function materializeCompilationArtifact(artifact, target) {
287
289
  writeArtifactTree(artifact.files, root);
288
290
  applyMode(root, DIRECTORY_MODE);
289
291
  },
290
- verifyArtifact: (root, ignoredPaths) =>
292
+ verifyArtifact: (root, ignoredPaths) => {
291
293
  verifyArtifactTree(artifact.files, root, ignoredPaths, {
292
294
  verifyRootMode: ignoredPaths === undefined,
293
- }),
295
+ });
296
+ },
297
+ verifyDesign: (designDirectory) => {
298
+ if (sketchFiles) {
299
+ const archive = path.join(designDirectory, "sketches");
300
+ for (const [name, bytes] of sketchFiles) {
301
+ const selected = path.join(archive, name);
302
+ if (
303
+ realpathSync(selected) !== selected ||
304
+ !lstatSync(selected).isFile() ||
305
+ !readFileSync(selected).equals(bytes)
306
+ ) {
307
+ throw new RootOutputMaterializationError(
308
+ "The archived sketch sources changed after review.",
309
+ "reviewed_sources_changed",
310
+ );
311
+ }
312
+ }
313
+ }
314
+ },
294
315
  });
295
316
  } catch (error) {
296
317
  if (!(error instanceof RootOutputMaterializationError)) throw error;
@@ -314,6 +335,17 @@ export function materializeCompilationArtifact(artifact, target) {
314
335
  writeArtifactTree(artifact.files, temporaryDirectory);
315
336
  applyMode(temporaryDirectory, DIRECTORY_MODE);
316
337
  verifyArtifactTree(artifact.files, temporaryDirectory);
338
+ if (sketchFiles) {
339
+ const design = path.join(temporaryDirectory, ".firstdraft", "design");
340
+ mkdirSync(design, { recursive: true });
341
+ const root = path.join(design, "sketches");
342
+ mkdirSync(root);
343
+ for (const [name, bytes] of sketchFiles) {
344
+ const file = path.join(root, name);
345
+ mkdirSync(path.dirname(file), { recursive: true });
346
+ writeFileSync(file, bytes, { flag: "wx" });
347
+ }
348
+ }
317
349
  assertTargetStillAvailable(target, parent);
318
350
  renameSync(temporaryDirectory, target);
319
351
  temporaryDirectory = null;
package/src/plan-state.js CHANGED
@@ -1,8 +1,18 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { lstatSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import {
3
+ unlinkSync,
4
+ mkdirSync,
5
+ rmdirSync,
6
+ lstatSync,
7
+ readFileSync,
8
+ renameSync,
9
+ rmSync,
10
+ writeFileSync,
11
+ } from "node:fs";
3
12
  import path from "node:path";
4
13
 
5
14
  import { isFileSystemError } from "./file-system.js";
15
+ import { ROOT_TRANSACTION_NAME, HOSTED_WRITER_NAME } from "./root-output.js";
6
16
 
7
17
  const STATE_FORMAT = "firstdraft.cli-state/1";
8
18
  export const MAX_STATE_BYTES = 4096;
@@ -22,6 +32,7 @@ const DEFAULT_FILE_SYSTEM = { lstatSync, readFileSync };
22
32
 
23
33
  export class PlanStateConfigurationError extends Error {}
24
34
  export class PlanStateLocalError extends Error {}
35
+ export class PlanStateBusyError extends PlanStateLocalError {}
25
36
  export class PlanStateNotPushedError extends Error {}
26
37
 
27
38
  /**
@@ -53,7 +64,7 @@ export function readPlanState({ cwd, fileSystem = DEFAULT_FILE_SYSTEM }) {
53
64
  export function readPinnedProject({ cwd, fileSystem }) {
54
65
  const projectDirectory = pinnedProjectDirectory(cwd, fileSystem);
55
66
  const state = readPlanState({ cwd: projectDirectory, fileSystem });
56
- if (state.api_url === undefined) {
67
+ if (state.api_url === undefined || state.foundation_plan_etag === undefined) {
57
68
  throw new PlanStateNotPushedError(
58
69
  "The local Foundation Plan has not been pushed.",
59
70
  );
@@ -331,7 +342,11 @@ export function isUuidV7(value) {
331
342
  * @param {number} maximumBytes
332
343
  * @param {PlanStateFileSystem} fileSystem
333
344
  */
334
- export function readLocalFile(filePath, maximumBytes, fileSystem) {
345
+ export function readLocalFile(
346
+ filePath,
347
+ maximumBytes,
348
+ fileSystem = DEFAULT_FILE_SYSTEM,
349
+ ) {
335
350
  try {
336
351
  const stat = fileSystem.lstatSync(filePath);
337
352
  if (!stat.isFile() || stat.size > maximumBytes) {
@@ -402,9 +417,15 @@ function parsePlanState(source) {
402
417
  const keys = Object.keys(state).sort();
403
418
  const hasRemoteState =
404
419
  state.api_url !== undefined || state.foundation_plan_etag !== undefined;
405
- const expectedKeys = hasRemoteState
406
- ? ["api_url", "format", "foundation_plan_etag", "project_id"]
407
- : ["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();
408
429
  let storedApiUrl;
409
430
 
410
431
  if (typeof state.api_url === "string") {
@@ -420,6 +441,7 @@ function parsePlanState(source) {
420
441
  }
421
442
 
422
443
  if (
444
+ (state.reserved === true && !storedApiUrl) ||
423
445
  !arraysEqual(keys, expectedKeys) ||
424
446
  state.format !== STATE_FORMAT ||
425
447
  !isUuidV7(state.project_id) ||
@@ -431,6 +453,7 @@ function parsePlanState(source) {
431
453
  }
432
454
 
433
455
  return {
456
+ ...(state.reserved === true ? { reserved: true } : {}),
434
457
  format: state.format,
435
458
  project_id: state.project_id,
436
459
  ...(storedApiUrl ? { api_url: storedApiUrl } : {}),
@@ -461,3 +484,51 @@ function arraysEqual(left, right) {
461
484
  left.every((value, index) => value === right[index])
462
485
  );
463
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
+ }