@firstdraft.com/cli 0.2.0 → 0.2.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.
@@ -1,4 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { lstatSync, readFileSync } from "node:fs";
3
+ import path from "node:path";
2
4
 
3
5
  import {
4
6
  ARTIFACT_MEDIA_TYPE,
@@ -8,6 +10,8 @@ import {
8
10
  MAX_ARTIFACT_BYTES,
9
11
  materializeCompilationArtifact,
10
12
  parseCompilationArtifact,
13
+ prepareCompilationOutputTarget,
14
+ releaseCompilationOutputTarget,
11
15
  resolveOutputTarget,
12
16
  } from "../compilation-artifact.js";
13
17
  import {
@@ -19,8 +23,9 @@ import {
19
23
  responseMediaType,
20
24
  sendRequest,
21
25
  } from "../api-response.js";
22
- import { isUuidV7, readPlanState } from "../plan-state.js";
26
+ import { isUuidV7, readLocalFile, readPlanState } from "../plan-state.js";
23
27
 
28
+ const MAX_PLAN_BYTES = 1024 * 1024;
24
29
  const REQUEST_TIMEOUT_MS = 30_000;
25
30
  const WAIT_TIMEOUT_MS = 10 * 60_000;
26
31
  const POLL_INTERVAL_MS = 1_000;
@@ -57,8 +62,50 @@ const SHA256_PATTERN = /^[0-9a-f]{64}$/;
57
62
  const RELEASE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
58
63
  const MAX_IDENTIFIER_BYTES = 256;
59
64
  const MAX_FAILURE_MESSAGE_BYTES = 4_096;
65
+ const HEAD_ETAG_PATTERN = /^"sha256:([0-9a-f]{64})"$/;
66
+
67
+ /** @type {import("../plan-state.js").PlanStateFileSystem} */
68
+ const DEFAULT_FILE_SYSTEM = { lstatSync, readFileSync };
60
69
 
61
70
  export class CompilationNotPushedError extends Error {}
71
+ export class CompilationLocalStateError extends Error {}
72
+ export class CompilationLocalPlanChangedError extends Error {}
73
+
74
+ export class CompilationRequestOutcomeUnknownError extends Error {
75
+ /**
76
+ * @param {number | undefined} status
77
+ * @param {Record<string, unknown> | null} [response]
78
+ */
79
+ constructor(status, response = null) {
80
+ super("The compilation start request outcome is unknown.");
81
+ this.status = status;
82
+ this.response = response;
83
+ }
84
+ }
85
+
86
+ export class CompilationRetainedError extends Error {
87
+ /**
88
+ * @param {Error} error
89
+ * @param {CompilationResponse} current
90
+ */
91
+ constructor(error, current) {
92
+ super("The retained Compilation requires recovery.", { cause: error });
93
+ this.error = error;
94
+ this.current = current;
95
+ }
96
+ }
97
+
98
+ export class CompilationStartRejectedError extends Error {
99
+ /**
100
+ * @param {number} status
101
+ * @param {Record<string, unknown>} response
102
+ */
103
+ constructor(status, response) {
104
+ super("First Draft rejected the compilation start request.");
105
+ this.status = status;
106
+ this.response = response;
107
+ }
108
+ }
62
109
 
63
110
  export class CompilationStatusUnavailableError extends Error {
64
111
  /**
@@ -106,6 +153,22 @@ export class CompilationNotSucceededError extends Error {
106
153
  }
107
154
  }
108
155
 
156
+ export class CompilationFailedError extends Error {
157
+ /** @param {CompilationResponse} current */
158
+ constructor(current) {
159
+ super("The compilation failed.");
160
+ this.current = current;
161
+ }
162
+ }
163
+
164
+ export class CompilationCancelledError extends Error {
165
+ /** @param {CompilationResponse} current */
166
+ constructor(current) {
167
+ super("The compilation was cancelled.");
168
+ this.current = current;
169
+ }
170
+ }
171
+
109
172
  export class CompilationArtifactUnavailableError extends Error {
110
173
  /**
111
174
  * @param {number | undefined} status
@@ -251,42 +314,247 @@ export async function downloadCompilation({
251
314
  createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
252
315
  }) {
253
316
  const context = readContext({ cwd, compilationId, fileSystem });
254
- const outputTarget = resolveOutputTarget({ cwd, output });
255
- const current = await readCompilationStatus({
256
- ...context,
257
- fetchFunction,
258
- createRequestSignal,
259
- requestTimeout: REQUEST_TIMEOUT_MS,
260
- });
261
- if (current.compilation.status !== "succeeded") {
262
- throw new CompilationNotSucceededError(current);
317
+ const outputTarget = prepareCompilationOutputTarget({ cwd, output });
318
+ try {
319
+ const current = await readCompilationStatus({
320
+ ...context,
321
+ fetchFunction,
322
+ createRequestSignal,
323
+ requestTimeout: REQUEST_TIMEOUT_MS,
324
+ });
325
+ if (current.compilation.status !== "succeeded") {
326
+ throw new CompilationNotSucceededError(current);
327
+ }
328
+
329
+ const metadata =
330
+ /** @type {{path: string, sha256: string, media_type: string, byte_size: number}} */ (
331
+ current.compilation.artifact
332
+ );
333
+ const source = await downloadArtifact({
334
+ apiUrl: context.apiUrl,
335
+ metadata,
336
+ fetchFunction,
337
+ createRequestSignal,
338
+ });
339
+ const artifact = parseCompilationArtifact(source, {
340
+ projectId: context.projectId,
341
+ compilationId: current.compilation.id,
342
+ graphVersion: current.compilation.graph_version,
343
+ headSourceSha256: current.compilation.head_source_sha256,
344
+ analysisRunId: current.compilation.analysis_run_id,
345
+ compilerRelease: current.compilation.compiler_release,
346
+ target: current.compilation.target,
347
+ });
348
+ const materialized = materializeCompilationArtifact(artifact, outputTarget);
349
+
350
+ return {
351
+ project: current.project,
352
+ compilation: current.compilation,
353
+ output: materialized,
354
+ };
355
+ } finally {
356
+ releaseCompilationOutputTarget(outputTarget);
263
357
  }
358
+ }
264
359
 
265
- const metadata =
266
- /** @type {{path: string, sha256: string, media_type: string, byte_size: number}} */ (
267
- current.compilation.artifact
360
+ /**
361
+ * @typedef {object} CurrentCompilationIdentity
362
+ * @property {string} projectId
363
+ * @property {number} graphVersion
364
+ * @property {string} headSourceSha256
365
+ * @property {string} analysisRunId
366
+ * @property {string} compilerRelease
367
+ * @property {{id: string, profile: string}} target
368
+ */
369
+
370
+ /**
371
+ * @typedef {object} CompileAndDownloadOptions
372
+ * @property {string} cwd
373
+ * @property {string} expectedEtag
374
+ * @property {CurrentCompilationIdentity} expected
375
+ * @property {string} output
376
+ * @property {string | import("../root-output.js").RootOutputTarget} [outputTarget]
377
+ * @property {typeof globalThis.fetch} [fetchFunction]
378
+ * @property {import("../plan-state.js").PlanStateFileSystem} [fileSystem]
379
+ * @property {(timeoutMs: number) => AbortSignal} [createRequestSignal]
380
+ * @property {(delayMs: number) => Promise<void>} [sleep]
381
+ * @property {() => number} [now]
382
+ * @property {(progress: import("../plan-compile-progress.js").PlanCompileProgress) => void} [onProgress]
383
+ */
384
+
385
+ /**
386
+ * Start one Compilation for the exact Plan and reviewed Analysis accepted by
387
+ * the current command, wait for that retained Compilation, and materialize its
388
+ * authenticated artifact into an absent destination or the eligible current
389
+ * directory.
390
+ *
391
+ * @param {CompileAndDownloadOptions} options
392
+ */
393
+ export async function compileAndDownload({
394
+ cwd,
395
+ expectedEtag,
396
+ expected,
397
+ output,
398
+ outputTarget: suppliedOutputTarget,
399
+ fetchFunction = globalThis.fetch,
400
+ fileSystem = DEFAULT_FILE_SYSTEM,
401
+ createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
402
+ sleep = sleepFor,
403
+ now = Date.now,
404
+ onProgress = () => {},
405
+ }) {
406
+ const ownsOutputTarget = suppliedOutputTarget === undefined;
407
+ const outputTarget =
408
+ suppliedOutputTarget ?? prepareCompilationOutputTarget({ cwd, output });
409
+ try {
410
+ const context = readStartContext({
411
+ cwd,
412
+ expectedEtag,
413
+ expected,
414
+ fileSystem,
415
+ });
416
+ if (
417
+ suppliedOutputTarget !== undefined &&
418
+ typeof outputTarget === "string"
419
+ ) {
420
+ resolveOutputTarget({ cwd, output });
421
+ }
422
+ const deadline = now() + WAIT_TIMEOUT_MS;
423
+
424
+ onProgress({ phase: "compilation", status: "waiting" });
425
+ const initial = await startCompilation({
426
+ ...context,
427
+ expected,
428
+ fetchFunction,
429
+ createRequestSignal,
430
+ });
431
+ let current = initial;
432
+
433
+ try {
434
+ while (!TERMINAL_STATUSES.has(current.compilation.status)) {
435
+ const remaining = deadline - now();
436
+ if (remaining <= 0) throw new CompilationTimeoutError(current);
437
+
438
+ await sleep(Math.min(POLL_INTERVAL_MS, remaining));
439
+ if (now() >= deadline) throw new CompilationTimeoutError(current);
440
+
441
+ const next = await readCompilationStatus({
442
+ apiUrl: context.apiUrl,
443
+ projectId: context.projectId,
444
+ compilationId: initial.compilation.id,
445
+ fetchFunction,
446
+ createRequestSignal,
447
+ requestTimeout: Math.max(
448
+ 1,
449
+ Math.min(REQUEST_TIMEOUT_MS, deadline - now()),
450
+ ),
451
+ });
452
+ if (
453
+ !sameCompilation(initial, next) ||
454
+ !validTransition(current, next)
455
+ ) {
456
+ throw new CompilationChangedError(next);
457
+ }
458
+ current = next;
459
+ }
460
+
461
+ if (current.compilation.status === "failed") {
462
+ throw new CompilationFailedError(current);
463
+ }
464
+ if (current.compilation.status === "cancelled") {
465
+ throw new CompilationCancelledError(current);
466
+ }
467
+
468
+ onProgress({ phase: "compilation", status: "succeeded" });
469
+ const metadata =
470
+ /** @type {{path: string, sha256: string, media_type: string, byte_size: number}} */ (
471
+ current.compilation.artifact
472
+ );
473
+ const source = await downloadArtifact({
474
+ apiUrl: context.apiUrl,
475
+ metadata,
476
+ fetchFunction,
477
+ createRequestSignal,
478
+ });
479
+ const artifact = parseCompilationArtifact(source, {
480
+ projectId: context.projectId,
481
+ compilationId: current.compilation.id,
482
+ graphVersion: current.compilation.graph_version,
483
+ headSourceSha256: current.compilation.head_source_sha256,
484
+ analysisRunId: current.compilation.analysis_run_id,
485
+ compilerRelease: current.compilation.compiler_release,
486
+ target: current.compilation.target,
487
+ });
488
+ const materialized = materializeCompilationArtifact(
489
+ artifact,
490
+ outputTarget,
491
+ );
492
+
493
+ return {
494
+ project: current.project,
495
+ compilation: current.compilation,
496
+ output: materialized,
497
+ };
498
+ } catch (error) {
499
+ if (requiresRetainedRecovery(error)) {
500
+ throw new CompilationRetainedError(error, current);
501
+ }
502
+
503
+ throw error;
504
+ }
505
+ } finally {
506
+ if (ownsOutputTarget) releaseCompilationOutputTarget(outputTarget);
507
+ }
508
+ }
509
+
510
+ /**
511
+ * @param {object} options
512
+ * @param {string} options.cwd
513
+ * @param {string} options.expectedEtag
514
+ * @param {CurrentCompilationIdentity} options.expected
515
+ * @param {import("../plan-state.js").PlanStateFileSystem} options.fileSystem
516
+ */
517
+ function readStartContext({ cwd, expectedEtag, expected, fileSystem }) {
518
+ const state = readPlanState({ cwd, fileSystem });
519
+ if (state.api_url === undefined || state.foundation_plan_etag === undefined) {
520
+ throw new CompilationNotPushedError(
521
+ "The local Foundation Plan has not been pushed.",
268
522
  );
269
- const source = await downloadArtifact({
270
- apiUrl: context.apiUrl,
271
- metadata,
272
- fetchFunction,
273
- createRequestSignal,
274
- });
275
- const artifact = parseCompilationArtifact(source, {
276
- projectId: context.projectId,
277
- compilationId: current.compilation.id,
278
- graphVersion: current.compilation.graph_version,
279
- headSourceSha256: current.compilation.head_source_sha256,
280
- analysisRunId: current.compilation.analysis_run_id,
281
- compilerRelease: current.compilation.compiler_release,
282
- target: current.compilation.target,
283
- });
284
- const materialized = materializeCompilationArtifact(artifact, outputTarget);
523
+ }
524
+ if (
525
+ state.project_id !== expected.projectId ||
526
+ state.foundation_plan_etag !== expectedEtag
527
+ ) {
528
+ throw new CompilationLocalPlanChangedError(
529
+ "Local Plan state changed after this command accepted its Plan.",
530
+ );
531
+ }
532
+
533
+ const match = HEAD_ETAG_PATTERN.exec(expectedEtag);
534
+ if (match === null) {
535
+ throw new CompilationLocalStateError(
536
+ "The saved Foundation Plan ETag cannot identify its accepted source.",
537
+ );
538
+ }
539
+ const headSourceSha256 = match[1] ?? "";
540
+ const planSource = readLocalFile(
541
+ path.join(cwd, ".firstdraft", "foundation-plan.json"),
542
+ MAX_PLAN_BYTES,
543
+ fileSystem,
544
+ );
545
+ if (
546
+ headSourceSha256 !== expected.headSourceSha256 ||
547
+ sha256(planSource) !== headSourceSha256
548
+ ) {
549
+ throw new CompilationLocalPlanChangedError(
550
+ "The local Foundation Plan differs from the accepted Plan.",
551
+ );
552
+ }
285
553
 
286
554
  return {
287
- project: current.project,
288
- compilation: current.compilation,
289
- output: materialized,
555
+ apiUrl: state.api_url,
556
+ projectId: state.project_id,
557
+ etag: expectedEtag,
290
558
  };
291
559
  }
292
560
 
@@ -315,6 +583,73 @@ function readContext({ cwd, compilationId, fileSystem }) {
315
583
  };
316
584
  }
317
585
 
586
+ /**
587
+ * @param {object} options
588
+ * @param {string} options.apiUrl
589
+ * @param {string} options.projectId
590
+ * @param {string} options.etag
591
+ * @param {CurrentCompilationIdentity} options.expected
592
+ * @param {typeof globalThis.fetch} options.fetchFunction
593
+ * @param {(timeoutMs: number) => AbortSignal} options.createRequestSignal
594
+ */
595
+ async function startCompilation({
596
+ apiUrl,
597
+ projectId,
598
+ etag,
599
+ expected,
600
+ fetchFunction,
601
+ createRequestSignal,
602
+ }) {
603
+ const endpoint = new URL(`/v1/projects/${projectId}/compilations`, apiUrl);
604
+ let response;
605
+ let body;
606
+ try {
607
+ response = await sendRequest(fetchFunction, endpoint, {
608
+ method: "POST",
609
+ headers: {
610
+ Accept: "application/json, application/problem+json",
611
+ "If-Match": etag,
612
+ },
613
+ redirect: "error",
614
+ signal: createRequestSignal(REQUEST_TIMEOUT_MS),
615
+ });
616
+ body = await readResponseBody(response);
617
+ } catch (error) {
618
+ if (
619
+ error instanceof FirstDraftNetworkError ||
620
+ error instanceof FirstDraftProtocolError
621
+ ) {
622
+ throw new CompilationRequestOutcomeUnknownError(error.status);
623
+ }
624
+
625
+ throw error;
626
+ }
627
+
628
+ if (response.status !== 202) {
629
+ const problem = safeProblem(response, body);
630
+ if (response.ok || problem === null) {
631
+ throw new CompilationRequestOutcomeUnknownError(response.status);
632
+ }
633
+ if (response.status === 408 || response.status >= 500) {
634
+ throw new CompilationRequestOutcomeUnknownError(response.status, problem);
635
+ }
636
+
637
+ throw new CompilationStartRejectedError(response.status, problem);
638
+ }
639
+
640
+ const parsed = parseStartedCompilationResponse(body, projectId);
641
+ if (
642
+ responseMediaType(response) !== "application/json" ||
643
+ parsed === null ||
644
+ response.headers.get("location") !== parsed.compilation.status_path ||
645
+ !matchesExpectedCompilation(parsed, expected)
646
+ ) {
647
+ throw new CompilationRequestOutcomeUnknownError(response.status);
648
+ }
649
+
650
+ return parsed;
651
+ }
652
+
318
653
  /**
319
654
  * @param {object} options
320
655
  * @param {string} options.apiUrl
@@ -377,6 +712,40 @@ async function readCompilationStatus({
377
712
  return parsed;
378
713
  }
379
714
 
715
+ /**
716
+ * @param {unknown} value
717
+ * @param {string} projectId
718
+ * @returns {CompilationResponse | null}
719
+ */
720
+ function parseStartedCompilationResponse(value, projectId) {
721
+ if (
722
+ !hasExactKeySet(value, RESPONSE_KEYS) ||
723
+ !hasExactKeySet(value.compilation, COMPILATION_KEYS) ||
724
+ !isUuidV7(value.compilation.id)
725
+ ) {
726
+ return null;
727
+ }
728
+
729
+ return parseCompilationResponse(value, projectId, value.compilation.id);
730
+ }
731
+
732
+ /**
733
+ * @param {CompilationResponse} current
734
+ * @param {CurrentCompilationIdentity} expected
735
+ */
736
+ function matchesExpectedCompilation(current, expected) {
737
+ return (
738
+ current.project.id === expected.projectId &&
739
+ current.project.graph_version === expected.graphVersion &&
740
+ current.compilation.graph_version === expected.graphVersion &&
741
+ current.compilation.head_source_sha256 === expected.headSourceSha256 &&
742
+ current.compilation.analysis_run_id === expected.analysisRunId &&
743
+ current.compilation.compiler_release === expected.compilerRelease &&
744
+ current.compilation.target.id === expected.target.id &&
745
+ current.compilation.target.profile === expected.target.profile
746
+ );
747
+ }
748
+
380
749
  /**
381
750
  * @param {object} options
382
751
  * @param {string} options.apiUrl
@@ -700,6 +1069,18 @@ function validTransition(previous, current) {
700
1069
  );
701
1070
  }
702
1071
 
1072
+ /** @param {unknown} error */
1073
+ function requiresRetainedRecovery(error) {
1074
+ return (
1075
+ error instanceof CompilationStatusUnavailableError ||
1076
+ error instanceof CompilationStatusInvalidError ||
1077
+ error instanceof CompilationArtifactUnavailableError ||
1078
+ error instanceof CompilationArtifactResponseInvalidError ||
1079
+ error instanceof CompilationArtifactInvalidError ||
1080
+ error instanceof CompilationMaterializationError
1081
+ );
1082
+ }
1083
+
703
1084
  /** @param {Response} response @param {unknown} body */
704
1085
  function safeProblem(response, body) {
705
1086
  if (!isRecord(body) || !isProblemBody(response, body)) return null;
@@ -1,4 +1,9 @@
1
1
  import { publishPlan } from "./plan-publish.js";
2
+ import { compileAndDownload } from "./compilation.js";
3
+ import {
4
+ prepareCompilationOutputTarget,
5
+ releaseCompilationOutputTarget,
6
+ } from "../compilation-artifact.js";
2
7
  import {
3
8
  PlanPushNetworkError,
4
9
  PlanPushProtocolError,
@@ -90,6 +95,124 @@ export async function compilePlan({
90
95
  push = pushPlan,
91
96
  readStatus = readPlanStatus,
92
97
  publish = publishPlan,
98
+ }) {
99
+ const prepared = await preparePlan({
100
+ cwd,
101
+ apiUrl,
102
+ fetchFunction,
103
+ fileSystem,
104
+ createTemporaryId,
105
+ createRequestSignal,
106
+ analysisSleep,
107
+ analysisNow,
108
+ onProgress,
109
+ push,
110
+ readStatus,
111
+ });
112
+
113
+ return publish({
114
+ cwd,
115
+ fetchFunction,
116
+ fileSystem,
117
+ createRequestSignal,
118
+ sleep: publicationSleep,
119
+ now: publicationNow,
120
+ expectedEtag: prepared.pushed.etag,
121
+ onProgress,
122
+ });
123
+ }
124
+
125
+ /**
126
+ * @typedef {CompilePlanOptions & {
127
+ * output: string,
128
+ * compilationSleep?: (delayMs: number) => Promise<void>,
129
+ * compilationNow?: () => number,
130
+ * compile?: typeof compileAndDownload
131
+ * }} CompilePlanToDirectoryOptions
132
+ */
133
+
134
+ /**
135
+ * Submit and analyze the exact current local Plan, then start one direct
136
+ * Compilation and materialize its verified artifact into an absent directory
137
+ * or the eligible current directory. GitHub Publication remains the no-output
138
+ * mode owned by compilePlan.
139
+ *
140
+ * @param {CompilePlanToDirectoryOptions} options
141
+ */
142
+ export async function compilePlanToDirectory({
143
+ cwd,
144
+ output,
145
+ apiUrl,
146
+ fetchFunction,
147
+ fileSystem,
148
+ createTemporaryId,
149
+ createRequestSignal,
150
+ analysisSleep,
151
+ analysisNow,
152
+ compilationSleep,
153
+ compilationNow,
154
+ onProgress = () => {},
155
+ push = pushPlan,
156
+ readStatus = readPlanStatus,
157
+ compile = compileAndDownload,
158
+ }) {
159
+ const outputTarget = prepareCompilationOutputTarget({ cwd, output });
160
+ try {
161
+ const prepared = await preparePlan({
162
+ cwd,
163
+ apiUrl,
164
+ fetchFunction,
165
+ fileSystem,
166
+ createTemporaryId,
167
+ createRequestSignal,
168
+ analysisSleep,
169
+ analysisNow,
170
+ onProgress,
171
+ push,
172
+ readStatus,
173
+ });
174
+ const body = prepared.status.body;
175
+
176
+ return await compile({
177
+ cwd,
178
+ expectedEtag: prepared.pushed.etag,
179
+ expected: {
180
+ projectId: body.project.id,
181
+ graphVersion: body.project.graph_version,
182
+ headSourceSha256: body.analysis.head_source_sha256,
183
+ analysisRunId: body.analysis.id,
184
+ compilerRelease: body.analysis.compiler_release,
185
+ target: body.analysis.target,
186
+ },
187
+ output,
188
+ outputTarget,
189
+ fetchFunction,
190
+ fileSystem,
191
+ createRequestSignal,
192
+ sleep: compilationSleep,
193
+ now: compilationNow,
194
+ onProgress,
195
+ });
196
+ } finally {
197
+ releaseCompilationOutputTarget(outputTarget);
198
+ }
199
+ }
200
+
201
+ /**
202
+ * @param {Omit<CompilePlanOptions, "publicationSleep" | "publicationNow" | "publish">} options
203
+ */
204
+ async function preparePlan({
205
+ cwd,
206
+ apiUrl,
207
+ fetchFunction,
208
+ fileSystem,
209
+ createTemporaryId,
210
+ createRequestSignal,
211
+ analysisSleep,
212
+ analysisNow,
213
+ onProgress = () => {},
214
+ push = pushPlan,
215
+ readStatus = readPlanStatus,
93
216
  }) {
94
217
  const pushed = await push({
95
218
  cwd,
@@ -146,14 +269,5 @@ export async function compilePlan({
146
269
  }
147
270
  onProgress({ phase: "analysis", status: "valid" });
148
271
 
149
- return publish({
150
- cwd,
151
- fetchFunction,
152
- fileSystem,
153
- createRequestSignal,
154
- sleep: publicationSleep,
155
- now: publicationNow,
156
- expectedEtag: pushed.etag,
157
- onProgress,
158
- });
272
+ return { pushed, status };
159
273
  }