@git.zone/cli 12.2.0 → 12.3.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.
Files changed (59) hide show
  1. package/assets/templates/npm/.package.json +1 -1
  2. package/assets/templates/service/.package.json +1 -1
  3. package/assets/templates/wcc/.package.json +1 -1
  4. package/assets/templates/website/.package.json +1 -1
  5. package/dist_ts/00_commitinfo_data.js +1 -1
  6. package/dist_ts/helpers.versionsource.d.ts +23 -5
  7. package/dist_ts/helpers.versionsource.js +115 -37
  8. package/dist_ts/helpers.workflow.d.ts +60 -17
  9. package/dist_ts/helpers.workflow.js +156 -51
  10. package/dist_ts/mod_config/index.js +98 -31
  11. package/dist_ts/mod_release/classes.releasejournal.d.ts +63 -8
  12. package/dist_ts/mod_release/classes.releasejournal.js +283 -124
  13. package/dist_ts/mod_release/helpers.cargorelease.d.ts +4 -3
  14. package/dist_ts/mod_release/helpers.cargorelease.js +5 -4
  15. package/dist_ts/mod_release/helpers.fossglobalassets.d.ts +61 -0
  16. package/dist_ts/mod_release/helpers.fossglobalassets.js +580 -0
  17. package/dist_ts/mod_release/helpers.giteaassets.d.ts +15 -51
  18. package/dist_ts/mod_release/helpers.giteaassets.js +40 -507
  19. package/dist_ts/mod_release/helpers.releaseassets.d.ts +40 -0
  20. package/dist_ts/mod_release/helpers.releaseassets.js +349 -0
  21. package/dist_ts/mod_release/helpers.releaseassettransfer.d.ts +67 -0
  22. package/dist_ts/mod_release/helpers.releaseassettransfer.js +239 -0
  23. package/dist_ts/mod_release/helpers.releasecheck.js +3 -2
  24. package/dist_ts/mod_release/helpers.releasepreparation.d.ts +7 -6
  25. package/dist_ts/mod_release/helpers.releasepreparation.js +34 -7
  26. package/dist_ts/mod_release/helpers.releasepublication.d.ts +8 -2
  27. package/dist_ts/mod_release/helpers.releasepublication.js +218 -54
  28. package/dist_ts/mod_release/helpers.releaseversionsource.d.ts +7 -5
  29. package/dist_ts/mod_release/helpers.releaseversionsource.js +9 -7
  30. package/dist_ts/mod_release/index.d.ts +1 -1
  31. package/dist_ts/mod_release/index.js +109 -68
  32. package/dist_ts/mod_release/interfaces.fossglobalassets.d.ts +108 -0
  33. package/dist_ts/mod_release/interfaces.fossglobalassets.js +2 -0
  34. package/dist_ts/mod_release/interfaces.giteaassets.d.ts +9 -43
  35. package/dist_ts/mod_release/interfaces.releaseassets.d.ts +68 -0
  36. package/dist_ts/mod_release/interfaces.releaseassets.js +2 -0
  37. package/dist_ts/plugins.d.ts +1 -0
  38. package/dist_ts/plugins.js +1 -1
  39. package/package.json +3 -2
  40. package/readme.md +338 -40
  41. package/ts/00_commitinfo_data.ts +1 -1
  42. package/ts/helpers.versionsource.ts +176 -45
  43. package/ts/helpers.workflow.ts +288 -78
  44. package/ts/mod_config/index.ts +130 -38
  45. package/ts/mod_release/classes.releasejournal.ts +499 -180
  46. package/ts/mod_release/helpers.cargorelease.ts +8 -3
  47. package/ts/mod_release/helpers.fossglobalassets.ts +886 -0
  48. package/ts/mod_release/helpers.giteaassets.ts +127 -694
  49. package/ts/mod_release/helpers.releaseassets.ts +516 -0
  50. package/ts/mod_release/helpers.releaseassettransfer.ts +339 -0
  51. package/ts/mod_release/helpers.releasecheck.ts +3 -1
  52. package/ts/mod_release/helpers.releasepreparation.ts +55 -12
  53. package/ts/mod_release/helpers.releasepublication.ts +351 -69
  54. package/ts/mod_release/helpers.releaseversionsource.ts +11 -7
  55. package/ts/mod_release/index.ts +151 -90
  56. package/ts/mod_release/interfaces.fossglobalassets.ts +127 -0
  57. package/ts/mod_release/interfaces.giteaassets.ts +14 -47
  58. package/ts/mod_release/interfaces.releaseassets.ts +96 -0
  59. package/ts/plugins.ts +3 -0
