@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.
@@ -1,1146 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { lstatSync, readFileSync } from "node:fs";
3
- import path from "node:path";
4
-
5
- import { isAuthenticationProblem } from "../api-authentication.js";
6
- import {
7
- FirstDraftNetworkError,
8
- FirstDraftProtocolError,
9
- SERVICE_ROUTES,
10
- isProblemBody,
11
- readResponseBody,
12
- responseMediaType,
13
- sendRequest,
14
- serviceEndpoint,
15
- } from "../api-response.js";
16
- import { isUuidV7, readLocalFile, readPlanState } from "../plan-state.js";
17
-
18
- const MAX_PLAN_BYTES = 1024 * 1024;
19
- const REQUEST_TIMEOUT_MS = 30_000;
20
- const WAIT_TIMEOUT_MS = 10 * 60_000;
21
- const POLL_INTERVAL_MS = 1_000;
22
- const MAX_IDENTIFIER_BYTES = 256;
23
- const MAX_REPOSITORY_NAME_BYTES = 100;
24
- const MAX_LOGIN_BYTES = 39;
25
- const MAX_FAILURE_CODE_BYTES = 256;
26
- const HEAD_ETAG_PATTERN = /^"sha256:([0-9a-f]{64})"$/;
27
- const SHA256_PATTERN = /^[0-9a-f]{64}$/;
28
- const GIT_SHA_PATTERN = /^[0-9a-f]{40}$/;
29
- const RELEASE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
30
- const GITHUB_NAME_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
31
- const COMPILATION_STATUSES = new Set([
32
- "queued",
33
- "running",
34
- "succeeded",
35
- "failed",
36
- "cancelled",
37
- ]);
38
- const PUBLICATION_STATUSES = new Set([
39
- "compiling",
40
- "provisioning_repository",
41
- "repository_unknown",
42
- "publishing",
43
- "publication_unknown",
44
- "succeeded",
45
- "repository_conflict",
46
- "failed",
47
- "cancelled",
48
- ]);
49
- const TERMINAL_PUBLICATION_STATUSES = new Set([
50
- "succeeded",
51
- "repository_conflict",
52
- "failed",
53
- "cancelled",
54
- ]);
55
- const RESPONSE_KEYS = ["compilation", "project", "publication"];
56
- const PROJECT_KEYS = ["graph_version", "head_source_sha256", "id"];
57
- const COMPILATION_KEYS = [
58
- "analysis_run_id",
59
- "artifact",
60
- "compiler_release",
61
- "graph_version",
62
- "head_source_sha256",
63
- "id",
64
- "status",
65
- "target",
66
- ];
67
- const TARGET_KEYS = ["id", "profile"];
68
- const ARTIFACT_KEYS = ["file_count", "manifest_sha256", "sha256"];
69
- const PUBLICATION_KEYS = [
70
- "completed_at",
71
- "created_at",
72
- "failure",
73
- "id",
74
- "progress",
75
- "repository",
76
- "started_at",
77
- "status",
78
- ];
79
- const FAILURE_KEYS = ["code", "phase"];
80
- const PROGRESS_KEYS = ["phase", "reason_code", "retry_at", "retry_count"];
81
- const REPOSITORY_KEYS = [
82
- "commit_sha",
83
- "default_branch",
84
- "full_name",
85
- "html_url",
86
- "id",
87
- "owner",
88
- "private",
89
- "tree_sha",
90
- ];
91
- const OWNER_KEYS = ["id", "login", "type"];
92
- const PROGRESS_PHASES = new Set([
93
- "compiling",
94
- "preparing_repository",
95
- "github_preflight",
96
- "creating_repository",
97
- "preparing_repository_reconciliation",
98
- "reconciling_repository",
99
- "preparing_artifact",
100
- "publishing_artifact",
101
- "preparing_publication_reconciliation",
102
- "reconciling_publication",
103
- "completed",
104
- "failed",
105
- "cancelled",
106
- ]);
107
- const PROGRESS_REASON_CODES = new Set([
108
- "github.configuration_missing",
109
- "github.oauth_unavailable",
110
- "github.api_unavailable",
111
- "github.reauthorization_required",
112
- "github.account_mismatch",
113
- "github.installation_unavailable",
114
- "github.installation_not_ready",
115
- "github.preflight_unavailable",
116
- "github.preflight_unclassified",
117
- "github.preflight_unavailable.configuration",
118
- "github.preflight_unavailable.authorization",
119
- "github.preflight_unavailable.repository_client",
120
- "github.preflight_unavailable.artifact_preparation",
121
- "github.preflight_unavailable.installation_token",
122
- "github.preflight_unavailable.publication_preparation",
123
- "github.preflight_unavailable.repository_ref_client",
124
- ]);
125
- const MAX_PROGRESS_RETRY_COUNT = 7;
126
- const RETRY_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/;
127
-
128
- /**
129
- * @typedef {object} PlanPublishFileSystem
130
- * @property {typeof lstatSync} lstatSync
131
- * @property {typeof readFileSync} readFileSync
132
- */
133
-
134
- /** @type {PlanPublishFileSystem} */
135
- const DEFAULT_FILE_SYSTEM = { lstatSync, readFileSync };
136
-
137
- export class PublicationNotPushedError extends Error {}
138
- export class PublicationLocalStateError extends Error {}
139
- export class PublicationLocalPlanChangedError extends Error {}
140
-
141
- export class PublicationRequestOutcomeUnknownError extends Error {
142
- /**
143
- * @param {number | undefined} status
144
- * @param {Record<string, unknown> | null} [response]
145
- */
146
- constructor(status, response = null) {
147
- super("The publication request outcome is unknown.");
148
- this.status = status;
149
- this.response = response;
150
- }
151
- }
152
-
153
- export class PublicationStartRejectedError extends Error {
154
- /**
155
- * @param {number} status
156
- * @param {Record<string, unknown>} response
157
- */
158
- constructor(status, response) {
159
- super("First Draft rejected the publication request.");
160
- this.status = status;
161
- this.response = response;
162
- }
163
- }
164
-
165
- export class PublicationStatusUnavailableError extends Error {
166
- /**
167
- * @param {number | undefined} status
168
- * @param {Record<string, unknown> | null} [response]
169
- */
170
- constructor(status, response = null) {
171
- super("The publication status is unavailable.");
172
- this.status = status;
173
- this.response = response;
174
- }
175
- }
176
-
177
- export class PublicationStatusInvalidError extends Error {
178
- /** @param {number} status */
179
- constructor(status) {
180
- super("The publication status response is invalid.");
181
- this.status = status;
182
- }
183
- }
184
-
185
- export class PublicationChangedError extends Error {
186
- /**
187
- * @param {PublicationResponse} current
188
- * @param {PublicationResponse} rejected
189
- */
190
- constructor(current, rejected) {
191
- super("The pinned publication changed while it was being polled.");
192
- this.current = current;
193
- this.rejected = rejected;
194
- }
195
- }
196
-
197
- export class PublicationTimeoutError extends Error {
198
- /** @param {PublicationResponse} current */
199
- constructor(current) {
200
- super("The publication did not finish before the wait deadline.");
201
- this.current = current;
202
- }
203
- }
204
-
205
- export class PublicationFailedError extends Error {
206
- /** @param {PublicationResponse} current */
207
- constructor(current) {
208
- super("The publication failed.");
209
- this.current = current;
210
- }
211
- }
212
-
213
- export class PublicationCancelledError extends Error {
214
- /** @param {PublicationResponse} current */
215
- constructor(current) {
216
- super("The publication was cancelled.");
217
- this.current = current;
218
- }
219
- }
220
-
221
- /**
222
- * @typedef {object} PublicationResponse
223
- * @property {{id: string, graph_version: number, head_source_sha256: string}} project
224
- * @property {{id: string, analysis_run_id: string, graph_version: number, head_source_sha256: string, status: string, compiler_release: string, target: {id: string, profile: string}, artifact: null | {sha256: string, manifest_sha256: string, file_count: number}}} compilation
225
- * @property {{id: string, status: string, repository: null | {id: number, private: true, owner: {id: number, login: string, type: "User"}, full_name: string, default_branch: string, html_url: string, tree_sha: string | null, commit_sha: string | null}, failure: null | {phase: string, code: string}, progress: {phase: string, retry_at: string | null, retry_count: number, reason_code: string | null}, created_at: string, started_at: string | null, completed_at: string | null}} publication
226
- */
227
-
228
- /**
229
- * @typedef {object} PublishPlanOptions
230
- * @property {string} cwd
231
- * @property {string} [expectedEtag]
232
- * @property {typeof globalThis.fetch} [fetchFunction]
233
- * @property {PlanPublishFileSystem} [fileSystem]
234
- * @property {(timeoutMs: number) => AbortSignal} [createRequestSignal]
235
- * @property {(delayMs: number) => Promise<void>} [sleep]
236
- * @property {() => number} [now]
237
- * @property {(progress: import("../plan-compile-progress.js").PlanCompileProgress) => void} [onProgress]
238
- */
239
-
240
- /**
241
- * @param {PublishPlanOptions} options
242
- * @returns {Promise<PublicationResponse>}
243
- */
244
- export async function publishPlan({
245
- cwd,
246
- expectedEtag,
247
- fetchFunction = globalThis.fetch,
248
- fileSystem = DEFAULT_FILE_SYSTEM,
249
- createRequestSignal = (timeoutMs) => AbortSignal.timeout(timeoutMs),
250
- sleep = sleepFor,
251
- now = Date.now,
252
- onProgress = () => {},
253
- }) {
254
- const state = readPlanState({ cwd, fileSystem });
255
- if (state.api_url === undefined || state.foundation_plan_etag === undefined) {
256
- throw new PublicationNotPushedError(
257
- "The local Foundation Plan has not been pushed.",
258
- );
259
- }
260
-
261
- if (
262
- expectedEtag !== undefined &&
263
- state.foundation_plan_etag !== expectedEtag
264
- ) {
265
- throw new PublicationLocalPlanChangedError(
266
- "Local Plan state changed after this command accepted its Plan.",
267
- );
268
- }
269
-
270
- const publicationEtag = expectedEtag ?? state.foundation_plan_etag;
271
- const match = HEAD_ETAG_PATTERN.exec(publicationEtag);
272
- if (match === null) {
273
- throw new PublicationLocalStateError(
274
- "The saved Foundation Plan ETag cannot identify its accepted source.",
275
- );
276
- }
277
- const headSourceSha256 = match[1] ?? "";
278
- const planSource = readLocalFile(
279
- path.join(cwd, ".firstdraft", "foundation-plan.json"),
280
- MAX_PLAN_BYTES,
281
- fileSystem,
282
- );
283
- if (sha256(planSource) !== headSourceSha256) {
284
- throw new PublicationLocalPlanChangedError(
285
- "The local Foundation Plan differs from the accepted Plan.",
286
- );
287
- }
288
-
289
- const apiUrl = state.api_url;
290
- const deadline = now() + WAIT_TIMEOUT_MS;
291
- let initial;
292
-
293
- onProgress({ phase: "compilation", status: "waiting" });
294
-
295
- try {
296
- initial = await startPublication({
297
- apiUrl,
298
- projectId: state.project_id,
299
- headSourceSha256,
300
- etag: publicationEtag,
301
- fetchFunction,
302
- createRequestSignal,
303
- });
304
- } catch (error) {
305
- if (!(error instanceof PublicationRequestOutcomeUnknownError)) throw error;
306
-
307
- try {
308
- initial = await readPublicationStatus({
309
- apiUrl,
310
- projectId: state.project_id,
311
- headSourceSha256,
312
- fetchFunction,
313
- createRequestSignal,
314
- requestTimeout: Math.max(
315
- 1,
316
- Math.min(REQUEST_TIMEOUT_MS, deadline - now()),
317
- ),
318
- });
319
- } catch (reconciliationError) {
320
- if (
321
- reconciliationError instanceof PublicationStatusUnavailableError &&
322
- isAuthenticationProblem(
323
- reconciliationError.status,
324
- reconciliationError.response,
325
- )
326
- ) {
327
- throw reconciliationError;
328
- }
329
- if (
330
- reconciliationError instanceof PublicationStatusUnavailableError ||
331
- reconciliationError instanceof PublicationStatusInvalidError
332
- ) {
333
- let status = reconciliationError.status ?? error.status;
334
- let response = error.response;
335
- if (
336
- reconciliationError instanceof PublicationStatusUnavailableError &&
337
- reconciliationError.response !== null
338
- ) {
339
- status = reconciliationError.status;
340
- response = reconciliationError.response;
341
- } else if (error.response !== null) {
342
- status = error.status;
343
- }
344
- throw new PublicationRequestOutcomeUnknownError(status, response);
345
- }
346
-
347
- throw reconciliationError;
348
- }
349
- }
350
-
351
- let current = initial;
352
- reportProgress(onProgress, current);
353
- while (!TERMINAL_PUBLICATION_STATUSES.has(current.publication.status)) {
354
- const remaining = deadline - now();
355
- if (remaining <= 0) throw new PublicationTimeoutError(current);
356
-
357
- await sleep(Math.min(POLL_INTERVAL_MS, remaining));
358
- if (now() >= deadline) throw new PublicationTimeoutError(current);
359
-
360
- const next = await readPublicationStatus({
361
- apiUrl,
362
- projectId: state.project_id,
363
- headSourceSha256,
364
- fetchFunction,
365
- createRequestSignal,
366
- requestTimeout: Math.max(
367
- 1,
368
- Math.min(REQUEST_TIMEOUT_MS, deadline - now()),
369
- ),
370
- });
371
- if (!samePublication(initial, next) || !validTransition(current, next)) {
372
- throw new PublicationChangedError(current, next);
373
- }
374
- current = next;
375
- reportProgress(onProgress, current);
376
- }
377
-
378
- if (
379
- current.publication.status === "failed" ||
380
- current.publication.status === "repository_conflict"
381
- ) {
382
- throw new PublicationFailedError(current);
383
- }
384
- if (current.publication.status === "cancelled") {
385
- throw new PublicationCancelledError(current);
386
- }
387
-
388
- return current;
389
- }
390
-
391
- /**
392
- * @param {object} options
393
- * @param {string} options.apiUrl
394
- * @param {string} options.projectId
395
- * @param {string} options.headSourceSha256
396
- * @param {string} options.etag
397
- * @param {typeof globalThis.fetch} options.fetchFunction
398
- * @param {(timeoutMs: number) => AbortSignal} options.createRequestSignal
399
- */
400
- async function startPublication({
401
- apiUrl,
402
- projectId,
403
- headSourceSha256,
404
- etag,
405
- fetchFunction,
406
- createRequestSignal,
407
- }) {
408
- const endpoint = serviceEndpoint(SERVICE_ROUTES.startPublication, apiUrl, {
409
- project_id: projectId,
410
- });
411
- let response;
412
- let body;
413
- try {
414
- response = await sendRequest(fetchFunction, endpoint, {
415
- headers: {
416
- Accept: "application/json, application/problem+json",
417
- "If-Match": etag,
418
- },
419
- redirect: "error",
420
- signal: createRequestSignal(REQUEST_TIMEOUT_MS),
421
- });
422
- body = await readResponseBody(response);
423
- } catch (error) {
424
- if (
425
- error instanceof FirstDraftNetworkError ||
426
- error instanceof FirstDraftProtocolError
427
- ) {
428
- throw new PublicationRequestOutcomeUnknownError(error.status);
429
- }
430
-
431
- throw error;
432
- }
433
-
434
- if (response.status !== 200 && response.status !== 201) {
435
- const problem = safeProblem(response, body);
436
- if (response.ok || problem === null) {
437
- throw new PublicationRequestOutcomeUnknownError(response.status);
438
- }
439
- if (response.status === 408 || response.status >= 500) {
440
- throw new PublicationRequestOutcomeUnknownError(response.status, problem);
441
- }
442
-
443
- throw new PublicationStartRejectedError(response.status, problem);
444
- }
445
-
446
- const parsed = parsePublicationResponse(body, projectId, headSourceSha256);
447
- if (responseMediaType(response) !== "application/json" || parsed === null) {
448
- throw new PublicationRequestOutcomeUnknownError(response.status);
449
- }
450
-
451
- return parsed;
452
- }
453
-
454
- /**
455
- * @param {object} options
456
- * @param {string} options.apiUrl
457
- * @param {string} options.projectId
458
- * @param {string} options.headSourceSha256
459
- * @param {typeof globalThis.fetch} options.fetchFunction
460
- * @param {(timeoutMs: number) => AbortSignal} options.createRequestSignal
461
- * @param {number} options.requestTimeout
462
- */
463
- async function readPublicationStatus({
464
- apiUrl,
465
- projectId,
466
- headSourceSha256,
467
- fetchFunction,
468
- createRequestSignal,
469
- requestTimeout,
470
- }) {
471
- const endpoint = serviceEndpoint(SERVICE_ROUTES.readPublication, apiUrl, {
472
- project_id: projectId,
473
- });
474
- let response;
475
- let body;
476
- try {
477
- response = await sendRequest(fetchFunction, endpoint, {
478
- headers: { Accept: "application/json, application/problem+json" },
479
- redirect: "error",
480
- signal: createRequestSignal(requestTimeout),
481
- });
482
- body = await readResponseBody(response);
483
- } catch (error) {
484
- if (error instanceof FirstDraftNetworkError) {
485
- throw new PublicationStatusUnavailableError(error.status);
486
- }
487
- if (error instanceof FirstDraftProtocolError) {
488
- throw new PublicationStatusInvalidError(error.status);
489
- }
490
-
491
- throw error;
492
- }
493
-
494
- if (response.status !== 200) {
495
- if (!response.ok) {
496
- throw new PublicationStatusUnavailableError(
497
- response.status,
498
- safeProblem(response, body),
499
- );
500
- }
501
- throw new PublicationStatusInvalidError(response.status);
502
- }
503
-
504
- const parsed = parsePublicationResponse(body, projectId, headSourceSha256);
505
- if (responseMediaType(response) !== "application/json" || parsed === null) {
506
- throw new PublicationStatusInvalidError(response.status);
507
- }
508
-
509
- return parsed;
510
- }
511
-
512
- /**
513
- * @param {unknown} value
514
- * @param {string} projectId
515
- * @param {string} headSourceSha256
516
- * @returns {PublicationResponse | null}
517
- */
518
- function parsePublicationResponse(value, projectId, headSourceSha256) {
519
- if (
520
- !hasExactKeySet(value, RESPONSE_KEYS) ||
521
- !hasExactKeySet(value.project, PROJECT_KEYS) ||
522
- !hasExactKeySet(value.compilation, COMPILATION_KEYS) ||
523
- !hasExactKeySet(value.publication, PUBLICATION_KEYS)
524
- ) {
525
- return null;
526
- }
527
-
528
- const project = value.project;
529
- const compilation = value.compilation;
530
- const publication = value.publication;
531
- if (
532
- project.id !== projectId ||
533
- !isGraphVersion(project.graph_version) ||
534
- project.head_source_sha256 !== headSourceSha256 ||
535
- !isUuidV7(compilation.id) ||
536
- !isUuidV7(compilation.analysis_run_id) ||
537
- compilation.graph_version !== project.graph_version ||
538
- compilation.head_source_sha256 !== headSourceSha256 ||
539
- typeof compilation.status !== "string" ||
540
- !COMPILATION_STATUSES.has(compilation.status) ||
541
- !isRelease(compilation.compiler_release) ||
542
- !hasExactKeySet(compilation.target, TARGET_KEYS) ||
543
- !isRelease(compilation.target.id) ||
544
- !isRelease(compilation.target.profile) ||
545
- !isNullableArtifact(compilation.artifact) ||
546
- !isUuidV7(publication.id) ||
547
- typeof publication.status !== "string" ||
548
- !PUBLICATION_STATUSES.has(publication.status) ||
549
- !isNullableRepository(publication.repository) ||
550
- !isNullableFailure(publication.failure) ||
551
- !isProgress(publication.progress, publication.status) ||
552
- !isTimestamp(publication.created_at) ||
553
- !isNullableTimestamp(publication.started_at) ||
554
- !isNullableTimestamp(publication.completed_at) ||
555
- !hasValidCompilationShape(compilation) ||
556
- !hasValidPublicationShape(compilation, publication)
557
- ) {
558
- return null;
559
- }
560
-
561
- const target = /** @type {{id: string, profile: string}} */ (
562
- compilation.target
563
- );
564
- const artifact =
565
- /** @type {null | {sha256: string, manifest_sha256: string, file_count: number}} */ (
566
- compilation.artifact
567
- );
568
- const repository =
569
- /** @type {null | {id: number, private: true, owner: {id: number, login: string, type: "User"}, full_name: string, default_branch: string, html_url: string, tree_sha: string | null, commit_sha: string | null}} */ (
570
- publication.repository
571
- );
572
- const failure = /** @type {null | {phase: string, code: string}} */ (
573
- publication.failure
574
- );
575
- const progress =
576
- /** @type {{phase: string, retry_at: string | null, retry_count: number, reason_code: string | null}} */ (
577
- publication.progress
578
- );
579
-
580
- return {
581
- project: {
582
- id: project.id,
583
- graph_version: /** @type {number} */ (project.graph_version),
584
- head_source_sha256: project.head_source_sha256,
585
- },
586
- compilation: {
587
- id: compilation.id,
588
- analysis_run_id: compilation.analysis_run_id,
589
- graph_version: /** @type {number} */ (compilation.graph_version),
590
- head_source_sha256: compilation.head_source_sha256,
591
- status: compilation.status,
592
- compiler_release: /** @type {string} */ (compilation.compiler_release),
593
- target: { id: target.id, profile: target.profile },
594
- artifact:
595
- artifact === null
596
- ? null
597
- : {
598
- sha256: artifact.sha256,
599
- manifest_sha256: artifact.manifest_sha256,
600
- file_count: artifact.file_count,
601
- },
602
- },
603
- publication: {
604
- id: publication.id,
605
- status: publication.status,
606
- repository:
607
- repository === null
608
- ? null
609
- : {
610
- id: repository.id,
611
- private: true,
612
- owner: {
613
- id: repository.owner.id,
614
- login: repository.owner.login,
615
- type: "User",
616
- },
617
- full_name: repository.full_name,
618
- default_branch: repository.default_branch,
619
- html_url: repository.html_url,
620
- tree_sha: repository.tree_sha,
621
- commit_sha: repository.commit_sha,
622
- },
623
- failure:
624
- failure === null ? null : { phase: failure.phase, code: failure.code },
625
- progress: {
626
- phase: progress.phase,
627
- retry_at: progress.retry_at,
628
- retry_count: progress.retry_count,
629
- reason_code: progress.reason_code,
630
- },
631
- created_at: /** @type {string} */ (publication.created_at),
632
- started_at: /** @type {string | null} */ (publication.started_at),
633
- completed_at: /** @type {string | null} */ (publication.completed_at),
634
- },
635
- };
636
- }
637
-
638
- /** @param {Record<string, unknown>} compilation */
639
- function hasValidCompilationShape(compilation) {
640
- return compilation.status === "succeeded"
641
- ? compilation.artifact !== null
642
- : compilation.artifact === null;
643
- }
644
-
645
- /**
646
- * @param {Record<string, unknown>} compilation
647
- * @param {Record<string, unknown>} publication
648
- */
649
- function hasValidPublicationShape(compilation, publication) {
650
- const status = String(publication.status);
651
- const terminal = TERMINAL_PUBLICATION_STATUSES.has(status);
652
- const failureExpected =
653
- status === "failed" || status === "repository_conflict";
654
- const created = timestampMilliseconds(String(publication.created_at));
655
- const started =
656
- publication.started_at === null
657
- ? null
658
- : timestampMilliseconds(String(publication.started_at));
659
- const completed =
660
- publication.completed_at === null
661
- ? null
662
- : timestampMilliseconds(String(publication.completed_at));
663
- const repository = /** @type {Record<string, unknown> | null} */ (
664
- publication.repository
665
- );
666
-
667
- if (
668
- (terminal && completed === null) ||
669
- (!terminal && completed !== null) ||
670
- (failureExpected && publication.failure === null) ||
671
- (!failureExpected && publication.failure !== null) ||
672
- (status !== "compiling" &&
673
- started === null &&
674
- !(
675
- (status === "failed" && compilation.status === "failed") ||
676
- (status === "cancelled" && compilation.status === "cancelled")
677
- )) ||
678
- (started !== null && started < created) ||
679
- (completed !== null && completed < created) ||
680
- (started !== null && completed !== null && completed < started) ||
681
- (status === "compiling" &&
682
- !["queued", "running", "succeeded"].includes(
683
- String(compilation.status),
684
- )) ||
685
- (status === "failed" &&
686
- !["failed", "succeeded"].includes(String(compilation.status))) ||
687
- (status === "cancelled" &&
688
- !["cancelled", "succeeded"].includes(String(compilation.status))) ||
689
- (!["compiling", "failed", "cancelled"].includes(status) &&
690
- compilation.status !== "succeeded") ||
691
- (["publishing", "publication_unknown", "succeeded"].includes(status) &&
692
- repository === null)
693
- ) {
694
- return false;
695
- }
696
-
697
- if (status !== "succeeded") return true;
698
-
699
- return (
700
- repository !== null &&
701
- typeof repository.tree_sha === "string" &&
702
- typeof repository.commit_sha === "string"
703
- );
704
- }
705
-
706
- /** @param {unknown} value */
707
- function isNullableArtifact(value) {
708
- return (
709
- value === null ||
710
- (hasExactKeySet(value, ARTIFACT_KEYS) &&
711
- typeof value.sha256 === "string" &&
712
- SHA256_PATTERN.test(value.sha256) &&
713
- typeof value.manifest_sha256 === "string" &&
714
- SHA256_PATTERN.test(value.manifest_sha256) &&
715
- Number.isSafeInteger(value.file_count) &&
716
- Number(value.file_count) >= 0)
717
- );
718
- }
719
-
720
- /** @param {unknown} value */
721
- function isNullableFailure(value) {
722
- return (
723
- value === null ||
724
- (hasExactKeySet(value, FAILURE_KEYS) &&
725
- isRelease(value.phase) &&
726
- isFailureCode(value.code))
727
- );
728
- }
729
-
730
- /** @param {unknown} value @param {unknown} publicationStatus */
731
- function isProgress(value, publicationStatus) {
732
- if (
733
- !hasExactKeySet(value, PROGRESS_KEYS) ||
734
- typeof value.phase !== "string" ||
735
- !PROGRESS_PHASES.has(value.phase) ||
736
- !Number.isSafeInteger(value.retry_count) ||
737
- Number(value.retry_count) < 0 ||
738
- Number(value.retry_count) > MAX_PROGRESS_RETRY_COUNT ||
739
- !isNullableRetryTimestamp(value.retry_at) ||
740
- !(
741
- value.reason_code === null ||
742
- (typeof value.reason_code === "string" &&
743
- PROGRESS_REASON_CODES.has(value.reason_code))
744
- ) ||
745
- !progressMatchesPublicationStatus(value.phase, publicationStatus)
746
- ) {
747
- return false;
748
- }
749
-
750
- if (value.phase !== "github_preflight") {
751
- return (
752
- value.retry_at === null &&
753
- value.retry_count === 0 &&
754
- value.reason_code === null
755
- );
756
- }
757
-
758
- return value.retry_count === 0
759
- ? value.retry_at === null && value.reason_code === null
760
- : value.reason_code !== null;
761
- }
762
-
763
- /** @param {string} progressPhase @param {unknown} publicationStatus */
764
- function progressMatchesPublicationStatus(progressPhase, publicationStatus) {
765
- if (progressPhase === "compiling") return publicationStatus === "compiling";
766
- if (progressPhase === "completed") return publicationStatus === "succeeded";
767
- if (progressPhase === "failed") {
768
- return (
769
- publicationStatus === "failed" ||
770
- publicationStatus === "repository_conflict"
771
- );
772
- }
773
- if (progressPhase === "cancelled") return publicationStatus === "cancelled";
774
- if (progressPhase === "github_preflight") {
775
- return [
776
- "provisioning_repository",
777
- "repository_unknown",
778
- "publishing",
779
- "publication_unknown",
780
- ].includes(String(publicationStatus));
781
- }
782
-
783
- const expectedStatus = new Map([
784
- ["preparing_repository", "provisioning_repository"],
785
- ["creating_repository", "provisioning_repository"],
786
- ["preparing_repository_reconciliation", "repository_unknown"],
787
- ["reconciling_repository", "repository_unknown"],
788
- ["preparing_artifact", "publishing"],
789
- ["publishing_artifact", "publishing"],
790
- ["preparing_publication_reconciliation", "publication_unknown"],
791
- ["reconciling_publication", "publication_unknown"],
792
- ]).get(progressPhase);
793
- return publicationStatus === expectedStatus;
794
- }
795
-
796
- /** @param {unknown} value */
797
- function isNullableRetryTimestamp(value) {
798
- return (
799
- value === null ||
800
- (typeof value === "string" &&
801
- RETRY_TIMESTAMP_PATTERN.test(value) &&
802
- isTimestamp(value))
803
- );
804
- }
805
-
806
- /** @param {unknown} value */
807
- function isNullableRepository(value) {
808
- if (value === null) return true;
809
- if (
810
- !hasExactKeySet(value, REPOSITORY_KEYS) ||
811
- !isPositiveInteger(value.id) ||
812
- value.private !== true ||
813
- !hasExactKeySet(value.owner, OWNER_KEYS) ||
814
- !isPositiveInteger(value.owner.id) ||
815
- value.owner.type !== "User" ||
816
- !isGithubName(value.owner.login, MAX_LOGIN_BYTES) ||
817
- typeof value.full_name !== "string" ||
818
- typeof value.default_branch !== "string" ||
819
- typeof value.html_url !== "string" ||
820
- !isNullableGitSha(value.tree_sha) ||
821
- !isNullableGitSha(value.commit_sha) ||
822
- (value.tree_sha === null) !== (value.commit_sha === null)
823
- ) {
824
- return false;
825
- }
826
-
827
- const prefix = `${value.owner.login}/`;
828
- const repositoryName = value.full_name.startsWith(prefix)
829
- ? value.full_name.slice(prefix.length)
830
- : "";
831
- return (
832
- isGithubName(repositoryName, MAX_REPOSITORY_NAME_BYTES) &&
833
- isGitBranch(value.default_branch) &&
834
- value.html_url === `https://github.com/${value.full_name}`
835
- );
836
- }
837
-
838
- /** @param {PublicationResponse} first @param {PublicationResponse} current */
839
- function samePublication(first, current) {
840
- return (
841
- current.project.id === first.project.id &&
842
- current.project.graph_version === first.project.graph_version &&
843
- current.project.head_source_sha256 === first.project.head_source_sha256 &&
844
- current.compilation.id === first.compilation.id &&
845
- current.compilation.analysis_run_id === first.compilation.analysis_run_id &&
846
- current.compilation.graph_version === first.compilation.graph_version &&
847
- current.compilation.head_source_sha256 ===
848
- first.compilation.head_source_sha256 &&
849
- current.compilation.compiler_release ===
850
- first.compilation.compiler_release &&
851
- current.compilation.target.id === first.compilation.target.id &&
852
- current.compilation.target.profile === first.compilation.target.profile &&
853
- current.publication.id === first.publication.id &&
854
- current.publication.created_at === first.publication.created_at
855
- );
856
- }
857
-
858
- /** @param {PublicationResponse} previous @param {PublicationResponse} current */
859
- function validTransition(previous, current) {
860
- if (!validCompilationTransition(previous.compilation, current.compilation)) {
861
- return false;
862
- }
863
- if (!validPublicationStatusTransition(previous, current)) return false;
864
- if (!validRepositoryTransition(previous, current)) return false;
865
-
866
- return (
867
- (previous.publication.started_at === null ||
868
- current.publication.started_at === previous.publication.started_at) &&
869
- (previous.publication.completed_at === null ||
870
- current.publication.completed_at === previous.publication.completed_at) &&
871
- (previous.publication.failure === null ||
872
- JSON.stringify(current.publication.failure) ===
873
- JSON.stringify(previous.publication.failure))
874
- );
875
- }
876
-
877
- /**
878
- * @param {PublicationResponse["compilation"]} previous
879
- * @param {PublicationResponse["compilation"]} current
880
- */
881
- function validCompilationTransition(previous, current) {
882
- if (previous.status === current.status) {
883
- return (
884
- JSON.stringify(previous.artifact) === JSON.stringify(current.artifact)
885
- );
886
- }
887
-
888
- if (previous.status === "queued") {
889
- return ["running", "succeeded", "failed", "cancelled"].includes(
890
- current.status,
891
- );
892
- }
893
- return (
894
- previous.status === "running" &&
895
- ["succeeded", "failed", "cancelled"].includes(current.status)
896
- );
897
- }
898
-
899
- /** @param {PublicationResponse} previous @param {PublicationResponse} current */
900
- function validPublicationStatusTransition(previous, current) {
901
- const from = previous.publication.status;
902
- const to = current.publication.status;
903
- if (from === to) {
904
- return (
905
- current.publication.started_at === previous.publication.started_at &&
906
- current.publication.completed_at === previous.publication.completed_at &&
907
- JSON.stringify(current.publication.failure) ===
908
- JSON.stringify(previous.publication.failure)
909
- );
910
- }
911
-
912
- if (
913
- (from === "repository_unknown" && to === "provisioning_repository") ||
914
- (from === "publication_unknown" && to === "publishing")
915
- ) {
916
- return false;
917
- }
918
-
919
- return publicationStage(to) >= publicationStage(from);
920
- }
921
-
922
- /** @param {string} status */
923
- function publicationStage(status) {
924
- if (status === "compiling") return 0;
925
- if (status === "provisioning_repository" || status === "repository_unknown") {
926
- return 1;
927
- }
928
- if (status === "publishing" || status === "publication_unknown") return 2;
929
- return 3;
930
- }
931
-
932
- /** @param {PublicationResponse} previous @param {PublicationResponse} current */
933
- function validRepositoryTransition(previous, current) {
934
- const before = previous.publication.repository;
935
- const after = current.publication.repository;
936
- if (before === null) return true;
937
- if (after === null) return false;
938
-
939
- return (
940
- after.id === before.id &&
941
- after.private === before.private &&
942
- after.owner.id === before.owner.id &&
943
- after.owner.login === before.owner.login &&
944
- after.owner.type === before.owner.type &&
945
- after.full_name === before.full_name &&
946
- after.default_branch === before.default_branch &&
947
- after.html_url === before.html_url &&
948
- (before.tree_sha === null || after.tree_sha === before.tree_sha) &&
949
- (before.commit_sha === null || after.commit_sha === before.commit_sha)
950
- );
951
- }
952
-
953
- /**
954
- * @param {(progress: import("../plan-compile-progress.js").PlanCompileProgress) => void} onProgress
955
- * @param {PublicationResponse} current
956
- */
957
- function reportProgress(onProgress, current) {
958
- const progress = current.publication.progress;
959
- onProgress({
960
- phase: "publication",
961
- compilationStatus:
962
- /** @type {"queued" | "running" | "succeeded" | "failed" | "cancelled"} */ (
963
- current.compilation.status
964
- ),
965
- publicationPhase: progress.phase,
966
- retryAt: progress.retry_at,
967
- retryCount: progress.retry_count,
968
- reasonCode: progress.reason_code,
969
- });
970
- }
971
-
972
- /** @param {Response} response @param {unknown} body */
973
- function safeProblem(response, body) {
974
- if (!isProblemBody(response, body)) return null;
975
- const problem = /** @type {Record<string, unknown>} */ (body);
976
-
977
- return {
978
- ...(problem.type === "about:blank" ? { type: problem.type } : {}),
979
- title: problem.title,
980
- status: problem.status,
981
- code: problem.code,
982
- detail: problem.detail,
983
- };
984
- }
985
-
986
- /** @param {number} delayMs */
987
- function sleepFor(delayMs) {
988
- return new Promise((resolve) => {
989
- setTimeout(resolve, delayMs);
990
- });
991
- }
992
-
993
- /** @param {Buffer} value */
994
- function sha256(value) {
995
- return createHash("sha256").update(value).digest("hex");
996
- }
997
-
998
- /** @param {unknown} value */
999
- function isRelease(value) {
1000
- return (
1001
- typeof value === "string" &&
1002
- Buffer.byteLength(value) <= MAX_IDENTIFIER_BYTES &&
1003
- RELEASE_PATTERN.test(value)
1004
- );
1005
- }
1006
-
1007
- /** @param {unknown} value */
1008
- function isFailureCode(value) {
1009
- return (
1010
- typeof value === "string" &&
1011
- Buffer.byteLength(value) <= MAX_FAILURE_CODE_BYTES &&
1012
- RELEASE_PATTERN.test(value)
1013
- );
1014
- }
1015
-
1016
- /** @param {unknown} value */
1017
- function isGraphVersion(value) {
1018
- return Number.isSafeInteger(value) && Number(value) >= 1;
1019
- }
1020
-
1021
- /** @param {unknown} value */
1022
- function isPositiveInteger(value) {
1023
- return Number.isSafeInteger(value) && Number(value) > 0;
1024
- }
1025
-
1026
- /** @param {unknown} value */
1027
- function isNullableGitSha(value) {
1028
- return (
1029
- value === null || (typeof value === "string" && GIT_SHA_PATTERN.test(value))
1030
- );
1031
- }
1032
-
1033
- /** @param {unknown} value @param {number} maximumBytes */
1034
- function isGithubName(value, maximumBytes) {
1035
- return (
1036
- typeof value === "string" &&
1037
- Buffer.byteLength(value) <= maximumBytes &&
1038
- GITHUB_NAME_PATTERN.test(value)
1039
- );
1040
- }
1041
-
1042
- /** @param {unknown} value */
1043
- function isGitBranch(value) {
1044
- return (
1045
- typeof value === "string" &&
1046
- Buffer.byteLength(value) <= MAX_IDENTIFIER_BYTES &&
1047
- value.length > 0 &&
1048
- !value.startsWith(".") &&
1049
- !value.endsWith(".") &&
1050
- !value.endsWith("/") &&
1051
- !value.endsWith(".lock") &&
1052
- !value.includes("..") &&
1053
- !value.includes("//") &&
1054
- ![...value].some((character) => {
1055
- const codePoint = character.codePointAt(0) ?? 0;
1056
- return codePoint <= 0x20 || "~^:?*[\\".includes(character);
1057
- })
1058
- );
1059
- }
1060
-
1061
- /** @param {unknown} value */
1062
- function isNullableTimestamp(value) {
1063
- return value === null || isTimestamp(value);
1064
- }
1065
-
1066
- /** @param {unknown} value */
1067
- function isTimestamp(value) {
1068
- return timestampParts(value) !== null;
1069
- }
1070
-
1071
- /** @param {string} value */
1072
- function timestampMilliseconds(value) {
1073
- const parsed = Date.parse(value);
1074
- if (Number.isFinite(parsed)) return parsed;
1075
-
1076
- return Date.parse(value.replace(/:60(?=[.,Zz+-])/, ":59")) + 1_000;
1077
- }
1078
-
1079
- /** @param {unknown} value */
1080
- function timestampParts(value) {
1081
- if (typeof value !== "string") return null;
1082
-
1083
- const match =
1084
- /^(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|([+-])(\d{2}):(\d{2}))$/.exec(
1085
- value,
1086
- );
1087
- if (!match) return null;
1088
-
1089
- const year = Number(match[1]);
1090
- const month = Number(match[2]);
1091
- const day = Number(match[3]);
1092
- const hour = Number(match[4]);
1093
- const minute = Number(match[5]);
1094
- const second = Number(match[6]);
1095
- const offsetHour = match[8] === undefined ? 0 : Number(match[8]);
1096
- const offsetMinute = match[9] === undefined ? 0 : Number(match[9]);
1097
- if (
1098
- month < 1 ||
1099
- month > 12 ||
1100
- day < 1 ||
1101
- day > daysInMonth(year, month) ||
1102
- hour > 23 ||
1103
- minute > 59 ||
1104
- second > 60 ||
1105
- (second === 60 && (hour !== 23 || minute !== 59)) ||
1106
- offsetHour > 23 ||
1107
- offsetMinute > 59
1108
- ) {
1109
- return null;
1110
- }
1111
-
1112
- return true;
1113
- }
1114
-
1115
- /** @param {number} year @param {number} month */
1116
- function daysInMonth(year, month) {
1117
- if (month === 2) {
1118
- return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
1119
- }
1120
-
1121
- return [4, 6, 9, 11].includes(month) ? 30 : 31;
1122
- }
1123
-
1124
- /**
1125
- * @param {unknown} value
1126
- * @param {string[]} keys
1127
- * @returns {value is Record<string, unknown>}
1128
- */
1129
- function hasExactKeySet(value, keys) {
1130
- return (
1131
- isRecord(value) && arraysEqual(Object.keys(value).sort(), [...keys].sort())
1132
- );
1133
- }
1134
-
1135
- /** @param {unknown} value @returns {value is Record<string, unknown>} */
1136
- function isRecord(value) {
1137
- return typeof value === "object" && value !== null && !Array.isArray(value);
1138
- }
1139
-
1140
- /** @param {unknown[]} left @param {unknown[]} right */
1141
- function arraysEqual(left, right) {
1142
- return (
1143
- left.length === right.length &&
1144
- left.every((value, index) => value === right[index])
1145
- );
1146
- }