@git.zone/cli 8.5.1 → 8.7.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 (40) hide show
  1. package/assets/templates/asset_tspack_release_gitea/.gitea/workflows/release.yml +12 -18
  2. package/assets/templates/asset_tspack_release_gitea/scripts/gitzone-gitea-tag.d.mts +22 -0
  3. package/assets/templates/asset_tspack_release_gitea/scripts/gitzone-gitea-tag.mjs +48 -0
  4. package/assets/templates/asset_tspack_release_gitea/scripts/gitzone-release-api.mjs +244 -74
  5. package/assets/templates/asset_tspack_release_gitea/scripts/gitzone-sealed-release.mjs +103 -38
  6. package/assets/templates/vscode/.vscode/settings.json +57 -0
  7. package/dist_ts/00_commitinfo_data.js +1 -1
  8. package/dist_ts/classes.gitzoneconfig.d.ts +3 -0
  9. package/dist_ts/classes.gitzoneconfig.js +1 -1
  10. package/dist_ts/helpers.objects.d.ts +2 -0
  11. package/dist_ts/helpers.objects.js +3 -0
  12. package/dist_ts/helpers.packagefiles.d.ts +74 -0
  13. package/dist_ts/helpers.packagefiles.js +177 -0
  14. package/dist_ts/helpers.workflow.d.ts +18 -0
  15. package/dist_ts/helpers.workflow.js +45 -2
  16. package/dist_ts/mod_config/index.js +69 -2
  17. package/dist_ts/mod_format/formatters/assets.formatter.js +2 -1
  18. package/dist_ts/mod_format/formatters/packagejson.formatter.js +8 -27
  19. package/dist_ts/mod_release/helpers.giteaassets.d.ts +4 -14
  20. package/dist_ts/mod_release/helpers.giteaassets.js +20 -35
  21. package/dist_ts/mod_release/helpers.npmartifactcheck.d.ts +93 -0
  22. package/dist_ts/mod_release/helpers.npmartifactcheck.js +279 -0
  23. package/dist_ts/mod_release/index.d.ts +15 -0
  24. package/dist_ts/mod_release/index.js +82 -17
  25. package/dist_ts/plugins.d.ts +2 -1
  26. package/dist_ts/plugins.js +3 -2
  27. package/package.json +2 -1
  28. package/readme.md +147 -33
  29. package/ts/00_commitinfo_data.ts +1 -1
  30. package/ts/classes.gitzoneconfig.ts +3 -0
  31. package/ts/helpers.objects.ts +5 -0
  32. package/ts/helpers.packagefiles.ts +273 -0
  33. package/ts/helpers.workflow.ts +70 -1
  34. package/ts/mod_config/index.ts +78 -0
  35. package/ts/mod_format/formatters/assets.formatter.ts +1 -0
  36. package/ts/mod_format/formatters/packagejson.formatter.ts +7 -27
  37. package/ts/mod_release/helpers.giteaassets.ts +28 -44
  38. package/ts/mod_release/helpers.npmartifactcheck.ts +397 -0
  39. package/ts/mod_release/index.ts +115 -26
  40. package/ts/plugins.ts +2 -0
@@ -31,7 +31,9 @@ jobs:
31
31
  deno eval --no-config --no-lock --no-npm --no-remote 'if (Deno.version.deno !== "{{assets.sealedRelease.denoVersion}}") throw new Error("Deno compiler version does not match the release pin");'
32
32
  - name: Install frozen dependencies
33
33
  run: pnpm install --frozen-lockfile
34
- - name: Find the original retained release
34
+ # The draft release is the retention: the sealed files are uploaded to a draft, read back and
35
+ # hashed, and published only as a complete set. A rerun resumes from a complete draft without building.
36
+ - name: Find the retained release
35
37
  id: retention
36
38
  env:
37
39
  GITHUB_TOKEN: ${-{ secrets.GITHUB_TOKEN }-}
@@ -40,27 +42,19 @@ jobs:
40
42
  if: steps.retention.outputs.retained != 'true'
41
43
  id: prepared
42
44
  run: node scripts/gitzone-sealed-release.mjs prepare
43
- # Gitea's REST retention API requires finalized v4 artifacts.
44
- # Gitea Runner 3.3.2+ supports these stock actions through its results service.
45
- - name: Retain the complete output before publication
45
+ - name: Retain the sealed output in the draft release
46
46
  if: steps.retention.outputs.retained != 'true'