@@ -0,0 +1,886 @@
1
+ import * as plugins from "./mod.plugins.js";
2
+ import type {
3
+ IFossglobalAssetInspection,
4
+ IFossglobalAssetsClient,
5
+ IFossglobalAssetsClientOptions,
6
+ IFossglobalClaimedAsset,
7
+ IFossglobalPresentAsset,
8
+ IFossglobalRelease,
9
+ IFossglobalReleaseClaim,
10
+ } from "./interfaces.fossglobalassets.js";
11
+ export type * from "./interfaces.fossglobalassets.js";
12
+ import {
13
+ ReleaseAssetConflictError,
14
+ assertReleaseAssetRecord,
15
+ assertReleaseAssetTag,
16
+ assertReleaseFrozenAssets,
17
+ normalizeReleaseAssetDestination,
18
+ openReleaseAssetFile,
19
+ releaseAssetTargets,
20
+ verifyReleaseAssetFile,
21
+ type IReleaseAssetDestination,
22
+ type IReleaseAssetTransferFailures,
23
+ type IReleaseAssetTransferLimits,
24
+ type IReleaseFrozenAsset,
25
+ type TReleaseAssetFileHandle,
26
+ } from "./helpers.releaseassets.js";
27
+ import {
28
+ ReleaseAssetRequestError,
29
+ ReleaseAssetTransferWatchdog,
30
+ assertReleaseAssetTransferLimits,
31
+ createReleaseAssetUploadBody,
32
+ defaultReleaseAssetTransferLimits,
33
+ describeReleaseAssetRequestFailure,
34
+ formatReleaseAssetSeconds,
35
+ readReleaseAssetResponse,
36
+ } from "./helpers.releaseassettransfer.js";
37
+
38
+ type IRepositoryRelease = plugins.fossglobalData.IRepositoryRelease;
39
+ type IRepositoryReleaseAsset = plugins.fossglobalData.IRepositoryReleaseAsset;
40
+ type IRepositoryReleaseCreateRequest =
41
+ plugins.fossglobalData.IRepositoryReleaseCreateRequest;
42
+ type IRepositoryReleaseUpdateRequest =
43
+ plugins.fossglobalData.IRepositoryReleaseUpdateRequest;
44
+ type IRepositoryReleaseListResponse =
45
+ plugins.fossglobalData.IRepositoryReleaseListResponse;
46
+ type IRepositoryReleaseResponse =
47
+ plugins.fossglobalData.IRepositoryReleaseResponse;
48
+ type IRepositoryReleaseAssetResponse =
49
+ plugins.fossglobalData.IRepositoryReleaseAssetResponse;
50
+
51
+ const target = "fossglobalAssets";
52
+ const { label, maximumAssets } = releaseAssetTargets[target];
53
+
54
+ /**
55
+ * The release list is the only read: the code host answers at most 1000
56
+ * releases with their assets in one response, without paging. 64 MiB holds
57
+ * them at 64 KiB each; a longer list fails closed until retention shortens it.
58
+ */
59
+ const maximumReleaseListBytes = 64 * 1024 * 1024;
60
+ const maximumListedReleases = 1000;
61
+ /** One release or asset, as a create, an update or an upload answers it. */
62
+ const maximumAnswerBytes = 1024 * 1024;
63
+ /** The code host's ids are opaque; anything else never enters a journal or message. */
64
+ const opaqueId = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
65
+ const objectId = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
66
+ const sha256Pattern = /^[a-f0-9]{64}$/;
67
+ /** The asset names the code host stores (`IRepositoryReleaseAsset.name`). */
68
+ const listedAssetName = /^[A-Za-z0-9][A-Za-z0-9._+@-]{0,254}$/;
69
+ /** A printable page link without whitespace or control characters. */
70
+ const printableUrl = /^[\x21-\x7e]{0,2048}$/;
71
+ /** The code host's user access tokens: `fgu_`, 32 to 256 visible characters. */
72
+ const userAccessToken = /^fgu_[\x21-\x7e]{28,252}$/;
73
+ const inspectAdvice = "inspect the retained release before another mutation.";
74
+ const inconclusive = `the result is inconclusive; ${inspectAdvice}`;
75
+ const commitOutcomeUnknown =
76
+ "the code host does not know whether its commit applied";
77
+
78
+ /**
79
+ * The destination holds something other than this release's frozen draft or
80
+ * asset. Terminal: the claim/inspect executor records a destination conflict.
81
+ */
82
+ export class FossglobalAssetConflictError extends ReleaseAssetConflictError {
83
+ constructor(message: string) {
84
+ super(message);
85
+ this.name = "FossglobalAssetConflictError";
86
+ }
87
+ }
88
+
89
+ /**
90
+ * A request ended without proving success or a conflict; the next inspection
91
+ * decides. The message carries a sanitized cause and never a URL, header,
92
+ * body or token.
93
+ */
94
+ export class FossglobalAssetInconclusiveError extends Error {
95
+ constructor(message: string) {
96
+ super(message);
97
+ this.name = "FossglobalAssetInconclusiveError";
98
+ }
99
+ }
100
+
101
+ /** The code host answered with a definite refusal or a redirect, never followed. */
102
+ export class FossglobalAssetHttpError extends Error {
103
+ constructor(
104
+ operation: string,
105
+ readonly status: number,
106
+ ) {
107
+ super(
108
+ status >= 300 && status < 400
109
+ ? `${label} asset ${operation} answered HTTP ${status}, a redirect, which requests to the code host never follow; the API origin must answer directly.`
110
+ : `${label} asset ${operation} returned HTTP ${status}; ${inspectAdvice}`,
111
+ );
112
+ this.name = "FossglobalAssetHttpError";
113
+ }
114
+ }
115
+
116
+ /**
117
+ * The release is published while frozen assets are missing, and it lists
118
+ * nothing foreign. Not terminal: setting it back to draft keeps its id, so a
119
+ * resume completes it. No asset is uploaded into a published release, where
120
+ * each would be public the moment it lands.
121
+ */
122
+ export class FossglobalReleaseStateChangedError extends Error {
123
+ constructor(tag: string) {
124
+ super(
125
+ `${label} release ${tag} is published without all of its frozen assets, and no asset is uploaded into a published release; set the release back to draft, then resume.`,
126
+ );
127
+ this.name = "FossglobalReleaseStateChangedError";
128
+ }
129
+ }
130
+
131
+ /** The transfer bound that ended a request. */
132
+ export type TFossglobalAssetTransferBound =
133
+ "response" | "stall" | "acknowledgement" | "rate";
134
+
135
+ /** A request ended by a transfer bound; its outcome is unknown. */
136
+ export class FossglobalAssetTimeoutError extends FossglobalAssetInconclusiveError {
137
+ constructor(
138
+ readonly bound: TFossglobalAssetTransferBound,
139
+ message: string,
140
+ ) {
141
+ super(message);
142
+ this.name = "FossglobalAssetTimeoutError";
143
+ }
144
+ }
145
+
146
+ const transferFailures: IReleaseAssetTransferFailures<FossglobalAssetTimeoutError> =
147
+ {
148
+ responseTimeout: (operation, limitMs) =>
149
+ new FossglobalAssetTimeoutError(
150
+ "response",
151
+ `${label} asset ${operation} received no response within ${formatReleaseAssetSeconds(limitMs)}; ${inconclusive}`,
152
+ ),
153
+ stalled: (operation, direction, limitMs, bytes) =>
154
+ new FossglobalAssetTimeoutError(
155
+ "stall",
156
+ `${label} asset ${operation} stalled: no bytes ${direction} for ${formatReleaseAssetSeconds(limitMs)} after ${bytes} bytes; ${inconclusive}`,
157
+ ),
158
+ notAcknowledged: (bytes, limitMs, minimumBytesPerSecond) =>
159
+ new FossglobalAssetTimeoutError(
160
+ "acknowledgement",
161
+ `${label} asset upload was not acknowledged: all ${bytes} bytes were sent, but no response arrived within ${formatReleaseAssetSeconds(limitMs)}, the allowance for its size at ${Math.round(minimumBytesPerSecond / 1024)} KiB/s; ${inconclusive}`,
162
+ ),
163
+ tooSlow: (
164
+ operation,
165
+ elapsedMs,
166
+ bytes,
167
+ expectedBytes,
168
+ minimumBytesPerSecond,
169
+ ) =>
170
+ new FossglobalAssetTimeoutError(
171
+ "rate",
172
+ `${label} asset ${operation} was still progressing but too slow: ${bytes} of ${expectedBytes} bytes after ${formatReleaseAssetSeconds(elapsedMs)}, below the ${Math.round(minimumBytesPerSecond / 1024)} KiB/s floor; ${inconclusive}`,
173
+ ),
174
+ };
175
+
176
+ /** The listed release fields this target reads; the rest of the wire shape is not its contract. */
177
+ type TListedRelease = Pick<
178
+ IRepositoryRelease,
179
+ | "releaseId"
180
+ | "tagName"
181
+ | "targetObjectId"
182
+ | "prerelease"
183
+ | "draft"
184
+ | "htmlUrl"
185
+ > & { assets: TListedAsset[] };
186
+ type TListedAsset = Pick<
187
+ IRepositoryReleaseAsset,
188
+ "assetId" | "name" | "sizeBytes" | "sha256"
189
+ >;
190
+
191
+ const record = (value: unknown): Record<string, unknown> =>
192
+ assertReleaseAssetRecord(target, value);
193
+
194
+ const parseAsset = (value: unknown): TListedAsset => {
195
+ const asset = record(value);
196
+ if (
197
+ typeof asset.assetId !== "string" ||
198
+ !opaqueId.test(asset.assetId) ||
199
+ typeof asset.name !== "string" ||
200
+ !listedAssetName.test(asset.name) ||
201
+ !Number.isSafeInteger(asset.sizeBytes) ||
202
+ (asset.sizeBytes as number) < 0 ||
203
+ typeof asset.sha256 !== "string" ||
204
+ !sha256Pattern.test(asset.sha256)
205
+ )
206
+ throw new Error(`Invalid ${label} release asset.`);
207
+ return {
208
+ assetId: asset.assetId,
209
+ name: asset.name,
210
+ sizeBytes: asset.sizeBytes as number,
211
+ sha256: asset.sha256,
212
+ };
213
+ };
214
+
215
+ const parseRelease = (value: unknown, tag: string): TListedRelease => {
216
+ const release = record(value);
217
+ if (
218
+ typeof release.releaseId !== "string" ||
219
+ !opaqueId.test(release.releaseId) ||
220
+ release.tagName !== tag ||
221
+ typeof release.targetObjectId !== "string" ||
222
+ !objectId.test(release.targetObjectId) ||
223
+ typeof release.prerelease !== "boolean" ||
224
+ typeof release.draft !== "boolean" ||
225
+ typeof release.htmlUrl !== "string" ||
226
+ !printableUrl.test(release.htmlUrl) ||
227
+ !Array.isArray(release.assets) ||
228
+ release.assets.length > maximumAssets
229
+ )
230
+ throw new Error(`Invalid ${label} release.`);
231
+ return {
232
+ releaseId: release.releaseId,
233
+ tagName: tag,
234
+ targetObjectId: release.targetObjectId,
235
+ prerelease: release.prerelease,
236
+ draft: release.draft,
237
+ htmlUrl: release.htmlUrl,
238
+ assets: release.assets.map(parseAsset),
239
+ };
240
+ };
241
+
242
+ const sameFrozenAsset = (
243
+ left: IReleaseFrozenAsset,
244
+ right: IReleaseFrozenAsset,
245
+ ): boolean =>
246
+ left.name === right.name &&
247
+ left.size === right.size &&
248
+ left.sha256 === right.sha256 &&
249
+ left.fileName === right.fileName &&
250
+ left.publicUrl === right.publicUrl;
251
+
252
+ /**
253
+ * A claim this release can hold for the tag at the destination: the tag
254
+ * object, the frozen set, and ids of the code host's form, the asset ids
255
+ * unique and recorded only once the release id is. The release journal's
256
+ * fossglobalAssets section is such a claim.
257
+ */
258
+ export function assertFossglobalReleaseClaim(
259
+ claim: unknown,
260
+ destination: IReleaseAssetDestination,
261
+ tag: string,
262
+ ): asserts claim is IFossglobalReleaseClaim {
263
+ const value = record(claim);
264
+ if (
265
+ typeof value.tagObjectId !== "string" ||
266
+ !objectId.test(value.tagObjectId) ||
267
+ (value.releaseId !== null &&
268
+ (typeof value.releaseId !== "string" ||
269
+ !opaqueId.test(value.releaseId))) ||
270
+ !Array.isArray(value.assets)
271
+ )
272
+ throw new Error(`Invalid ${label} release claim.`);
273
+ const assets = value.assets.map(record);
274
+ assertReleaseFrozenAssets(
275
+ target,
276
+ assets.map((entry) => entry.asset),
277
+ destination,
278
+ tag,
279
+ );
280
+ const assetIds = new Set<string>();
281
+ for (const { assetId } of assets) {
282
+ if (assetId === null) continue;
283
+ if (
284
+ value.releaseId === null ||
285
+ typeof assetId !== "string" ||
286
+ !opaqueId.test(assetId) ||
287
+ assetIds.has(assetId)
288
+ )
289
+ throw new Error(`Invalid ${label} release claim.`);
290
+ assetIds.add(assetId);
291
+ }
292
+ }
293
+
294
+ type TMethod = "GET" | "POST" | "PUT";
295
+
296
+ interface IApiRequest {
297
+ method: TMethod;
298
+ /** Below the repository's release API path. */
299
+ path: string;
300
+ success: 200 | 201;
301
+ maximumBytes: number;
302
+ json?: IRepositoryReleaseCreateRequest | IRepositoryReleaseUpdateRequest;
303
+ /** Streams exactly `size` bytes of the open file with a fixed `Content-Length`. */
304
+ upload?: { handle: TReleaseAssetFileHandle; size: number };
305
+ /** Statuses that leave this mutation's outcome unknown, with the reason. */
306
+ inconclusive?: Readonly<Partial<Record<number, string>>>;
307
+ }
308
+
309
+ /**
310
+ * The code host's native release API for one release tag. No method retries
311
+ * a mutation or sleeps; the release journal owns attempt admission.
312
+ */
313
+ export class FossglobalAssetsClient implements IFossglobalAssetsClient {
314
+ readonly #destination: IReleaseAssetDestination;
315
+ readonly #tag: string;
316
+ readonly #token: string;
317
+ readonly #fetch: typeof fetch;
318
+ readonly #limits: IReleaseAssetTransferLimits;
319
+ readonly #releasesUrl: string;
320
+ /** The release id this client's create answered, before a journal records it. */
321
+ #createdReleaseId: string | null = null;
322
+ /** The asset each upload of this client answered with, by name. */
323
+ readonly #answered = new Map<string, TListedAsset>();
324
+
325
+ constructor(options: IFossglobalAssetsClientOptions) {
326
+ this.#destination = normalizeReleaseAssetDestination(
327
+ target,
328
+ options.destination,
329
+ );
330
+ assertReleaseAssetTag(target, options.tag);
331
+ if (
332
+ typeof options.token !== "string" ||
333
+ !userAccessToken.test(options.token)
334
+ )
335
+ throw new Error(
336
+ `${label} assets require an fgu_ user access token in the configured environment variable.`,
337
+ );
338
+ this.#tag = options.tag;
339
+ this.#token = options.token;
340
+ this.#fetch = options.fetchImplementation ?? fetch;
341
+ this.#limits = assertReleaseAssetTransferLimits(target, {
342
+ responseTimeoutMs:
343
+ options.responseTimeoutMs ??
344
+ defaultReleaseAssetTransferLimits.responseTimeoutMs,
345
+ stallTimeoutMs:
346
+ options.stallTimeoutMs ??
347
+ defaultReleaseAssetTransferLimits.stallTimeoutMs,
348
+ minimumBytesPerSecond:
349
+ options.minimumBytesPerSecond ??
350
+ defaultReleaseAssetTransferLimits.minimumBytesPerSecond,
351
+ });
352
+ const { apiOrigin, owner, repository } = this.#destination;
353
+ this.#releasesUrl = `${apiOrigin}/api/v1/repositories/${owner}/${repository}/releases`;
354
+ }
355
+
356
+ /**
357
+ * One authenticated request to the release API: the token goes to the API
358
+ * origin only, a redirect is refused, and a transfer ends only by its bounds.
359
+ */
360
+ async #request(request: IApiRequest): Promise<unknown> {
361
+ const operation = request.upload ? "upload" : request.method;
362
+ const watchdog = new ReleaseAssetTransferWatchdog(
363
+ transferFailures,
364
+ operation,
365
+ this.#limits,
366
+ (request.upload?.size ?? 0) + request.maximumBytes,
367
+ request.upload?.size,
368
+ );
369
+ let response: Response | undefined;
370
+ try {
371
+ const headers: Record<string, string> = {
372
+ Accept: "application/json",
373
+ Authorization: `Bearer ${this.#token}`,
374
+ };
375
+ let body: BodyInit | undefined;
376
+ if (request.upload) {
377
+ body = createReleaseAssetUploadBody(
378
+ target,
379
+ request.upload.handle,
380
+ request.upload.size,
381
+ watchdog,
382
+ );
383
+ headers["Content-Type"] = "application/octet-stream";
384
+ // The code host refuses a chunked body (415); a stream body with this
385
+ // header makes fetch send exactly this length.
386
+ headers["Content-Length"] = String(request.upload.size);
387
+ watchdog.progress("sent", 0);
388
+ } else {
389
+ if (request.json) {
390
+ body = JSON.stringify(request.json);
391
+ headers["Content-Type"] = "application/json";
392
+ }
393
+ watchdog.awaitResponse();
394
+ }
395
+ const init: RequestInit & { duplex?: "half" } = {
396
+ method: request.method,
397
+ redirect: "manual",
398
+ signal: watchdog.signal,
399
+ headers,
400
+ };
401
+ if (body !== undefined) init.body = body;
402
+ if (request.upload) init.duplex = "half";
403
+ response = await this.#fetch(`${this.#releasesUrl}${request.path}`, init);
404
+ watchdog.progress("received", 0);
405
+ if (response.status !== request.success) {
406
+ const reason = request.inconclusive?.[response.status];
407
+ if (reason)
408
+ throw new FossglobalAssetInconclusiveError(
409
+ `${label} asset ${operation} answered HTTP ${response.status}: ${reason}; ${inconclusive}`,
410
+ );
411
+ throw new FossglobalAssetHttpError(operation, response.status);
412
+ }
413
+ return JSON.parse(
414
+ (
415
+ await readReleaseAssetResponse(
416
+ target,
417
+ response,
418
+ request.maximumBytes,
419
+ watchdog,
420
+ )
421
+ ).toString("utf8"),
422
+ );
423
+ } catch (error) {
424
+ // Never pass on response text, fetch errors, URLs or causes that can carry the token.
425
+ if (watchdog.failure) throw watchdog.failure;
426
+ if (
427
+ error instanceof FossglobalAssetHttpError ||
428
+ error instanceof FossglobalAssetInconclusiveError
429
+ )
430
+ throw error;
431
+ throw new FossglobalAssetInconclusiveError(
432
+ `${label} asset ${operation} result is inconclusive ${describeReleaseAssetRequestFailure(
433
+ error,
434
+ {
435
+ status: response?.status,
436
+ progress: `${watchdog.bytes} bytes transferred`,
437
+ },
438
+ )}; ${inspectAdvice}`,
439
+ );
440
+ } finally {
441
+ watchdog.close();
442
+ if (response?.body && !response.body.locked)
443
+ await response.body.cancel().catch(() => undefined);
444
+ }
445
+ }
446
+
447
+ /** The release for the tag from the authenticated release list, drafts included. */
448
+ async #listedRelease(): Promise<TListedRelease | null> {
449
+ const answer = record(
450
+ await this.#request({
451
+ method: "GET",
452
+ path: "",
453
+ success: 200,
454
+ maximumBytes: maximumReleaseListBytes,
455
+ }),
456
+ );
457
+ const releases =
458
+ answer["releases" satisfies keyof IRepositoryReleaseListResponse];
459
+ if (!Array.isArray(releases) || releases.length > maximumListedReleases)
460
+ throw new Error(`Invalid ${label} release list.`);
461
+ const forTag = releases.filter(
462
+ (entry) => record(entry).tagName === this.#tag,
463
+ );
464
+ if (forTag.length > 1)
465
+ throw new FossglobalAssetConflictError(
466
+ `${label} lists more than one release for ${this.#tag}.`,
467
+ );
468
+ return forTag.length === 1 ? parseRelease(forTag[0], this.#tag) : null;
469
+ }
470
+
471
+ #assertClaim(claim: IFossglobalReleaseClaim): void {
472
+ assertFossglobalReleaseClaim(claim, this.#destination, this.#tag);
473
+ }
474
+
475
+ /** The claimed release id, or the one this client's create answered. */
476
+ #recordedReleaseId(claim: IFossglobalReleaseClaim): string | null {
477
+ if (
478
+ claim.releaseId !== null &&
479
+ this.#createdReleaseId !== null &&
480
+ claim.releaseId !== this.#createdReleaseId
481
+ )
482
+ throw new FossglobalAssetConflictError(
483
+ `The recorded ${label} release for ${this.#tag} is not the one this run created.`,
484
+ );
485
+ return claim.releaseId ?? this.#createdReleaseId;
486
+ }
487
+
488
+ /**
489
+ * The claimed asset id, or the one this client's upload answered; an upload
490
+ * answered with other bytes than the frozen asset stays a conflict.
491
+ */
492
+ #recordedAssetId(claimed: IFossglobalClaimedAsset): string | null {
493
+ const { asset } = claimed;
494
+ const answered = this.#answered.get(asset.name);
495
+ if (!answered) return claimed.assetId;
496
+ if (answered.sizeBytes !== asset.size || answered.sha256 !== asset.sha256)
497
+ throw new FossglobalAssetConflictError(
498
+ `${label} stored ${asset.name} with other bytes than the frozen asset.`,
499
+ );
500
+ if (claimed.assetId !== null && claimed.assetId !== answered.assetId)
501
+ throw new FossglobalAssetConflictError(
502
+ `The recorded ${label} asset ${asset.name} is not the one this run uploaded.`,
503
+ );
504
+ return answered.assetId;
505
+ }
506
+
507
+ /**
508
+ * Whether the listed release for the tag is this release's: the recorded id
509
+ * in either draft state, or with no id recorded the draft a crash between
510
+ * its create and the journal write left behind. Both must target the tag
511
+ * object as a full release.
512
+ */
513
+ #ownedRelease(
514
+ listed: TListedRelease,
515
+ claim: IFossglobalReleaseClaim,
516
+ ): IFossglobalRelease {
517
+ const recorded = this.#recordedReleaseId(claim);
518
+ if (recorded !== null && listed.releaseId !== recorded)
519
+ throw new FossglobalAssetConflictError(
520
+ `A ${label} release for ${this.#tag} other than the recorded one holds the tag.`,
521
+ );
522
+ if (listed.targetObjectId !== claim.tagObjectId || listed.prerelease)
523
+ throw new FossglobalAssetConflictError(
524
+ `The ${label} release for ${this.#tag} is not a full release of the release tag object.`,
525
+ );
526
+ if (
527
+ recorded === null &&
528
+ (!listed.draft ||
529
+ !listed.assets.every((listedAsset) =>
530
+ claim.assets.some(
531
+ ({ asset }) =>
532
+ asset.name === listedAsset.name &&
533
+ asset.size === listedAsset.sizeBytes &&
534
+ asset.sha256 === listedAsset.sha256,
535
+ ),
536
+ ))
537
+ )
538
+ throw new FossglobalAssetConflictError(
539
+ `A ${label} release for ${this.#tag} that this release did not record holds the tag.`,
540
+ );
541
+ return {
542
+ releaseId: listed.releaseId,
543
+ draft: listed.draft,
544
+ htmlUrl: listed.htmlUrl,
545
+ };
546
+ }
547
+
548
+ /** The recorded release read from the list, every listed asset held against the claim. */
549
+ async #inspect(
550
+ claim: IFossglobalReleaseClaim,
551
+ ): Promise<IFossglobalAssetInspection> {
552
+ this.#assertClaim(claim);
553
+ if (this.#recordedReleaseId(claim) === null)
554
+ throw new Error(
555
+ `${label} assets of ${this.#tag} need the release recorded first.`,
556
+ );
557
+ const listed = await this.#listedRelease();
558
+ if (!listed)
559
+ throw new FossglobalAssetConflictError(
560
+ `The recorded ${label} release for ${this.#tag} is gone.`,
561
+ );
562
+ return this.#classify(listed, claim);
563
+ }
564
+
565
+ /**
566
+ * A frozen name with the frozen size and SHA-256, and the recorded id once
567
+ * there is one, is present; any other listed asset is a conflict.
568
+ */
569
+ #classify(
570
+ listed: TListedRelease,
571
+ claim: IFossglobalReleaseClaim,
572
+ ): IFossglobalAssetInspection {
573
+ const release = this.#ownedRelease(listed, claim);
574
+ const recordedAssetIds = new Map(
575
+ claim.assets.map((claimed) => [
576
+ claimed.asset.name,
577
+ this.#recordedAssetId(claimed),
578
+ ]),
579
+ );
580
+ const present: IFossglobalPresentAsset[] = [];
581
+ const names = new Set<string>();
582
+ const assetIds = new Set<string>();
583
+ for (const listedAsset of listed.assets) {
584
+ const claimed = claim.assets.find(
585
+ ({ asset }) => asset.name === listedAsset.name,
586
+ );
587
+ if (!claimed)
588
+ throw new FossglobalAssetConflictError(
589
+ `The ${label} release for ${this.#tag} holds an asset outside the frozen set.`,
590
+ );
591
+ const { asset } = claimed;
592
+ if (names.has(asset.name) || assetIds.has(listedAsset.assetId))
593
+ throw new FossglobalAssetConflictError(
594
+ `The ${label} release for ${this.#tag} lists an asset twice.`,
595
+ );
596
+ names.add(asset.name);
597
+ assetIds.add(listedAsset.assetId);
598
+ if (
599
+ listedAsset.sizeBytes !== asset.size ||
600
+ listedAsset.sha256 !== asset.sha256
601
+ )
602
+ throw new FossglobalAssetConflictError(
603
+ `${label} asset ${asset.name} holds other bytes than the frozen asset.`,
604
+ );
605
+ const recorded = recordedAssetIds.get(asset.name) ?? null;
606
+ if (recorded !== null && listedAsset.assetId !== recorded)
607
+ throw new FossglobalAssetConflictError(
608
+ `${label} asset ${asset.name} is not the upload recorded for it.`,
609
+ );
610
+ present.push({ asset, assetId: listedAsset.assetId });
611
+ }
612
+ return {
613
+ release,
614
+ present,
615
+ missing: claim.assets
616
+ .filter(({ asset }) => !names.has(asset.name))
617
+ .map(({ asset }) => asset),
618
+ };
619
+ }
620
+
621
+ /**
622
+ * A published release holds the complete frozen set or nothing more happens
623
+ * to it: with only part of the set (and nothing foreign, which the
624
+ * classification refused already) it waits for a person to set it back to
625
+ * draft.
626
+ */
627
+ #refusePublishedIncomplete(inspection: IFossglobalAssetInspection): void {
628
+ if (!inspection.release.draft && inspection.missing.length !== 0)
629
+ throw new FossglobalReleaseStateChangedError(this.#tag);
630
+ }
631
+
632
+ public async preflight(claim: IFossglobalReleaseClaim | null): Promise<void> {
633
+ if (claim) this.#assertClaim(claim);
634
+ const listed = await this.#listedRelease();
635
+ if (!listed) return;
636
+ if (!claim)
637
+ throw new FossglobalAssetConflictError(
638
+ `A ${label} release for ${this.#tag} exists before this release created one.`,
639
+ );
640
+ if (this.#recordedReleaseId(claim) === null)
641
+ this.#ownedRelease(listed, claim);
642
+ else this.#classify(listed, claim);
643
+ }
644
+
645
+ public async inspectRelease(
646
+ claim: IFossglobalReleaseClaim,
647
+ ): Promise<IFossglobalRelease | null> {
648
+ this.#assertClaim(claim);
649
+ const listed = await this.#listedRelease();
650
+ return listed ? this.#ownedRelease(listed, claim) : null;
651
+ }
652
+
653
+ public async createRelease(
654
+ claim: IFossglobalReleaseClaim,
655
+ ): Promise<IFossglobalRelease> {
656
+ this.#assertClaim(claim);
657
+ if (this.#recordedReleaseId(claim) !== null)
658
+ throw new Error(
659
+ `The ${label} release for ${this.#tag} is recorded already; it is never created twice.`,
660
+ );
661
+ // Nothing is public before the complete set is stored; see publishRelease.
662
+ const request: IRepositoryReleaseCreateRequest = {
663
+ tagName: this.#tag,
664
+ name: this.#tag,
665
+ prerelease: false,
666
+ draft: true,
667
+ };
668
+ const answer = record(
669
+ await this.#request({
670
+ method: "POST",
671
+ path: "",
672
+ success: 201,
673
+ maximumBytes: maximumAnswerBytes,
674
+ json: request,
675
+ inconclusive: {
676
+ 409: "a release for the tag exists already",
677
+ 503: commitOutcomeUnknown,
678
+ },
679
+ }),
680
+ );
681
+ const created = parseRelease(
682
+ answer["release" satisfies keyof IRepositoryReleaseResponse],
683
+ this.#tag,
684
+ );
685
+ if (
686
+ !created.draft ||
687
+ created.prerelease ||
688
+ created.targetObjectId !== claim.tagObjectId ||
689
+ created.assets.length !== 0
690
+ )
691
+ throw new FossglobalAssetConflictError(
692
+ `${label} created the release for ${this.#tag} other than as an empty draft of the release tag object.`,
693
+ );
694
+ this.#createdReleaseId = created.releaseId;
695
+ return {
696
+ releaseId: created.releaseId,
697
+ draft: created.draft,
698
+ htmlUrl: created.htmlUrl,
699
+ };
700
+ }
701
+
702
+ public async inspectAssets(
703
+ claim: IFossglobalReleaseClaim,
704
+ ): Promise<IFossglobalAssetInspection> {
705
+ return this.#inspect(claim);
706
+ }
707
+
708
+ public async uploadAsset(
709
+ claim: IFossglobalReleaseClaim,
710
+ asset: IReleaseFrozenAsset,
711
+ artifactDirectory: string,
712
+ ): Promise<IFossglobalPresentAsset> {
713
+ this.#assertClaim(claim);
714
+ if (!claim.assets.some((claimed) => sameFrozenAsset(claimed.asset, asset)))
715
+ throw new Error(`${label} uploads only frozen assets of the claim.`);
716
+ const handle = await openReleaseAssetFile(
717
+ target,
718
+ plugins.path.join(artifactDirectory, asset.fileName),
719
+ );
720
+ try {
721
+ await verifyReleaseAssetFile(target, handle, asset);
722
+ const inspection = await this.#inspect(claim);
723
+ // The code host takes uploads into a published release too; this client
724
+ // never sends one.
725
+ this.#refusePublishedIncomplete(inspection);
726
+ const present = inspection.present.find(
727
+ (entry) => entry.asset.name === asset.name,
728
+ );
729
+ // Already stored with the frozen bytes: nothing is sent again. A
730
+ // published release holds every frozen asset here, so an upload only
731
+ // ever goes into a draft.
732
+ if (present) return present;
733
+ const answer = record(
734
+ await this.#request({
735
+ method: "POST",
736
+ path: `/${encodeURIComponent(this.#tag)}/assets/${encodeURIComponent(asset.name)}`,
737
+ success: 201,
738
+ maximumBytes: maximumAnswerBytes,
739
+ upload: { handle, size: asset.size },
740
+ inconclusive: {
741
+ 409: "the name may still be held by an upload the code host never finished, which it reaps once abandoned",
742
+ 503: commitOutcomeUnknown,
743
+ },
744
+ }),
745
+ );
746
+ const stored = parseAsset(
747
+ answer["asset" satisfies keyof IRepositoryReleaseAssetResponse],
748
+ );
749
+ if (stored.name !== asset.name)
750
+ throw new Error(`Invalid ${label} upload answer.`);
751
+ this.#answered.set(asset.name, stored);
752
+ if (stored.sizeBytes !== asset.size || stored.sha256 !== asset.sha256)
753
+ throw new FossglobalAssetConflictError(
754
+ `${label} stored ${asset.name} with other bytes than the frozen asset; the release is not published.`,
755
+ );
756
+ return { asset, assetId: stored.assetId };
757
+ } finally {
758
+ await handle.close();
759
+ }
760
+ }
761
+
762
+ public async verifyComplete(
763
+ claim: IFossglobalReleaseClaim,
764
+ ): Promise<IFossglobalRelease> {
765
+ const inspection = await this.#inspect(claim);
766
+ this.#refusePublishedIncomplete(inspection);
767
+ if (inspection.missing.length !== 0)
768
+ throw new Error(
769
+ `${label} asset set of ${this.#tag} is incomplete; npm publication is blocked.`,
770
+ );
771
+ return inspection.release;
772
+ }
773
+
774
+ public async publishRelease(claim: IFossglobalReleaseClaim): Promise<void> {
775
+ const before = await this.#inspect(claim);
776
+ this.#refusePublishedIncomplete(before);
777
+ if (before.missing.length !== 0)
778
+ throw new Error(
779
+ `${label} asset set of ${this.#tag} is incomplete; the release stays a draft.`,
780
+ );
781
+ if (before.release.draft) {
782
+ let failure: unknown;
783
+ try {
784
+ const request: IRepositoryReleaseUpdateRequest = { draft: false };
785
+ const answer = record(
786
+ await this.#request({
787
+ method: "PUT",
788
+ path: `/${encodeURIComponent(this.#tag)}`,
789
+ success: 200,
790
+ maximumBytes: maximumAnswerBytes,
791
+ json: request,
792
+ inconclusive: {
793
+ 409: "the release changed concurrently",
794
+ 503: commitOutcomeUnknown,
795
+ },
796
+ }),
797
+ );
798
+ const updated = parseRelease(
799
+ answer["release" satisfies keyof IRepositoryReleaseResponse],
800
+ this.#tag,
801
+ );
802
+ if (updated.releaseId !== before.release.releaseId)
803
+ throw new FossglobalAssetConflictError(
804
+ `${label} published a release for ${this.#tag} other than the recorded one.`,
805
+ );
806
+ } catch (error) {
807
+ if (error instanceof ReleaseAssetConflictError) throw error;
808
+ failure = error;
809
+ }
810
+ // One mutation, then the list decides: published with exactly the
811
+ // frozen set is verified, whatever the update answered.
812
+ const after = await this.#inspect(claim);
813
+ this.#refusePublishedIncomplete(after);
814
+ if (after.release.draft)
815
+ throw (
816
+ failure ??
817
+ new FossglobalAssetInconclusiveError(
818
+ `${label} release ${this.#tag} is still not published with its complete asset set; ${inspectAdvice}`,
819
+ )
820
+ );
821
+ }
822
+ for (const { asset } of claim.assets)
823
+ await this.#proveAnonymousAvailability(asset);
824
+ }
825
+
826
+ /**
827
+ * Proves a published asset is served anonymously as frozen, from the HEAD of
828
+ * its frozen URL alone: the code host hashed the upload as it arrived and
829
+ * again when stored, and HEAD answers the stored digest without a download.
830
+ */
831
+ async #proveAnonymousAvailability(asset: IReleaseFrozenAsset): Promise<void> {
832
+ const watchdog = new ReleaseAssetTransferWatchdog(
833
+ transferFailures,
834
+ "HEAD",
835
+ this.#limits,
836
+ 0,
837
+ );
838
+ let response: Response | undefined;
839
+ try {
840
+ watchdog.awaitResponse();
841
+ response = await this.#fetch(asset.publicUrl, {
842
+ method: "HEAD",
843
+ redirect: "manual",
844
+ signal: watchdog.signal,
845
+ headers: { "Accept-Encoding": "identity" },
846
+ });
847
+ watchdog.progress("received", 0);
848
+ const length = response.headers.get("content-length");
849
+ const digest = response.headers.get("x-release-asset-sha256");
850
+ const etag = response.headers.get("etag");
851
+ if (
852
+ response.status !== 200 ||
853
+ (response.headers.get("content-encoding") ?? "identity") !==
854
+ "identity" ||
855
+ length === null ||
856
+ !/^\d+$/.test(length) ||
857
+ digest === null ||
858
+ etag === null
859
+ )
860
+ throw new ReleaseAssetRequestError(
861
+ target,
862
+ "asset-not-anonymously-downloadable",
863
+ );
864
+ if (
865
+ Number(length) !== asset.size ||
866
+ digest !== asset.sha256 ||
867
+ etag !== `"${asset.sha256}"`
868
+ )
869
+ throw new FossglobalAssetConflictError(
870
+ `${label} serves ${asset.name} anonymously as other bytes than the frozen asset.`,
871
+ );
872
+ } catch (error) {
873
+ if (watchdog.failure) throw watchdog.failure;
874
+ if (error instanceof FossglobalAssetConflictError) throw error;
875
+ throw new FossglobalAssetInconclusiveError(
876
+ `${label} public asset availability of ${asset.name} is inconclusive ${describeReleaseAssetRequestFailure(
877
+ error,
878
+ { status: response?.status, progress: "headers only" },
879
+ )}; inspect the published release.`,
880
+ );
881
+ } finally {
882
+ watchdog.close();
883
+ if (response?.body) await response.body.cancel().catch(() => undefined);
884
+ }
885
+ }
886
+ }