@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.
package/src/cli.js CHANGED
@@ -94,6 +94,11 @@ import {
94
94
  resolveMaintenanceItem,
95
95
  showMaintenanceItem,
96
96
  } from "./commands/maintain.js";
97
+ import {
98
+ startProject,
99
+ publishSketches,
100
+ SketchError,
101
+ } from "./commands/sketches.js";
97
102
  import { initializePlan } from "./commands/plan-init.js";
98
103
  import {
99
104
  PlanPushConfigurationError,
@@ -136,6 +141,7 @@ import { storedTokenReader } from "./credentials.js";
136
141
  import { isFileSystemError } from "./file-system.js";
137
142
  import { createPlanCompileProgressReporter } from "./plan-compile-progress.js";
138
143
  import {
144
+ PlanStateBusyError,
139
145
  CompilationNotRecordedError,
140
146
  CompilationRecordWriteError,
141
147
  PlanStateNotPushedError,
@@ -173,6 +179,8 @@ Commands:
173
179
  maintain List, inspect, and act on a deployed application's items
174
180
  note Send a note about a problem with First Draft
175
181
  plan Work with Foundation Plans
182
+ project Start or reopen a hosted Project
183
+ sketches Publish a board and its working Foundation Plan
176
184
  report Send a progress or failure report to First Draft
177
185
  start Check versions, login, and reports before other work
178
186
 
@@ -483,11 +491,13 @@ const PLAN_COMPILE_HELP = `First Draft CLI
483
491
 
484
492
  Usage:
485
493
  firstdraft plan compile
494
+ firstdraft plan compile --revision <approved-sketch-revision>
486
495
  firstdraft plan compile --output <absent-directory|.>
487
496
 
488
497
  Options:
489
498
  --staging Use staging; reject a different saved origin
490
499
  --output <absent-directory|.> Materialize here (default: .)
500
+ --revision <approved-id> Compile the approved Sketches revision
491
501
  -h, --help Show help
492
502
 
493
503
  Environment:
@@ -495,8 +505,9 @@ Environment:
495
505
  FIRSTDRAFT_STAGING_API_TOKEN Authenticate staging.firstdraft.com
496
506
  FIRSTDRAFT_API_URL Override the initial API origin
497
507
 
498
- The command submits the exact current whole-file Plan, waits for its analysis,
499
- and proceeds only when that analysis is valid. By default it materializes the
508
+ In a Plan-only Project, the command pushes the exact local Plan. With --revision,
509
+ it verifies the local sources against the published review. Both paths require
510
+ a valid analysis of the accepted Plan. By default the command materializes the
500
511
  verified application in the current directory, preserving existing root material
501
512
  under .firstdraft/design. --output can select another absent directory.
502
513
  Progress is written to stderr.
@@ -861,7 +872,7 @@ const COMPILATION_CANCEL_INVALID_ARGUMENTS_DETAIL =
861
872
  const COMPILATION_LOCAL_INPUT_UNREADABLE_DETAIL =
862
873
  "Could not read valid local First Draft state. No network request was made.";
863
874
  const COMPILATION_NOT_PUSHED_DETAIL =
864
- "The local Project has no pinned API origin. Run 'firstdraft plan push' first.";
875
+ "The local Project has no accepted Plan. Run 'firstdraft plan push' or publish its Sketches first.";
865
876
  const COMPILATION_STATUS_UNAVAILABLE_DETAIL =
866
877
  "Could not read the requested Compilation status. This read-only request is safe to retry.";
867
878
  const COMPILATION_STATUS_INVALID_DETAIL =
@@ -905,7 +916,7 @@ const MAINTAIN_ASK_OWNER_INVALID_ARGUMENTS_DETAIL =
905
916
  const MAINTAIN_LOCAL_INPUT_UNREADABLE_DETAIL =
906
917
  "Could not read valid local First Draft state. No network request was made. Run this command from the application's folder, where the CLI reads the Project from .firstdraft/gaps.json or from the state archived at .firstdraft/design, or from the directory whose .firstdraft holds the Project's state.";
907
918
  const MAINTAIN_NOT_PUSHED_DETAIL =
908
- "The local Project has no pinned API origin. Run 'firstdraft plan push' first.";
919
+ "The local Project has no accepted Plan. Run 'firstdraft plan push' or publish its Sketches first.";
909
920
  const MAINTAIN_REJECTED_DETAIL =
910
921
  "First Draft rejected the request; response.code says why. environment_not_found or item_not_found means First Draft found no such Environment or item for this Project and account. item_already_resolved means nothing changed.";
911
922
  const MAINTAIN_UNAVAILABLE_DETAIL =
@@ -955,7 +966,7 @@ const NOTE_ACCOUNT_INVALID_RESPONSE_DETAIL =
955
966
  const PINNED_LOCAL_INPUT_UNREADABLE_DETAIL =
956
967
  "Could not read valid local First Draft state, so nothing was sent. Run the command from the generated application's root after root adoption, or from the Project's directory.";
957
968
  const PINNED_NOT_PUSHED_DETAIL =
958
- "The local Project has no pinned API origin, so nothing was sent. Run 'firstdraft plan push' first.";
969
+ "The local Project has no accepted Plan, so nothing was sent. Run 'firstdraft plan push' or publish its Sketches first.";
959
970
 
960
971
  /**
961
972
  * @typedef {object} Writer
@@ -1157,6 +1168,23 @@ export async function run({
1157
1168
  });
1158
1169
  }
1159
1170
 
1171
+ if (argv[0] === "project" || argv[0] === "sketches") {
1172
+ return runSketchCommand({
1173
+ argv,
1174
+ stdout,
1175
+ stderr,
1176
+ cwd,
1177
+ getCwd,
1178
+ apiUrl,
1179
+ apiToken,
1180
+ stagingApiToken,
1181
+ fetchFunction,
1182
+ credentials,
1183
+ staging,
1184
+ service,
1185
+ });
1186
+ }
1187
+
1160
1188
  if (argv[0] === "generate") {
1161
1189
  return runGenerate({
1162
1190
  argv: argv.slice(1),
@@ -1689,6 +1717,13 @@ async function runCompilationDownload({
1689
1717
  writeJson(stdout, result);
1690
1718
  return 0;
1691
1719
  } catch (error) {
1720
+ if (error instanceof SketchError) {
1721
+ writeJson(stderr, {
1722
+ error: "sketch_review_failed",
1723
+ detail: error.message,
1724
+ });
1725
+ return 1;
1726
+ }
1692
1727
  const readStatus = writeCompilationReadError(stderr, error, false);
1693
1728
  if (readStatus !== null) return readStatus;
1694
1729
 
@@ -3052,7 +3087,10 @@ async function runPlanPush({
3052
3087
  if (error instanceof PlanPushLocalError) {
3053
3088
  writeJson(stderr, {
3054
3089
  error: "local_input_unreadable",
3055
- detail: PLAN_PUSH_LOCAL_INPUT_UNREADABLE_DETAIL,
3090
+ detail:
3091
+ error instanceof PlanStateBusyError
3092
+ ? error.message
3093
+ : PLAN_PUSH_LOCAL_INPUT_UNREADABLE_DETAIL,
3056
3094
  });
3057
3095
  return 1;
3058
3096
  }
@@ -3320,6 +3358,7 @@ async function runPlanCompile({
3320
3358
  options: {
3321
3359
  staging: { type: "boolean" },
3322
3360
  output: { type: "string" },
3361
+ revision: { type: "string" },
3323
3362
  help: { type: "boolean", short: "h" },
3324
3363
  },
3325
3364
  allowPositionals: false,
@@ -3342,7 +3381,10 @@ async function runPlanCompile({
3342
3381
  }
3343
3382
 
3344
3383
  const { output } = parsed.values;
3345
- if (output === "") {
3384
+ if (
3385
+ output === "" ||
3386
+ (parsed.values.revision !== undefined && !isUuidV7(parsed.values.revision))
3387
+ ) {
3346
3388
  writeJson(stderr, {
3347
3389
  error: "invalid_arguments",
3348
3390
  detail: PLAN_COMPILE_INVALID_ARGUMENTS_DETAIL,
@@ -3373,6 +3415,7 @@ async function runPlanCompile({
3373
3415
  compilePlanToDirectory({
3374
3416
  cwd,
3375
3417
  output: output ?? ".",
3418
+ revision: parsed.values.revision,
3376
3419
  apiUrl: authentication.apiUrl,
3377
3420
  fetchFunction: authentication.fetchFunction,
3378
3421
  fileSystem: planPushFileSystem,
@@ -3398,6 +3441,10 @@ async function runPlanCompile({
3398
3441
 
3399
3442
  /** @param {Writer} writer @param {unknown} error */
3400
3443
  function writePlanCompileError(writer, error) {
3444
+ if (error instanceof SketchError) {
3445
+ writeJson(writer, { error: "sketch_review_failed", detail: error.message });
3446
+ return 1;
3447
+ }
3401
3448
  const stopStatus = writeServiceStop(writer, error);
3402
3449
  if (stopStatus !== null) return stopStatus;
3403
3450
 
@@ -3417,7 +3464,10 @@ function writePlanCompileError(writer, error) {
3417
3464
  if (error instanceof PlanPushLocalError) {
3418
3465
  writeJson(writer, {
3419
3466
  error: "local_input_unreadable",
3420
- detail: PLAN_COMPILE_LOCAL_INPUT_UNREADABLE_DETAIL,
3467
+ detail:
3468
+ error instanceof PlanStateBusyError
3469
+ ? error.message
3470
+ : PLAN_COMPILE_LOCAL_INPUT_UNREADABLE_DETAIL,
3421
3471
  });
3422
3472
  return 1;
3423
3473
  }
@@ -3825,7 +3875,8 @@ function runPlanInit({
3825
3875
  fileSystem,
3826
3876
  });
3827
3877
  } catch (error) {
3828
- if (!isFileSystemError(error)) throw error;
3878
+ if (!isFileSystemError(error) && !(error instanceof PlanPushLocalError))
3879
+ throw error;
3829
3880
 
3830
3881
  writeJson(stderr, {
3831
3882
  error: "local_initialization_failed",
@@ -5059,3 +5110,146 @@ function safeDiagnosticSubject(value) {
5059
5110
  function isRecord(value) {
5060
5111
  return typeof value === "object" && value !== null && !Array.isArray(value);
5061
5112
  }
5113
+
5114
+ /** @param {ServiceCommandOptions} options */
5115
+ async function runSketchCommand({
5116
+ argv,
5117
+ stdout,
5118
+ stderr,
5119
+ cwd,
5120
+ getCwd,
5121
+ apiUrl,
5122
+ apiToken,
5123
+ stagingApiToken,
5124
+ fetchFunction,
5125
+ credentials,
5126
+ staging,
5127
+ service,
5128
+ }) {
5129
+ const start = argv[0] === "project";
5130
+ const subcommand = start ? "start" : "publish";
5131
+ const group = start ? "project" : "sketches";
5132
+ const command = `firstdraft ${group} ${subcommand}`;
5133
+ const help = `Usage: ${command} [--staging]${start ? "" : " [--after <revision> --head <sha256>]"}\n${start ? "Create or reopen this directory's hosted Project before drafting its Plan." : "Capture sketches/board.json and publish its screens with the local Foundation Plan."}\n`;
5134
+ if (argv[1] !== subcommand)
5135
+ return runCommandGroup(
5136
+ { argv: argv.slice(1), stdout, stderr },
5137
+ group,
5138
+ help,
5139
+ );
5140
+ const parsed = parseArguments(() =>
5141
+ parseArgs({
5142
+ args: argv.slice(2),
5143
+ options: {
5144
+ staging: { type: "boolean" },
5145
+ help: { type: "boolean", short: "h" },
5146
+ ...(!start
5147
+ ? {
5148
+ after: { type: /** @type {const} */ ("string") },
5149
+ head: { type: /** @type {const} */ ("string") },
5150
+ }
5151
+ : {}),
5152
+ },
5153
+ allowPositionals: false,
5154
+ tokens: true,
5155
+ strict: true,
5156
+ }),
5157
+ );
5158
+ if (
5159
+ !parsed ||
5160
+ repeatedValueOption(parsed.tokens) ||
5161
+ ((parsed.values.after !== undefined || parsed.values.head !== undefined) &&
5162
+ (start ||
5163
+ (parsed.values.after !== "none" && !isUuidV7(parsed.values.after)) ||
5164
+ typeof parsed.values.head !== "string" ||
5165
+ (parsed.values.head !== "none" &&
5166
+ !/^[a-f0-9]{64}$/.test(parsed.values.head))))
5167
+ ) {
5168
+ writeJson(stderr, {
5169
+ error: "invalid_arguments",
5170
+ detail: `Invalid arguments. Run '${command} --help' for usage.`,
5171
+ });
5172
+ return 2;
5173
+ }
5174
+ if (parsed.values.help) {
5175
+ stdout.write(help);
5176
+ return 0;
5177
+ }
5178
+ try {
5179
+ const auth = authenticateApiCommand({
5180
+ fetchFunction: service.fetch(fetchFunction),
5181
+ apiUrl,
5182
+ apiToken,
5183
+ stagingApiToken,
5184
+ staging: staging || parsed.values.staging,
5185
+ readStoredTokens: storedTokenReader(credentials),
5186
+ });
5187
+ if (!auth) {
5188
+ writeAuthenticationRequired(stderr);
5189
+ return 1;
5190
+ }
5191
+ const result = await service.settle(
5192
+ start
5193
+ ? startProject({ cwd: cwd ?? getCwd(), ...auth })
5194
+ : publishSketches({
5195
+ cwd: cwd ?? getCwd(),
5196
+ ...auth,
5197
+ after: parsed.values.after,
5198
+ head: parsed.values.head,
5199
+ }),
5200
+ );
5201
+ writeJson(stdout, result);
5202
+ return 0;
5203
+ } catch (error) {
5204
+ const stop = writeServiceStop(stderr, error);
5205
+ if (stop !== null) return stop;
5206
+ if (error instanceof ApiAuthenticationRequiredError) {
5207
+ writeAuthenticationRequired(stderr);
5208
+ return 1;
5209
+ }
5210
+ if (
5211
+ error instanceof SketchError &&
5212
+ isAuthenticationProblem(error.status, error.response)
5213
+ ) {
5214
+ writeAuthenticationRequired(
5215
+ stderr,
5216
+ error.status,
5217
+ /** @type {Record<string, unknown>} */ (error.response),
5218
+ );
5219
+ return 1;
5220
+ }
5221
+ if (error instanceof PlanPushConfigurationError) {
5222
+ writeJson(stderr, {
5223
+ error: "invalid_configuration",
5224
+ detail: error.message,
5225
+ });
5226
+ return 2;
5227
+ }
5228
+ if (error instanceof SyntaxError) {
5229
+ writeJson(stderr, {
5230
+ error: "sketch_review_failed",
5231
+ detail: "A local review or Plan file contains invalid JSON.",
5232
+ });
5233
+ return 1;
5234
+ }
5235
+ if (
5236
+ error instanceof SketchError ||
5237
+ error instanceof PlanPushLocalError ||
5238
+ error instanceof PlanPushNetworkError ||
5239
+ error instanceof PlanPushProtocolError ||
5240
+ isFileSystemError(error)
5241
+ ) {
5242
+ writeJson(stderr, {
5243
+ error: "sketch_review_failed",
5244
+ detail: isFileSystemError(error)
5245
+ ? "Could not read or save the local sketch files. Check the planning directory and retry."
5246
+ : error.message,
5247
+ ...(error instanceof SketchError && error.status
5248
+ ? { status: error.status, response: error.response }
5249
+ : {}),
5250
+ });
5251
+ return 1;
5252
+ }
5253
+ throw error;
5254
+ }
5255
+ }
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { lstatSync, readFileSync } from "node:fs";
3
+ import { reviewedSources, SketchError } from "./sketches.js";
3
4
  import path from "node:path";
4
5
 
5
6
  import {
@@ -19,6 +20,7 @@ import {
19
20
  FirstDraftProtocolError,
20
21
  SERVICE_ROUTES,
21
22
  isProblemBody,
23
+ reviewConflict,
22
24
  readResponseBody,
23
25
  readResponseBytes,
24
26
  responseMediaType,
@@ -223,6 +225,7 @@ export class CompilationArtifactResponseInvalidError extends Error {
223
225
  * analysis_run_id: string,
224
226
  * graph_version: number,
225
227
  * head_source_sha256: string,
228
+ * sketch_revision_id?:string,
226
229
  * status: string,
227
230
  * compiler_release: string,
228
231
  * target: {id: string, profile: string},
@@ -373,7 +376,21 @@ export async function downloadCompilation({
373
376
  compilerRelease: current.compilation.compiler_release,
374
377
  target: current.compilation.target,
375
378
  });
376
- const materialized = materializeCompilationArtifact(artifact, outputTarget);
379
+ const selected = current.compilation.sketch_revision_id
380
+ ? reviewedSources(cwd, current.compilation.sketch_revision_id, true)
381
+ : undefined;
382
+ if (
383
+ selected &&
384
+ selected.planSha256 !== current.compilation.head_source_sha256
385
+ )
386
+ throw new SketchError(
387
+ "The retained Compilation and local review identify different Plans.",
388
+ );
389
+ const materialized = materializeCompilationArtifact(
390
+ artifact,
391
+ outputTarget,
392
+ selected?.files,
393
+ );
377
394
 
378
395
  return {
379
396
  project: current.project,
@@ -474,6 +491,8 @@ export async function cancelCompilation({
474
491
  /**
475
492
  * @typedef {object} CompileAndDownloadOptions
476
493
  * @property {string} cwd
494
+ * @property {string} [revision]
495
+ * @property {Map<string,Buffer>} [sketchFiles]
477
496
  * @property {string} expectedEtag
478
497
  * @property {CurrentCompilationIdentity} expected
479
498
  * @property {string} output
@@ -497,6 +516,8 @@ export async function cancelCompilation({
497
516
  export async function compileAndDownload({
498
517
  cwd,
499
518
  expectedEtag,
519
+ revision,
520
+ sketchFiles,
500
521
  expected,
501
522
  output,
502
523
  outputTarget: suppliedOutputTarget,
@@ -528,6 +549,7 @@ export async function compileAndDownload({
528
549
  onProgress({ phase: "compilation", status: "waiting" });
529
550
  const initial = await startCompilation({
530
551
  ...context,
552
+ revision,
531
553
  expected,
532
554
  fetchFunction,
533
555
  createRequestSignal,
@@ -591,9 +613,21 @@ export async function compileAndDownload({
591
613
  compilerRelease: current.compilation.compiler_release,
592
614
  target: current.compilation.target,
593
615
  });
616
+ if (revision && typeof outputTarget !== "string") {
617
+ try {
618
+ reviewedSources(cwd, revision);
619
+ } catch (error) {
620
+ if (!(error instanceof SketchError)) throw error;
621
+ throw new CompilationMaterializationError(
622
+ "Restore the reviewed sources before adopting this directory.",
623
+ { cause: error, reason: "reviewed_sources_changed" },
624
+ );
625
+ }
626
+ }
594
627
  const materialized = materializeCompilationArtifact(
595
628
  artifact,
596
629
  outputTarget,
630
+ sketchFiles,
597
631
  );
598
632
 
599
633
  return {
@@ -676,7 +710,7 @@ function readContext({ cwd, compilationId, fileSystem }) {
676
710
  }
677
711
 
678
712
  const state = readPlanState({ cwd, fileSystem });
679
- if (state.api_url === undefined) {
713
+ if (state.api_url === undefined || state.foundation_plan_etag === undefined) {
680
714
  throw new CompilationNotPushedError(
681
715
  "The local Foundation Plan has not been pushed.",
682
716
  );
@@ -693,6 +727,7 @@ function readContext({ cwd, compilationId, fileSystem }) {
693
727
  * @param {object} options
694
728
  * @param {string} options.apiUrl
695
729
  * @param {string} options.projectId
730
+ * @param {string} [options.revision]
696
731
  * @param {string} options.etag
697
732
  * @param {CurrentCompilationIdentity} options.expected
698
733
  * @param {typeof globalThis.fetch} options.fetchFunction
@@ -702,6 +737,7 @@ async function startCompilation({
702
737
  apiUrl,
703
738
  projectId,
704
739
  etag,
740
+ revision,
705
741
  expected,
706
742
  fetchFunction,
707
743
  createRequestSignal,
@@ -716,6 +752,7 @@ async function startCompilation({
716
752
  headers: {
717
753
  Accept: "application/json, application/problem+json",
718
754
  "If-Match": etag,
755
+ ...(revision ? { "FirstDraft-Sketch-Revision": revision } : {}),
719
756
  },
720
757
  redirect: "error",
721
758
  signal: createRequestSignal(REQUEST_TIMEOUT_MS),
@@ -749,6 +786,7 @@ async function startCompilation({
749
786
  responseMediaType(response) !== "application/json" ||
750
787
  parsed === null ||
751
788
  response.headers.get("location") !== parsed.compilation.status_path ||
789
+ parsed.compilation.sketch_revision_id !== revision ||
752
790
  !matchesExpectedCompilation(parsed, expected)
753
791
  ) {
754
792
  throw new CompilationRequestOutcomeUnknownError(response.status);
@@ -826,7 +864,7 @@ async function readCompilationStatus({
826
864
  function parseStartedCompilationResponse(value, projectId) {
827
865
  if (
828
866
  !hasExactKeySet(value, RESPONSE_KEYS) ||
829
- !hasExactKeySet(value.compilation, COMPILATION_KEYS) ||
867
+ !isRecord(value.compilation) ||
830
868
  !isUuidV7(value.compilation.id)
831
869
  ) {
832
870
  return null;
@@ -939,7 +977,13 @@ function parseCompilationResponse(value, projectId, compilationId) {
939
977
  if (
940
978
  !hasExactKeySet(value, RESPONSE_KEYS) ||
941
979
  !hasExactKeySet(value.project, PROJECT_KEYS) ||
942
- !hasExactKeySet(value.compilation, COMPILATION_KEYS)
980
+ !isRecord(value.compilation) ||
981
+ !hasExactKeySet(
982
+ value.compilation,
983
+ Object.hasOwn(value.compilation, "sketch_revision_id")
984
+ ? [...COMPILATION_KEYS, "sketch_revision_id"]
985
+ : COMPILATION_KEYS,
986
+ )
943
987
  ) {
944
988
  return null;
945
989
  }
@@ -949,6 +993,8 @@ function parseCompilationResponse(value, projectId, compilationId) {
949
993
  if (
950
994
  project.id !== projectId ||
951
995
  !isGraphVersion(project.graph_version) ||
996
+ (compilation.sketch_revision_id !== undefined &&
997
+ !isUuidV7(compilation.sketch_revision_id)) ||
952
998
  compilation.id !== compilationId ||
953
999
  !isUuidV7(compilation.id) ||
954
1000
  !isUuidV7(compilation.analysis_run_id) ||
@@ -994,6 +1040,9 @@ function parseCompilationResponse(value, projectId, compilationId) {
994
1040
  project: { id: project.id, graph_version: project.graph_version },
995
1041
  compilation: {
996
1042
  id: compilation.id,
1043
+ ...(isUuidV7(compilation.sketch_revision_id)
1044
+ ? { sketch_revision_id: compilation.sketch_revision_id }
1045
+ : {}),
997
1046
  analysis_run_id: compilation.analysis_run_id,
998
1047
  graph_version: compilation.graph_version,
999
1048
  head_source_sha256: /** @type {string} */ (
@@ -1137,6 +1186,8 @@ function sameCompilation(first, current) {
1137
1186
  current.project.id === first.project.id &&
1138
1187
  current.project.graph_version === first.project.graph_version &&
1139
1188
  current.compilation.id === first.compilation.id &&
1189
+ current.compilation.sketch_revision_id ===
1190
+ first.compilation.sketch_revision_id &&
1140
1191
  current.compilation.analysis_run_id === first.compilation.analysis_run_id &&
1141
1192
  current.compilation.graph_version === first.compilation.graph_version &&
1142
1193
  current.compilation.head_source_sha256 ===
@@ -1195,8 +1246,9 @@ function requiresRetainedRecovery(error) {
1195
1246
 
1196
1247
  /** @param {Response} response @param {unknown} body */
1197
1248
  function safeProblem(response, body) {
1249
+ const conflict = reviewConflict(response, body);
1250
+ if (conflict) return conflict;
1198
1251
  if (!isRecord(body) || !isProblemBody(response, body)) return null;
1199
-
1200
1252
  return {
1201
1253
  ...(body.type === "about:blank" ? { type: body.type } : {}),
1202
1254
  title: body.title,
@@ -1,3 +1,5 @@
1
+ import { readPlanState } from "../plan-state.js";
2
+ import { reviewedSources } from "./sketches.js";
1
3
  import { compileAndDownload } from "./compilation.js";
2
4
  import {
3
5
  prepareCompilationOutputTarget,
@@ -7,6 +9,7 @@ import {
7
9
  PlanPushNetworkError,
8
10
  PlanPushProtocolError,
9
11
  pushPlan,
12
+ resolveApiUrl,
10
13
  } from "./plan-push.js";
11
14
  import { PlanStatusChangedError, readPlanStatus } from "./plan-status.js";
12
15
 
@@ -57,6 +60,7 @@ export class PlanCompileAnalysisInvalidError extends Error {
57
60
  /**
58
61
  * @typedef {object} CompilePlanOptions
59
62
  * @property {string} cwd
63
+ * @property {string} [reviewedDigest]
60
64
  * @property {string} [apiUrl]
61
65
  * @property {typeof globalThis.fetch} [fetchFunction]
62
66
  * @property {import("./plan-push.js").PlanPushFileSystem} [fileSystem]
@@ -72,6 +76,7 @@ export class PlanCompileAnalysisInvalidError extends Error {
72
76
  /**
73
77
  * @typedef {CompilePlanOptions & {
74
78
  * output: string,
79
+ * revision?: string,
75
80
  * compilationSleep?: (delayMs: number) => Promise<void>,
76
81
  * compilationNow?: () => number,
77
82
  * compile?: typeof compileAndDownload
@@ -88,6 +93,7 @@ export class PlanCompileAnalysisInvalidError extends Error {
88
93
  export async function compilePlanToDirectory({
89
94
  cwd,
90
95
  output,
96
+ revision,
91
97
  apiUrl,
92
98
  fetchFunction,
93
99
  fileSystem,
@@ -102,10 +108,14 @@ export async function compilePlanToDirectory({
102
108
  readStatus = readPlanStatus,
103
109
  compile = compileAndDownload,
104
110
  }) {
111
+ const reviewed = reviewedSources(cwd, revision);
112
+ if (reviewed)
113
+ resolveApiUrl(apiUrl, readPlanState({ cwd, fileSystem }).api_url);
105
114
  const outputTarget = prepareCompilationOutputTarget({ cwd, output });
106
115
  try {
107
116
  const prepared = await preparePlan({
108
117
  cwd,
118
+ reviewedDigest: reviewed?.planSha256,
109
119
  apiUrl,
110
120
  fetchFunction,
111
121
  fileSystem,
@@ -121,7 +131,8 @@ export async function compilePlanToDirectory({
121
131
 
122
132
  return await compile({
123
133
  cwd,
124
- expectedEtag: prepared.pushed.etag,
134
+ ...(reviewed ? { revision, sketchFiles: reviewed.files } : {}),
135
+ expectedEtag: prepared.etag,
125
136
  expected: {
126
137
  projectId: body.project.id,
127
138
  graphVersion: body.project.graph_version,
@@ -149,6 +160,7 @@ export async function compilePlanToDirectory({
149
160
  */
150
161
  async function preparePlan({
151
162
  cwd,
163
+ reviewedDigest,
152
164
  apiUrl,
153
165
  fetchFunction,
154
166
  fileSystem,
@@ -160,24 +172,32 @@ async function preparePlan({
160
172
  push = pushPlan,
161
173
  readStatus = readPlanStatus,
162
174
  }) {
163
- const pushed = await push({
164
- cwd,
165
- apiUrl,
166
- fetchFunction,
167
- fileSystem,
168
- createTemporaryId,
169
- createRequestSignal,
170
- });
171
- if (!("outcome" in pushed)) {
172
- throw new PlanCompilePushRejectedError(pushed);
173
- }
174
- const acceptedGraphVersion = /** @type {{graph_version: number}} */ (
175
- pushed.body.project
176
- ).graph_version;
177
- const acceptedHeadSourceSha256 = /** @type {{source_sha256: string}} */ (
178
- pushed.body.foundation_plan
179
- ).source_sha256;
175
+ let acceptedGraphVersion;
176
+ let acceptedHeadSourceSha256 = reviewedDigest;
177
+ let etag;
178
+ if (reviewedDigest) {
179
+ etag = '"sha256:' + reviewedDigest + '"';
180
+ } else {
181
+ const pushed = await push({
182
+ cwd,
183
+ apiUrl,
184
+ fetchFunction,
185
+ fileSystem,
186
+ createTemporaryId,
187
+ createRequestSignal,
188
+ });
189
+ if (!("outcome" in pushed)) {
190
+ throw new PlanCompilePushRejectedError(pushed);
191
+ }
192
+ acceptedGraphVersion = /** @type {{graph_version: number}} */ (
193
+ pushed.body.project
194
+ ).graph_version;
195
+ acceptedHeadSourceSha256 = /** @type {{source_sha256: string}} */ (
196
+ pushed.body.foundation_plan
197
+ ).source_sha256;
180
198
 
199
+ etag = pushed.etag;
200
+ }
181
201
  let status;
182
202
  onProgress({ phase: "analysis", status: "waiting" });
183
203
  try {
@@ -204,8 +224,9 @@ async function preparePlan({
204
224
  throw new PlanCompileAnalysisRejectedError(status);
205
225
  }
206
226
  if (
207
- status.body.project.graph_version !== acceptedGraphVersion ||
208
- status.body.analysis.graph_version !== acceptedGraphVersion ||
227
+ (acceptedGraphVersion !== undefined &&
228
+ (status.body.project.graph_version !== acceptedGraphVersion ||
229
+ status.body.analysis.graph_version !== acceptedGraphVersion)) ||
209
230
  status.body.analysis.head_source_sha256 !== acceptedHeadSourceSha256
210
231
  ) {
211
232
  throw new PlanStatusChangedError(status.body);
@@ -215,5 +236,5 @@ async function preparePlan({
215
236
  }
216
237
  onProgress({ phase: "analysis", status: "valid" });
217
238
 
218
- return { pushed, status };
239
+ return { etag, status };
219
240
  }
@@ -1,4 +1,5 @@
1
- import { mkdirSync, writeFileSync } from "node:fs";
1
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { readPlanState } from "../plan-state.js";
2
3
  import path from "node:path";
3
4
 
4
5
  import {
@@ -37,6 +38,18 @@ export function initializePlan({
37
38
  const directory = path.join(cwd, ".firstdraft");
38
39
  const writeOptions = { flag: "wx", mode: 0o600, flush: true };
39
40
 
41
+ if (
42
+ fileSystem === DEFAULT_FILE_SYSTEM &&
43
+ existsSync(path.join(directory, "state.json")) &&
44
+ readPlanState({ cwd }).reserved
45
+ ) {
46
+ fileSystem.writeFileSync(
47
+ path.join(directory, "foundation-plan.json"),
48
+ plan,
49
+ writeOptions,
50
+ );
51
+ return;
52
+ }
40
53
  fileSystem.mkdirSync(directory, { recursive: false, mode: 0o700 });
41
54
  fileSystem.writeFileSync(
42
55
  path.join(directory, ".gitignore"),