47
- uses: https://github.com/actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
48
- with:
49
- name: ${-{ steps.retention.outputs.artifact }-}
50
- path: ${-{ steps.retention.outputs.output }-}/
51
- if-no-files-found: error
52
- retention-days: 90
53
- - name: Download retained bytes into a fresh directory
54
- uses: https://github.com/actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
55
- with:
56
- name: ${-{ steps.retention.outputs.artifact }-}
57
- path: dist_gitzone_retained
58
- - name: Verify retained component and complete archives
59
47
  env:
48
+ GITHUB_TOKEN: ${-{ secrets.GITHUB_TOKEN }-}
60
49
  EXPECTED_MANIFEST: ${-{ steps.prepared.outputs.manifest }-}
50
+ run: node scripts/gitzone-sealed-release.mjs retain
51
+ - name: Restore and verify the retained release
52
+ if: steps.retention.outputs.retained == 'true'
53
+ env:
54
+ EXPECTED_MANIFEST: ${-{ steps.retention.outputs.manifest }-}
61
55
  run: node scripts/gitzone-sealed-release.mjs restore
62
- - name: Publish or resume the verified draft
56
+ - name: Publish or verify the retained release
63
57
  env:
64
58
  GITHUB_TOKEN: ${-{ secrets.GITHUB_TOKEN }-}
65
- EXPECTED_MANIFEST: ${-{ steps.prepared.outputs.manifest }-}
59
+ EXPECTED_MANIFEST: ${-{ steps.prepared.outputs.manifest || steps.retention.outputs.manifest }-}
66
60
  run: node scripts/gitzone-sealed-release.mjs publish
@@ -0,0 +1,22 @@
1
+ // Types for gitzone-gitea-tag.mjs, which `gitzone release` imports from its package. Not rendered into projects.
2
+
3
+ export declare const giteaTagProcessingTimeoutMs: number;
4
+ export declare const giteaTagProcessingPollIntervalMs: number;
5
+
6
+ export declare const giteaReleasePagePath: (owner: string, repository: string, tag: string) => string;
7
+
8
+ export type TGiteaTagProcessingResult =
9
+ | { outcome: 'processed' }
10
+ | { outcome: 'unexpected'; status: number }
11
+ | { outcome: 'timeout'; elapsedMs: number };
12
+
13
+ export interface IGiteaTagProcessingWait {
14
+ /** The anonymous HTTP status of the tag's public release page. */
15
+ pageStatus: () => Promise<number>;
16
+ timeoutMs?: number;
17
+ pollIntervalMs?: number;
18
+ /** Called on the first unprocessed answer and then at most once a minute. */
19
+ onWaiting?: (elapsedMs: number) => void;
20
+ }
21
+
22
+ export declare function awaitGiteaTagProcessed(options: IGiteaTagProcessingWait): Promise<TGiteaTagProcessingResult>;
@@ -0,0 +1,48 @@
1
+ // Managed by GitZone's asset_tspack_release_gitea template.
2
+ // GitZone's one implementation of the wait for Gitea's tag processing: `gitzone release` imports this
3
+ // file from its package, and the sealed release workflow runs this rendered copy.
4
+
5
+ /** Gitea processes a pushed tag in its push queue after the push returned; a busy queue has taken more than 90 s. */
6
+ export const giteaTagProcessingTimeoutMs = 15 * 60_000;
7
+ export const giteaTagProcessingPollIntervalMs = 5_000;
8
+ const waitingReportIntervalMs = 60_000;
9
+
10
+ /** The public page of a tag's release, relative to the Gitea origin. */
11
+ export const giteaReleasePagePath = (owner, repository, tag) =>
12
+ `/${owner}/${repository}/releases/tag/${encodeURIComponent(tag)}`;
13
+
14
+ /**
15
+ * Waits until Gitea has processed a pushed tag, so a draft created afterwards stays a draft.
16
+ *
17
+ * Gitea handles a tag push in its push queue after the push returned: it writes a tag-only release
18
+ * row for the tag, or, when a release for the tag already exists, sets `draft: false` on it (Gitea
19
+ * 1.27.3, services/repository/push.go, pushUpdateAddTags). A draft created before that runs is
20
+ * published by Gitea with whatever attachments it has. Once the tag-only row exists, creating the
21
+ * release converts that row into the draft in place, and the processed push never touches it again.
22
+ * The API hides tag-only rows; the public release page (`giteaReleasePagePath`) answers 200 for a
23
+ * tag-only row and a published release, and 404 for a draft and for a tag Gitea has not processed.
24
+ * The caller has seen no release for the tag through the API, so a 200 proves the tag-only row.
25
+ *
26
+ * `pageStatus` returns the anonymous HTTP status of that page. The result names the outcome; the
27
+ * caller decides how to report a timeout or an unexpected status, and creates nothing on either.
28
+ */
29
+ export async function awaitGiteaTagProcessed({ pageStatus, timeoutMs = giteaTagProcessingTimeoutMs,
30
+ pollIntervalMs = giteaTagProcessingPollIntervalMs, onWaiting }) {
31
+ if (typeof pageStatus !== 'function' || ![timeoutMs, pollIntervalMs].every((value) => Number.isSafeInteger(value) && value > 0)) {
32
+ throw new Error('Invalid Gitea tag processing wait.');
33
+ }
34
+ const started = Date.now();
35
+ let reportedAt;
36
+ while (true) {
37
+ const status = await pageStatus();
38
+ if (status === 200) return { outcome: 'processed' };
39
+ if (status !== 404) return { outcome: 'unexpected', status };
40
+ const elapsedMs = Date.now() - started;
41
+ if (elapsedMs >= timeoutMs) return { outcome: 'timeout', elapsedMs };
42
+ if (reportedAt === undefined || elapsedMs - reportedAt >= waitingReportIntervalMs) {
43
+ reportedAt = elapsedMs;
44
+ onWaiting?.(elapsedMs);
45
+ }
46
+ await new Promise((resolve) => setTimeout(resolve, Math.min(pollIntervalMs, timeoutMs - elapsedMs)));
47
+ }
48
+ }
@@ -1,38 +1,68 @@
1
1
  // Managed by GitZone's asset_tspack_release_gitea template.
2
2
  import { createHash } from 'node:crypto';
3
+ import { awaitGiteaTagProcessed, giteaReleasePagePath } from './gitzone-gitea-tag.mjs';
3
4
 
4
5
  const requireValue = (value, message) => { if (!value) throw new Error(message); };
5
6
  const identifier = (value) => Number.isSafeInteger(value) && value > 0;
7
+ const digestPattern = /^[a-f0-9]{64}$/;
8
+ const namePattern = /^[a-zA-Z0-9_.-]+$/;
9
+ const releaseBody = (manifestSha256) => `Sealed TsPack release. Manifest SHA-256: ${manifestSha256}. See changelog.md at this tag.`;
10
+ const bodyDigest = (body) => /^Sealed TsPack release\. Manifest SHA-256: ([a-f0-9]{64})\. See changelog\.md at this tag\.$/.exec(body ?? '')?.[1] ?? null;
11
+ const manifestName = 'tspack-manifest.json';
12
+ const checksumsName = 'SHA256SUMS.txt';
13
+ // TsPack's own bounds for release metadata.
14
+ const manifestLimit = 16 * 1024 * 1024;
15
+ const checksumsLimit = 64 * 1024;
6
16
 
7
- /** Gitea transport for retained, already-verified TsPack files. No compiler or packer runs here. */
17
+ /**
18
+ * Gitea transport for sealed TsPack files. No compiler or packer runs here.
19
+ *
20
+ * The draft release is the retention: sealed files are uploaded to a draft, read back and hashed,
21
+ * and published only as a complete verified set. Gitea shows a draft, its attachment list and its
22
+ * downloads only to accounts with write access, so a draft has never been public. A draft whose
23
+ * attachment conflicts with the sealed set is corrected by replacing that attachment, and only
24
+ * while the release reads back as a draft both with the token and anonymously. A published
25
+ * attachment is never replaced.
26
+ */
8
27
  export class GiteaSealedRelease {
9
- constructor({ server, repository, token, fetch: fetchArg = globalThis.fetch }) {
28
+ constructor({ server, repository, token, fetch: fetchArg = globalThis.fetch, log = (message) => console.error(message),
29
+ tagProcessing = {} }) {
10
30
  const origin = new URL(server);
11
31
  requireValue(origin.protocol === 'https:' && !origin.username && !origin.password &&
12
32
  origin.pathname === '/' && !origin.search && !origin.hash &&
13
- /^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repository) && typeof token === 'string' && token.length > 0,
33
+ /^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(repository) && typeof token === 'string' && token.length > 0 &&
34
+ typeof log === 'function',
14
35
  'Expected an HTTPS Gitea origin, repository and job token.');
15
36
  this.origin = origin.origin;
37
+ this.repository = repository;
16
38
  this.base = `${origin.origin}/api/v1/repos/${repository}`;
17
39
  this.token = token;
18
40
  this.fetch = fetchArg;
41
+ this.log = log;
42
+ this.tagProcessing = tagProcessing;
19
43
  }
20
44
 
21
- async response(url, options = {}, expected = [200]) {
45
+ async response(url, options = {}, expected = [200], anonymous = false) {
22
46
  requireValue(new URL(url).origin === this.origin, 'Refusing to send a job token outside Gitea.');
23
47
  let response;
24
48
  try {
25
49
  response = await this.fetch(url, { ...options, redirect: 'error',
26
50
  signal: AbortSignal.timeout(15 * 60 * 1000),
27
- headers: { ...options.headers, Authorization: `token ${this.token}` } });
51
+ headers: anonymous ? { ...options.headers } : { ...options.headers, Authorization: `token ${this.token}` } });
28
52
  } catch { throw new Error('Gitea request failed; retain this run and retry it.'); }
29
- requireValue(expected.includes(response.status), `Unexpected Gitea HTTP status ${response.status}; retain this run and retry it.`);
53
+ if (!expected.includes(response.status)) {
54
+ await response.body?.cancel();
55
+ throw new Error(`Unexpected Gitea HTTP status ${response.status}; retain this run and retry it.`);
56
+ }
30
57
  return response;
31
58
  }
32
59
 
33
- async json(path, options = {}, expected = [200]) {
34
- const response = await this.response(`${this.base}${path}`, options, expected);
35
- if (response.status === 404) return null;
60
+ async json(path, options = {}, expected = [200], anonymous = false) {
61
+ const response = await this.response(`${this.base}${path}`, options, expected, anonymous);
62
+ if (response.status === 404 || response.status === 204) {
63
+ await response.body?.cancel();
64
+ return null;
65
+ }
36
66
  const chunks = []; let size = 0;
37
67
  for await (const chunk of response.body) {
38
68
  size += chunk.length;
@@ -43,29 +73,49 @@ export class GiteaSealedRelease {
43
73
  catch { throw new Error('Gitea returned invalid metadata.'); }
44
74
  }
45
75
 
46
- async findRetention({ name, runId, tag }) {
47
- requireValue(/^tspack-(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(name) && identifier(runId) && /^v\d+\.\d+\.\d+$/.test(tag), 'Invalid release retention identity.');
48
- const result = await this.json(`/actions/artifacts?name=${name}`);
49
- requireValue(Array.isArray(result?.artifacts) && result.artifacts.every((item) => item.name === name) &&
50
- result.total_count === result.artifacts.length && result.artifacts.length <= 1,
51
- 'Release retention is incomplete or ambiguous; inspect the original run.');
52
- const artifact = result.artifacts[0];
53
- if (artifact) {
54
- requireValue(identifier(artifact.id) && identifier(artifact.workflow_run?.id) &&
55
- artifact.workflow_run.head_sha === name.slice(7) && artifact.expired === false && artifact.size_in_bytes > 0,
56
- 'Retained release expired or is incomplete; recover its original bytes.');
57
- requireValue(artifact.workflow_run.id === runId, `Retained release belongs to run ${artifact.workflow_run.id}; rerun that original run.`);
58
- return artifact.id;
59
- }
60
- requireValue(await this.json(`/releases/tags/${tag}`, {}, [200, 404]) === null,
61
- 'A release exists without retained artifacts in this run; recover the original bytes before retrying.');
62
- return null;
76
+ async assertTag(tag, commit) {
77
+ const remoteTag = await this.json(`/tags/${tag}`);
78
+ requireValue(remoteTag?.name === tag && remoteTag.commit?.sha === commit, 'Remote tag does not identify the sealed source.');
63
79
  }
64
80
 
65
81
  assertRelease(release, tag, commit) {
66
82
  requireValue(identifier(release?.id) && release.tag_name === tag && release.target_commitish === commit &&
67
83
  typeof release.draft === 'boolean' && release.prerelease === false,
68
84
  'Existing release does not match this sealed source identity.');
85
+ return { id: release.id, draft: release.draft, manifestSha256: bodyDigest(release.body) };
86
+ }
87
+
88
+ /** The release for the tag as writers and anonymous readers see it; a draft must be invisible anonymously. */
89
+ async inspect(tag, commit) {
90
+ const authenticated = await this.json(`/releases/tags/${tag}`, {}, [200, 404]);
91
+ const anonymous = await this.json(`/releases/tags/${tag}`, {}, [200, 404], true);
92
+ if (authenticated === null && anonymous === null) return null;
93
+ requireValue(authenticated !== null, 'Gitea release visibility is inconclusive; public and authenticated lookups differ.');
94
+ const release = this.assertRelease(authenticated, tag, commit);
95
+ if (release.draft) {
96
+ requireValue(anonymous === null, 'Gitea release visibility is inconclusive; a draft is publicly visible.');
97
+ } else {
98
+ requireValue(anonymous !== null && this.assertRelease(anonymous, tag, commit).id === release.id && anonymous.draft === false,
99
+ 'Gitea release is not anonymously available with the same identity.');
100
+ }
101
+ return release;
102
+ }
103
+
104
+ /** Re-reads the release right before a draft mutation: it must still be this draft, with the token and anonymously. */
105
+ async requireDraft(tag, commit, releaseId) {
106
+ const release = await this.inspect(tag, commit);
107
+ requireValue(release?.id === releaseId && release.draft,
108
+ 'The release is no longer an unpublished draft; nothing more was changed. Rerun the job to verify it.');
109
+ }
110
+
111
+ async assets(releaseId, anonymous = false) {
112
+ const assets = await this.json(`/releases/${releaseId}/assets`, {}, [200], anonymous);
113
+ requireValue(Array.isArray(assets) && assets.length <= 130 && new Set(assets.map((asset) => asset?.name)).size === assets.length &&
114
+ assets.every((asset) => identifier(asset?.id) && typeof asset.name === 'string' && namePattern.test(asset.name) &&
115
+ Number.isSafeInteger(asset.size) && asset.size >= 0 && typeof asset.uuid === 'string' && asset.uuid.length > 0 &&
116
+ typeof asset.browser_download_url === 'string'),
117
+ 'Unexpected release attachments.');
118
+ return assets.map(({ id, name, size, uuid, browser_download_url: url }) => ({ id, name, size, uuid, url }));
69
119
  }
70
120
 
71
121
  async download(urlArg) {
@@ -86,65 +136,185 @@ export class GiteaSealedRelease {
86
136
  throw new Error('Too many attachment redirects.');
87
137
  }
88
138
 
89
- async verifyAssets(releaseId, files, complete) {
90
- const assets = await this.json(`/releases/${releaseId}/assets`);
91
- requireValue(Array.isArray(assets) && assets.length <= files.length, 'Unexpected release attachments.');
92
- const found = new Set();
93
- for (const asset of assets) {
94
- const file = files.find((item) => item.name === asset.name);
95
- requireValue(file && identifier(asset.id) && !found.has(asset.name) && asset.size === file.size &&
96
- typeof asset.browser_download_url === 'string', 'Release attachment identity conflict.');
97
- const response = await this.download(asset.browser_download_url);
98
- const hash = createHash('sha256'); let size = 0;
99
- for await (const chunk of response.body) {
100
- size += chunk.length;
101
- requireValue(size <= file.size, 'Release attachment exceeds its sealed size.');
102
- hash.update(chunk);
103
- }
104
- requireValue(size === file.size && hash.digest('hex') === file.sha256, 'Release attachment digest conflict.');
105
- found.add(file.name);
139
+ /**
140
+ * Streams one attachment and hashes it, passing each chunk to `onChunk`. Reading stops after the
141
+ * listed size plus one byte; `complete` is false when the served bytes do not have the listed size.
142
+ */
143
+ async read(asset, onChunk) {
144
+ const response = await this.download(asset.url);
145
+ const hash = createHash('sha256'); let size = 0;
146
+ // Leaving the loop early cancels the response body.
147
+ for await (const chunk of response.body) {
148
+ size += chunk.length;
149
+ if (size > asset.size) break;
150
+ hash.update(chunk);
151
+ await onChunk?.(chunk);
152
+ }
153
+ return { complete: size === asset.size, size, sha256: size === asset.size ? hash.digest('hex') : null };
154
+ }
155
+
156
+ async readBytes(asset, limit) {
157
+ requireValue(asset.size <= limit, `Release attachment ${asset.name} exceeds its metadata limit.`);
158
+ const chunks = [];
159
+ const read = await this.read(asset, (chunk) => { chunks.push(chunk); });
160
+ return { ...read, bytes: read.complete ? Buffer.concat(chunks) : null };
161
+ }
162
+
163
+ /**
164
+ * Finds the release this tag already retained. Returns `absent` when no release exists, `incomplete`
165
+ * for a draft that does not hold a complete verifiable set (it is rebuilt and corrected), and
166
+ * `candidate` with the attachment set the remote manifest describes; the caller downloads and hashes
167
+ * every artifact before relying on it. A published release that is not a complete verifiable set stops.
168
+ * `readMetadata(manifestBytes, checksumsBytes, manifestSha256)` validates TsPack metadata and returns its manifest.
169
+ */
170
+ async findRetained({ tag, commit, readMetadata }) {
171
+ requireValue(/^v\d+\.\d+\.\d+$/.test(tag) && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(commit) && typeof readMetadata === 'function',
172
+ 'Invalid release retention identity.');
173
+ await this.assertTag(tag, commit);
174
+ const release = await this.inspect(tag, commit);
175
+ if (!release) return { state: 'absent' };
176
+ const unusable = (reason) => {
177
+ requireValue(release.draft, `The published release is not a complete sealed set (${reason}); recover its original bytes.`);
178
+ return { state: 'incomplete', release, reason };
179
+ };
180
+ if (!release.manifestSha256) return unusable('its description names no manifest digest');
181
+ const assets = await this.assets(release.id);
182
+ const manifestAsset = assets.find((asset) => asset.name === manifestName);
183
+ const checksumsAsset = assets.find((asset) => asset.name === checksumsName);
184
+ if (!manifestAsset || !checksumsAsset) return unusable('its manifest or checksums are missing');
185
+ const manifest = await this.readBytes(manifestAsset, manifestLimit);
186
+ if (manifest.sha256 !== release.manifestSha256) return unusable('its manifest does not match its digest');
187
+ const checksums = await this.readBytes(checksumsAsset, checksumsLimit);
188
+ if (!checksums.complete) return unusable('its checksums are incomplete');
189
+ let metadata;
190
+ try { metadata = readMetadata(manifest.bytes, checksums.bytes, release.manifestSha256); }
191
+ catch { return unusable('its metadata does not verify'); }
192
+ const artifacts = metadata.artifacts.map((artifact) => ({ artifact, asset: assets.find((asset) => asset.name === artifact.name) }));
193
+ if (assets.length !== artifacts.length + 2 || artifacts.some(({ artifact, asset }) => !asset || asset.size !== artifact.size)) {
194
+ return unusable('its attachments are not exactly the sealed set');
106
195
  }
107
- requireValue(!complete || found.size === files.length, 'Release attachments are incomplete.');
108
- return found;
196
+ return { state: 'candidate', release, manifest: metadata, manifestBytes: manifest.bytes, checksumsBytes: checksums.bytes,
197
+ attachments: [
198
+ ...artifacts.map(({ artifact, asset }) => ({ ...asset, sha256: artifact.sha256 })),
199
+ { ...manifestAsset, sha256: release.manifestSha256 },
200
+ { ...checksumsAsset, sha256: checksums.sha256 },
201
+ ] };
202
+ }
203
+
204
+ async pageStatus(tag) {
205
+ const [owner, repository] = this.repository.split('/');
206
+ let response;
207
+ try {
208
+ response = await this.fetch(`${this.origin}${giteaReleasePagePath(owner, repository, tag)}`,
209
+ { redirect: 'manual', signal: AbortSignal.timeout(60 * 1000), headers: { Accept: 'text/html' } });
210
+ } catch { throw new Error('Gitea release page check failed; no release was created.'); }
211
+ await response.body?.cancel();
212
+ return response.status;
109
213
  }
110
214
 
111
- async publish({ tag, commit, manifestSha256, files }) {
215
+ async createDraft(tag, commit, manifestSha256) {
216
+ const waited = await awaitGiteaTagProcessed({ ...this.tagProcessing, pageStatus: () => this.pageStatus(tag),
217
+ onWaiting: (elapsedMs) => this.log(`Waiting for Gitea to process the pushed tag ${tag} (${Math.round(elapsedMs / 1000)} s).`) });
218
+ requireValue(waited.outcome !== 'unexpected', `Gitea release page check is inconclusive (HTTP ${waited.status}); no release was created.`);
219
+ requireValue(waited.outcome !== 'timeout', `Gitea has not processed the pushed tag ${tag} within ${Math.round(waited.elapsedMs / 1000)} s; ` +
220
+ 'the draft release was not created, because Gitea publishes a draft it finds for the tag once it processes the push. Rerun the job once Gitea shows the tag.');
221
+ const created = await this.json('/releases', { method: 'POST', headers: { 'Content-Type': 'application/json' },
222
+ body: JSON.stringify({ tag_name: tag, target_commitish: commit, name: tag, body: releaseBody(manifestSha256), draft: true, prerelease: false }) }, [201]);
223
+ const release = await this.inspect(tag, commit);
224
+ requireValue(release?.id === this.assertRelease(created, tag, commit).id && release.draft,
225
+ 'Gitea did not keep the new release as a draft; nothing was uploaded.');
226
+ return release;
227
+ }
228
+
229
+ /**
230
+ * Retains the verified sealed files in the tag's draft release and returns the attachment
231
+ * identities it read back and hashed. Attachments that already match are kept; a draft
232
+ * attachment that conflicts with the sealed set is replaced, never one of a published release.
233
+ */
234
+ async retain({ tag, commit, manifestSha256, files }) {
112
235
  requireValue(/^v\d+\.\d+\.\d+$/.test(tag) && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(commit) &&
113
- /^[a-f0-9]{64}$/.test(manifestSha256) && Array.isArray(files) && files.length >= 3 && files.length <= 130 &&
236
+ digestPattern.test(manifestSha256) && Array.isArray(files) && files.length >= 3 && files.length <= 130 &&
114
237
  new Set(files.map((file) => file.name)).size === files.length &&
115
- files.every((file) => /^[a-zA-Z0-9_.-]+$/.test(file.name) && Number.isSafeInteger(file.size) && file.size > 0 &&
116
- /^[a-f0-9]{64}$/.test(file.sha256) && typeof file.blob === 'function') &&
117
- files.some((file) => file.name === 'tspack-manifest.json' && file.sha256 === manifestSha256) &&
118
- files.some((file) => file.name === 'SHA256SUMS.txt'), 'Expected a verified sealed artifact set.');
119
- const remoteTag = await this.json(`/tags/${tag}`);
120
- requireValue(remoteTag?.name === tag && remoteTag.commit?.sha === commit, 'Remote tag does not identify the sealed source.');
121
- let release = await this.json(`/releases/tags/${tag}`, {}, [200, 404]);
122
- if (!release) {
123
- release = await this.json('/releases', { method: 'POST', headers: { 'Content-Type': 'application/json' },
124
- body: JSON.stringify({ tag_name: tag, target_commitish: commit, name: tag,
125
- body: `Sealed TsPack release. Manifest SHA-256: ${manifestSha256}. See changelog.md at this tag.`,
126
- draft: true, prerelease: false }) }, [201]);
238
+ files.every((file) => namePattern.test(file.name) && Number.isSafeInteger(file.size) && file.size > 0 &&
239
+ digestPattern.test(file.sha256) && typeof file.blob === 'function') &&
240
+ files.some((file) => file.name === manifestName && file.sha256 === manifestSha256) &&
241
+ files.some((file) => file.name === checksumsName), 'Expected a verified sealed artifact set.');
242
+ await this.assertTag(tag, commit);
243
+ let release = await this.inspect(tag, commit);
244
+ if (!release) release = await this.createDraft(tag, commit, manifestSha256);
245
+ requireValue(release.draft, 'The release for this tag is already published and is never changed; rerun the job to verify it.');
246
+ const retained = new Map();
247
+ for (const asset of await this.assets(release.id)) {
248
+ const file = files.find((item) => item.name === asset.name);
249
+ const read = await this.read(asset);
250
+ if (file && read.sha256 === file.sha256 && asset.size === file.size) {
251
+ retained.set(file.name, { ...asset, sha256: file.sha256 });
252
+ continue;
253
+ }
254
+ await this.requireDraft(tag, commit, release.id);
255
+ this.log(`Replacing attachment ${asset.name} of the unpublished draft ${tag}: it has sha256 ${read.sha256 ?? 'of incomplete bytes'} ` +
256
+ `(${read.size} of ${asset.size} bytes), the sealed set ${file ? `has sha256 ${file.sha256}` : 'has no such file'}.`);
257
+ await this.json(`/releases/${release.id}/assets/${asset.id}`, { method: 'DELETE' }, [204]);
258
+ }
259
+ if (release.manifestSha256 !== manifestSha256) {
260
+ await this.requireDraft(tag, commit, release.id);
261
+ this.log(`Describing the unpublished draft ${tag} with manifest sha256 ${manifestSha256} instead of ${release.manifestSha256 ?? 'none'}.`);
262
+ const edited = await this.json(`/releases/${release.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' },
263
+ body: JSON.stringify({ body: releaseBody(manifestSha256) }) });
264
+ const after = this.assertRelease(edited, tag, commit);
265
+ requireValue(after.id === release.id && after.draft && after.manifestSha256 === manifestSha256, 'Gitea did not confirm the draft description.');
127
266
  }
128
- this.assertRelease(release, tag, commit);
129
- const found = await this.verifyAssets(release.id, files, !release.draft);
130
- if (!release.draft) return { id: release.id, published: true, reused: true };
131
267
  for (const file of files) {
132
- if (found.has(file.name)) continue;
268
+ if (retained.has(file.name)) continue;
269
+ // Every upload reads the release first: a draft that turned public stops before the next byte.
270
+ await this.requireDraft(tag, commit, release.id);
133
271
  const form = new FormData();
134
272
  const blob = await file.blob();
135
273
  requireValue(blob.size === file.size, 'Local sealed attachment changed before upload.');
136
274
  form.set('attachment', blob, file.name);
137
- const asset = await this.json(`/releases/${release.id}/assets?name=${file.name}`, { method: 'POST', body: form }, [201]);
138
- requireValue(identifier(asset?.id) && asset.name === file.name && asset.size === file.size, 'Invalid attachment upload acknowledgement.');
275
+ const ack = await this.json(`/releases/${release.id}/assets?name=${file.name}`, { method: 'POST', body: form }, [201]);
276
+ requireValue(identifier(ack?.id) && ack.name === file.name && ack.size === file.size, 'Invalid attachment upload acknowledgement.');
277
+ const asset = (await this.assets(release.id)).find((item) => item.id === ack.id);
278
+ requireValue(asset?.name === file.name && asset.size === file.size, 'Uploaded attachment is not listed with its sealed identity.');
279
+ const read = await this.read(asset);
280
+ requireValue(read.sha256 === file.sha256, `Uploaded attachment ${file.name} reads back with a different digest.`);
281
+ retained.set(file.name, { ...asset, sha256: file.sha256 });
282
+ }
283
+ await this.requireDraft(tag, commit, release.id);
284
+ const attachments = files.map((file) => retained.get(file.name));
285
+ this.assertAttachments(await this.assets(release.id), attachments);
286
+ return { releaseId: release.id, attachments: attachments.map(({ id, name, size, uuid, sha256 }) => ({ id, name, size, uuid, sha256 })) };
287
+ }
288
+
289
+ /** Gitea stores attachment bytes under their UUID and its API can only rename one, so id, name and UUID identify hashed bytes. */
290
+ assertAttachments(assets, attachments) {
291
+ requireValue(assets.length === attachments.length && attachments.every((attachment) => assets.some((asset) =>
292
+ asset.id === attachment.id && asset.name === attachment.name && asset.size === attachment.size && asset.uuid === attachment.uuid)),
293
+ 'Release attachments differ from the retained, hashed set.');
294
+ }
295
+
296
+ /** Publishes the draft holding exactly the retained attachments, or confirms a release already published with them. */
297
+ async publish({ tag, commit, manifestSha256, releaseId, attachments }) {
298
+ requireValue(/^v\d+\.\d+\.\d+$/.test(tag) && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(commit) &&
299
+ digestPattern.test(manifestSha256) && identifier(releaseId) && Array.isArray(attachments) && attachments.length >= 3 &&
300
+ attachments.every((item) => identifier(item?.id) && namePattern.test(item.name) && typeof item.uuid === 'string' &&
301
+ Number.isSafeInteger(item.size) && digestPattern.test(item.sha256)) &&
302
+ attachments.some((item) => item.name === manifestName && item.sha256 === manifestSha256), 'Expected a retained sealed release.');
303
+ await this.assertTag(tag, commit);
304
+ const release = await this.inspect(tag, commit);
305
+ requireValue(release?.id === releaseId && release.manifestSha256 === manifestSha256, 'The release is not the retained sealed release.');
306
+ this.assertAttachments(await this.assets(release.id), attachments);
307
+ if (!release.draft) {
308
+ this.assertAttachments(await this.assets(release.id, true), attachments);
309
+ return { id: release.id, published: true, reused: true };
139
310
  }
140
- await this.verifyAssets(release.id, files, true);
141
- const finalTag = await this.json(`/tags/${tag}`);
142
- requireValue(finalTag?.commit?.sha === commit, 'Remote tag changed during publication.');
143
- const published = await this.json(`/releases/${release.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' },
144
- body: JSON.stringify({ draft: false }) });
145
- this.assertRelease(published, tag, commit);
146
- requireValue(published.draft === false, 'Gitea did not confirm publication.');
147
- await this.verifyAssets(published.id, files, true);
148
- return { id: published.id, published: true, reused: false };
311
+ await this.assertTag(tag, commit);
312
+ const published = this.assertRelease(await this.json(`/releases/${release.id}`, { method: 'PATCH',
313
+ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ draft: false }) }), tag, commit);
314
+ requireValue(published.id === release.id && published.draft === false, 'Gitea did not confirm publication.');
315
+ const visible = await this.inspect(tag, commit);
316
+ requireValue(visible?.id === release.id && !visible.draft, 'Gitea did not confirm publication.');
317
+ this.assertAttachments(await this.assets(release.id, true), attachments);
318
+ return { id: release.id, published: true, reused: false };
149
319
  }
150
320
  }