@intentius/chant 0.124.100 → 0.124.101

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 (223) hide show
  1. package/dist/action-pins.d.ts +2 -0
  2. package/dist/action-pins.js +3 -0
  3. package/dist/ci-detect.d.ts +13 -0
  4. package/dist/ci-detect.js +12 -0
  5. package/dist/ci-system.d.ts +66 -0
  6. package/dist/ci-system.js +61 -0
  7. package/dist/cli/handlers/build.js +27 -0
  8. package/dist/cli/handlers/release-doctor.d.ts +12 -0
  9. package/dist/cli/handlers/release-doctor.js +118 -0
  10. package/dist/cli/handlers/release-init.d.ts +10 -0
  11. package/dist/cli/handlers/release-init.js +342 -0
  12. package/dist/cli/handlers/release.d.ts +42 -1
  13. package/dist/cli/handlers/release.js +656 -31
  14. package/dist/cli/handlers/run-generate.js +11 -0
  15. package/dist/cli/main.d.ts +2 -0
  16. package/dist/cli/main.js +44 -101
  17. package/dist/cli/parse-args.js +48 -0
  18. package/dist/cli/registry.d.ts +16 -0
  19. package/dist/cli/release-commands/artifacts.d.ts +3 -0
  20. package/dist/cli/release-commands/artifacts.js +14 -0
  21. package/dist/cli/release-commands/candidates.d.ts +3 -0
  22. package/dist/cli/release-commands/candidates.js +16 -0
  23. package/dist/cli/release-commands/changed.d.ts +3 -0
  24. package/dist/cli/release-commands/changed.js +14 -0
  25. package/dist/cli/release-commands/compose.d.ts +3 -0
  26. package/dist/cli/release-commands/compose.js +16 -0
  27. package/dist/cli/release-commands/cut.d.ts +3 -0
  28. package/dist/cli/release-commands/cut.js +49 -0
  29. package/dist/cli/release-commands/doctor.d.ts +3 -0
  30. package/dist/cli/release-commands/doctor.js +14 -0
  31. package/dist/cli/release-commands/export.d.ts +3 -0
  32. package/dist/cli/release-commands/export.js +12 -0
  33. package/dist/cli/release-commands/images.d.ts +3 -0
  34. package/dist/cli/release-commands/images.js +13 -0
  35. package/dist/cli/release-commands/index.d.ts +8 -0
  36. package/dist/cli/release-commands/index.js +52 -0
  37. package/dist/cli/release-commands/init.d.ts +3 -0
  38. package/dist/cli/release-commands/init.js +16 -0
  39. package/dist/cli/release-commands/list.d.ts +3 -0
  40. package/dist/cli/release-commands/list.js +10 -0
  41. package/dist/cli/release-commands/next.d.ts +3 -0
  42. package/dist/cli/release-commands/next.js +13 -0
  43. package/dist/cli/release-commands/publish.d.ts +3 -0
  44. package/dist/cli/release-commands/publish.js +22 -0
  45. package/dist/cli/release-commands/stamp.d.ts +3 -0
  46. package/dist/cli/release-commands/stamp.js +15 -0
  47. package/dist/cli/release-commands/status.d.ts +3 -0
  48. package/dist/cli/release-commands/status.js +17 -0
  49. package/dist/cli/release-commands/tag.d.ts +3 -0
  50. package/dist/cli/release-commands/tag.js +12 -0
  51. package/dist/cli/release-commands/types.d.ts +20 -0
  52. package/dist/cli/release-commands/types.js +1 -0
  53. package/dist/cli/release-commands/verify.d.ts +3 -0
  54. package/dist/cli/release-commands/verify.js +15 -0
  55. package/dist/cli/release-commands/workflow.d.ts +3 -0
  56. package/dist/cli/release-commands/workflow.js +13 -0
  57. package/dist/components/cli-support.d.ts +1 -1
  58. package/dist/components/cli-support.js +1 -1
  59. package/dist/config-environments.d.ts +8 -1
  60. package/dist/config-environments.js +2 -0
  61. package/dist/config.d.ts +294 -9
  62. package/dist/config.js +100 -5
  63. package/dist/floor-table.data.js +15 -1
  64. package/dist/forge-remote.d.ts +13 -0
  65. package/dist/forge-remote.js +15 -0
  66. package/dist/lexicon.d.ts +41 -2
  67. package/dist/lifecycle/__fixtures__/publish-fakes.d.ts +62 -0
  68. package/dist/lifecycle/__fixtures__/publish-fakes.js +270 -3
  69. package/dist/lifecycle/publish-attachments.d.ts +2 -1
  70. package/dist/lifecycle/publish-attachments.js +19 -2
  71. package/dist/lifecycle/publish-cargo.d.ts +99 -0
  72. package/dist/lifecycle/publish-cargo.js +412 -0
  73. package/dist/lifecycle/publish-credentials.d.ts +1 -1
  74. package/dist/lifecycle/publish-credentials.js +8 -0
  75. package/dist/lifecycle/publish-declaration.d.ts +199 -4
  76. package/dist/lifecycle/publish-declaration.js +200 -9
  77. package/dist/lifecycle/publish-forge.d.ts +45 -2
  78. package/dist/lifecycle/publish-forge.js +434 -34
  79. package/dist/lifecycle/publish-git-ssh.d.ts +15 -0
  80. package/dist/lifecycle/publish-git-ssh.js +30 -4
  81. package/dist/lifecycle/publish-github.d.ts +40 -2
  82. package/dist/lifecycle/publish-github.js +100 -3
  83. package/dist/lifecycle/publish-homebrew.d.ts +7 -9
  84. package/dist/lifecycle/publish-homebrew.js +34 -197
  85. package/dist/lifecycle/publish-index.d.ts +141 -0
  86. package/dist/lifecycle/publish-index.js +719 -0
  87. package/dist/lifecycle/publish-marketplace.js +77 -0
  88. package/dist/lifecycle/publish-mcp-registry.d.ts +66 -0
  89. package/dist/lifecycle/publish-mcp-registry.js +306 -0
  90. package/dist/lifecycle/publish-npm.js +165 -2
  91. package/dist/lifecycle/publish-oci.d.ts +34 -1
  92. package/dist/lifecycle/publish-oci.js +246 -7
  93. package/dist/lifecycle/publish-pypi.d.ts +136 -0
  94. package/dist/lifecycle/publish-pypi.js +657 -0
  95. package/dist/lifecycle/publish-record.d.ts +6 -3
  96. package/dist/lifecycle/publish-record.js +6 -3
  97. package/dist/lifecycle/publish-signing.d.ts +147 -0
  98. package/dist/lifecycle/publish-signing.js +257 -0
  99. package/dist/lifecycle/publish-targets.d.ts +27 -1
  100. package/dist/lifecycle/publish-targets.js +80 -0
  101. package/dist/lifecycle/publish-tauri.js +43 -0
  102. package/dist/lifecycle/publish-train-names.d.ts +54 -0
  103. package/dist/lifecycle/publish-train-names.js +118 -0
  104. package/dist/lifecycle/publish-verify.d.ts +121 -0
  105. package/dist/lifecycle/publish-verify.js +130 -0
  106. package/dist/lifecycle/query.js +8 -0
  107. package/dist/lifecycle/release-artifacts.d.ts +212 -0
  108. package/dist/lifecycle/release-artifacts.js +571 -0
  109. package/dist/lifecycle/release-changelog.d.ts +13 -1
  110. package/dist/lifecycle/release-changelog.js +35 -2
  111. package/dist/lifecycle/release-cut.d.ts +58 -3
  112. package/dist/lifecycle/release-cut.js +132 -34
  113. package/dist/lifecycle/release-doctor.d.ts +113 -0
  114. package/dist/lifecycle/release-doctor.js +996 -0
  115. package/dist/lifecycle/release-green.d.ts +86 -0
  116. package/dist/lifecycle/release-green.js +286 -0
  117. package/dist/lifecycle/release-init.d.ts +255 -0
  118. package/dist/lifecycle/release-init.js +859 -0
  119. package/dist/lifecycle/release-intents.d.ts +73 -0
  120. package/dist/lifecycle/release-intents.js +128 -0
  121. package/dist/lifecycle/release-next.d.ts +111 -0
  122. package/dist/lifecycle/release-next.js +252 -0
  123. package/dist/lifecycle/release-prerelease.d.ts +19 -0
  124. package/dist/lifecycle/release-prerelease.js +30 -0
  125. package/dist/lifecycle/release-publish.d.ts +256 -10
  126. package/dist/lifecycle/release-publish.js +246 -34
  127. package/dist/lifecycle/release-status-change.d.ts +226 -0
  128. package/dist/lifecycle/release-status-change.js +478 -0
  129. package/dist/lifecycle/release-status.d.ts +11 -0
  130. package/dist/lifecycle/release-status.js +1 -1
  131. package/dist/lifecycle/release-store.d.ts +73 -2
  132. package/dist/lifecycle/release-store.js +32 -1
  133. package/dist/lifecycle/release-tag.d.ts +142 -0
  134. package/dist/lifecycle/release-tag.js +323 -0
  135. package/dist/lifecycle/release-verify.d.ts +73 -1
  136. package/dist/lifecycle/release-verify.js +117 -2
  137. package/dist/lifecycle/release-version-formats.d.ts +73 -0
  138. package/dist/lifecycle/release-version-formats.js +570 -0
  139. package/dist/lifecycle/release-version.d.ts +58 -10
  140. package/dist/lifecycle/release-version.js +164 -36
  141. package/dist/lifecycle/release-workstation.d.ts +3 -2
  142. package/dist/lifecycle/release-workstation.js +3 -2
  143. package/dist/op/generate-pipeline.js +1 -1
  144. package/dist/pr-forge-base.js +4 -2
  145. package/dist/pr-forge.d.ts +20 -2
  146. package/dist/pr-forge.js +46 -10
  147. package/dist/release-floors.d.ts +8 -1
  148. package/dist/release-floors.js +9 -2
  149. package/dist/tool-pins.d.ts +38 -0
  150. package/dist/tool-pins.js +54 -0
  151. package/dist/wave-runtime.mjs +337 -334
  152. package/dist/workspace/ci-forge.d.ts +17 -0
  153. package/dist/workspace/ci-forge.js +17 -0
  154. package/dist/workspace/ci-init.js +1 -1
  155. package/dist/workspace/composites.schema.json +1 -0
  156. package/dist/workspace/declaration.d.ts +8 -0
  157. package/dist/workspace/declaration.js +12 -0
  158. package/dist/workspace/declaration.schema.json +8 -0
  159. package/dist/workspace/environments.d.ts +2 -0
  160. package/dist/workspace/environments.js +1 -1
  161. package/dist/workspace/identity-gate-rule.d.ts +61 -5
  162. package/dist/workspace/identity-gate-rule.js +81 -12
  163. package/dist/workspace/member-pipeline.d.ts +2 -1
  164. package/dist/workspace/member-pipeline.js +5 -2
  165. package/dist/workspace/reason-codes.d.ts +2 -0
  166. package/dist/workspace/reason-codes.js +3 -1
  167. package/dist/workspace/release-changed.d.ts +75 -4
  168. package/dist/workspace/release-changed.js +205 -34
  169. package/dist/workspace/release-changed.schema.json +20 -2
  170. package/dist/workspace/release-steps/artifacts.d.ts +7 -0
  171. package/dist/workspace/release-steps/artifacts.js +45 -0
  172. package/dist/workspace/release-steps/builds.d.ts +12 -0
  173. package/dist/workspace/release-steps/builds.js +38 -0
  174. package/dist/workspace/release-steps/doctor.d.ts +8 -0
  175. package/dist/workspace/release-steps/doctor.js +14 -0
  176. package/dist/workspace/release-steps/goreleaser.d.ts +16 -0
  177. package/dist/workspace/release-steps/goreleaser.js +36 -0
  178. package/dist/workspace/release-steps/green.d.ts +3 -0
  179. package/dist/workspace/release-steps/green.js +6 -0
  180. package/dist/workspace/release-steps/images.d.ts +22 -0
  181. package/dist/workspace/release-steps/images.js +59 -0
  182. package/dist/workspace/release-steps/index.d.ts +9 -0
  183. package/dist/workspace/release-steps/index.js +46 -0
  184. package/dist/workspace/release-steps/pypi.d.ts +15 -0
  185. package/dist/workspace/release-steps/pypi.js +21 -0
  186. package/dist/workspace/release-steps/qemu.d.ts +21 -0
  187. package/dist/workspace/release-steps/qemu.js +35 -0
  188. package/dist/workspace/release-steps/signing.d.ts +18 -0
  189. package/dist/workspace/release-steps/signing.js +30 -0
  190. package/dist/workspace/release-steps/stamp.d.ts +3 -0
  191. package/dist/workspace/release-steps/stamp.js +4 -0
  192. package/dist/workspace/release-steps/targets.d.ts +31 -0
  193. package/dist/workspace/release-steps/targets.js +40 -0
  194. package/dist/workspace/release-steps/types.d.ts +104 -0
  195. package/dist/workspace/release-steps/types.js +2 -0
  196. package/dist/workspace/release-steps/verify.d.ts +3 -0
  197. package/dist/workspace/release-steps/verify.js +4 -0
  198. package/dist/workspace/release-toolchains.d.ts +59 -0
  199. package/dist/workspace/release-toolchains.js +133 -0
  200. package/dist/workspace/release-train-workflow.d.ts +29 -0
  201. package/dist/workspace/release-train-workflow.js +85 -0
  202. package/dist/workspace/release-train.d.ts +3 -1
  203. package/dist/workspace/release-train.js +20 -3
  204. package/dist/workspace/release-workflow.d.ts +160 -61
  205. package/dist/workspace/release-workflow.js +539 -193
  206. package/dist/workspace/releases.schema.json +70 -1
  207. package/dist/workspace/search-contract.d.ts +1 -1
  208. package/dist/workspace/security.js +9 -2
  209. package/dist/workspace/train-cut.d.ts +182 -0
  210. package/dist/workspace/train-cut.js +482 -0
  211. package/dist/workspace/train-prepare.d.ts +61 -0
  212. package/dist/workspace/train-prepare.js +267 -0
  213. package/dist/workspace/train-publish.d.ts +177 -0
  214. package/dist/workspace/train-publish.js +575 -0
  215. package/dist/workspace/train-range-labels.d.ts +33 -0
  216. package/dist/workspace/train-range-labels.js +109 -0
  217. package/dist/workspace/trust/seal.d.ts +13 -3
  218. package/dist/workspace/trust/seal.js +14 -4
  219. package/dist/workspace/work-cli.d.ts +3 -2
  220. package/dist/workspace/work-cli.js +3 -2
  221. package/dist/workspace/workspace-ledger.d.ts +14 -1
  222. package/dist/workspace/workspace-ledger.js +33 -7
  223. package/package.json +1 -1
@@ -0,0 +1,657 @@
1
+ /**
2
+ * The PyPI target (#5167): built wheels and sdists uploaded to PyPI, TestPyPI
3
+ * or another index that takes PyPI's upload API.
4
+ *
5
+ * The files are the ones the build wrote, named one by one, by their
6
+ * directory, or as `artifact:<name>` for the files the release records for a
7
+ * `release.artifacts` entry. Each file that the release records must match
8
+ * its digest. The project's name and version are read from the file's own
9
+ * metadata: `<name>.dist-info/METADATA` in a wheel, `PKG-INFO` in an sdist.
10
+ *
11
+ * An index has no draft: a file is visible as soon as it is uploaded, and a
12
+ * file name can never be uploaded again. So the stage uploads nothing. It
13
+ * checks what it can without changing anything: the files and their
14
+ * digests, the credential, and which files the index already serves, read
15
+ * from its simple API (PEP 691 JSON, or PEP 503 HTML). A file the index
16
+ * serves with the same SHA-256 is `present`; one it serves with another is
17
+ * refused (`publish-pypi-file-exists`). The reveal uploads the rest, after
18
+ * reading the simple API again, so a reveal run again after an upload whose
19
+ * record was lost sends nothing twice. Nothing is out between the stage and
20
+ * the reveal, so a check of what staged can't see this target.
21
+ *
22
+ * Credentials:
23
+ *
24
+ * - `auth: "token"`: an API token from `tokenEnv` (default `PYPI_TOKEN`, or
25
+ * `TEST_PYPI_TOKEN` for TestPyPI), sent as the password of user
26
+ * `__token__`, or of the user in `usernameEnv`.
27
+ * - `auth: "trusted-publishing"`, PyPI and TestPyPI only: the run's OIDC ID
28
+ * token, from GitHub Actions or from `PYPI_ID_TOKEN` (a GitLab job's
29
+ * `id_tokens`), with the audience the index names at `/_/oidc/audience`,
30
+ * is exchanged at `/_/oidc/mint-token` for an upload token that lasts
31
+ * minutes. The stage makes the exchange to check that the index takes this
32
+ * workflow as a trusted publisher of the project, and drops the token; the
33
+ * reveal exchanges again for the upload.
34
+ *
35
+ * Unset, `auth` is a token when the token's variable is set, else trusted
36
+ * publishing when the run has an OIDC ID token.
37
+ *
38
+ * A wheel carries its SBOM in `.dist-info/sboms/` (PEP 770), since an index
39
+ * keeps no file beside a distribution. Under the `supply-chain` group a wheel
40
+ * without one is refused (`publish-sbom-missing`) unless `sbom` is `false`.
41
+ * The PEP 740 attestations beside each file (`<file>.<name>.attestation`, as
42
+ * `pypi-attestations sign` writes them) are uploaded with it. When the
43
+ * publish signs with Sigstore (`release.signing` or `supply-chain`, #5164)
44
+ * and uploads by trusted publishing, the stage signs a publish attestation
45
+ * (`https://docs.pypi.org/attestations/publish/v1`) for each file that has
46
+ * none beside it, keeps it in the publish record's state, and the reveal
47
+ * uploads it. PyPI takes attestations only from a trusted publisher, so
48
+ * under a token nothing is signed and the stage says so.
49
+ */
50
+ import { randomBytes } from "node:crypto";
51
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
52
+ import { basename, dirname, join, relative } from "node:path";
53
+ import { gunzipSync, inflateRawSync } from "node:zlib";
54
+ import { readCredential } from "./publish-credentials.js";
55
+ import { bytesDigest, checkReleaseDigest, expandArtifactAssets, hasIdToken, memberFile, publishTargetKey, runIdToken } from "./publish-targets.js";
56
+ import { releaseVersion } from "./publish-index.js";
57
+ import { pep440Version, pypiFileVersion, pypiRequirements, trainName, waitUntilServed } from "./publish-train-names.js";
58
+ import { PublishTargetError } from "./release-publish.js";
59
+ /** The first chant that publishes a `pypi` target (#5167). */
60
+ export const PUBLISH_PYPI_FLOOR = "0.124.101";
61
+ /** The variable an OIDC ID token for PyPI is read from outside GitHub Actions, as PyPI's docs name it for GitLab. */
62
+ export const PYPI_ID_TOKEN_ENV = "PYPI_ID_TOKEN";
63
+ /** Where each named index is. */
64
+ export const PYPI_INDEXES = {
65
+ pypi: { label: "PyPI", site: "https://pypi.org", upload: "https://upload.pypi.org/legacy/", simple: "https://pypi.org/simple/", tokenEnv: "PYPI_TOKEN" },
66
+ testpypi: { label: "TestPyPI", site: "https://test.pypi.org", upload: "https://test.pypi.org/legacy/", simple: "https://test.pypi.org/simple/", tokenEnv: "TEST_PYPI_TOKEN" },
67
+ };
68
+ /** The index a declaration uploads to: a named one, or another with its own URLs and no trusted publishing. */
69
+ export function pypiIndex(decl) {
70
+ if (decl.uploadUrl && decl.simpleUrl) {
71
+ return { label: new URL(decl.uploadUrl).host, site: null, upload: decl.uploadUrl, simple: decl.simpleUrl.endsWith("/") ? decl.simpleUrl : `${decl.simpleUrl}/`, tokenEnv: "PYPI_TOKEN" };
72
+ }
73
+ return PYPI_INDEXES[decl.index ?? "pypi"];
74
+ }
75
+ /** The variable the declaration's token is read from. */
76
+ export function pypiTokenEnv(decl) {
77
+ return decl.tokenEnv ?? pypiIndex(decl).tokenEnv;
78
+ }
79
+ /** How the target authenticates in `env`: the declared `auth`, else a token when its variable is set, else trusted publishing when the run has an OIDC ID token on PyPI or TestPyPI. */
80
+ export function pypiAuth(decl, env) {
81
+ if (decl.auth)
82
+ return decl.auth;
83
+ if (env[pypiTokenEnv(decl)])
84
+ return "token";
85
+ return pypiIndex(decl).site !== null && hasIdToken(env, PYPI_ID_TOKEN_ENV) ? "trusted-publishing" : "token";
86
+ }
87
+ /** A project name as the simple API keys it (PEP 503). */
88
+ export function normalizeProjectName(name) {
89
+ return name.toLowerCase().replace(/[-_.]+/g, "-");
90
+ }
91
+ // Reading a distribution.
92
+ /** The names of a zip archive's entries. */
93
+ export function zipEntryNames(zip) {
94
+ let end = -1;
95
+ for (let i = zip.length - 22; i >= Math.max(0, zip.length - 22 - 0xffff); i--) {
96
+ if (zip.readUInt32LE(i) === 0x06054b50) {
97
+ end = i;
98
+ break;
99
+ }
100
+ }
101
+ if (end < 0)
102
+ throw new Error("not a zip archive: no end of central directory");
103
+ const count = zip.readUInt16LE(end + 10);
104
+ let at = zip.readUInt32LE(end + 16);
105
+ if (count === 0xffff || at === 0xffffffff)
106
+ throw new Error("a zip64 archive, which chant does not read");
107
+ const names = [];
108
+ for (let i = 0; i < count; i++) {
109
+ if (zip.readUInt32LE(at) !== 0x02014b50)
110
+ throw new Error("a malformed zip central directory");
111
+ const nameLen = zip.readUInt16LE(at + 28);
112
+ names.push(zip.toString("utf-8", at + 46, at + 46 + nameLen));
113
+ at += 46 + nameLen + zip.readUInt16LE(at + 30) + zip.readUInt16LE(at + 32);
114
+ }
115
+ return names;
116
+ }
117
+ /** One file of a zip archive, or null. Reads stored and deflated entries. */
118
+ function zipEntry(zip, name) {
119
+ let end = -1;
120
+ for (let i = zip.length - 22; i >= Math.max(0, zip.length - 22 - 0xffff); i--) {
121
+ if (zip.readUInt32LE(i) === 0x06054b50) {
122
+ end = i;
123
+ break;
124
+ }
125
+ }
126
+ if (end < 0)
127
+ return null;
128
+ const count = zip.readUInt16LE(end + 10);
129
+ let at = zip.readUInt32LE(end + 16);
130
+ for (let i = 0; i < count; i++) {
131
+ const method = zip.readUInt16LE(at + 10);
132
+ const size = zip.readUInt32LE(at + 20);
133
+ const nameLen = zip.readUInt16LE(at + 28);
134
+ const local = zip.readUInt32LE(at + 42);
135
+ if (zip.toString("utf-8", at + 46, at + 46 + nameLen) === name) {
136
+ const data = local + 30 + zip.readUInt16LE(local + 26) + zip.readUInt16LE(local + 28);
137
+ const raw = zip.subarray(data, data + size);
138
+ if (method === 0)
139
+ return Buffer.from(raw);
140
+ if (method === 8)
141
+ return inflateRawSync(raw);
142
+ throw new Error(`${name} is compressed with method ${method}, which chant does not read`);
143
+ }
144
+ at += 46 + nameLen + zip.readUInt16LE(at + 30) + zip.readUInt16LE(at + 32);
145
+ }
146
+ return null;
147
+ }
148
+ /** Each entry of a tar archive, by name, with its bytes: ustar names with their prefix, and pax and GNU long names. */
149
+ export function tarEntries(tar) {
150
+ const out = new Map();
151
+ let at = 0;
152
+ let longName = null;
153
+ const str = (b) => b.toString("utf-8").replace(/\0.*$/s, "");
154
+ while (at + 512 <= tar.length) {
155
+ const header = tar.subarray(at, at + 512);
156
+ if (header.every((b) => b === 0))
157
+ break;
158
+ const size = parseInt(str(header.subarray(124, 136)).trim() || "0", 8);
159
+ const type = String.fromCharCode(header[156] ?? 0);
160
+ const prefix = str(header.subarray(345, 500));
161
+ const name = longName ?? (prefix ? `${prefix}/${str(header.subarray(0, 100))}` : str(header.subarray(0, 100)));
162
+ const body = tar.subarray(at + 512, at + 512 + size);
163
+ longName = null;
164
+ if (type === "x") {
165
+ const m = /\d+ path=([^\n]*)\n/.exec(body.toString("utf-8"));
166
+ if (m)
167
+ longName = m[1];
168
+ }
169
+ else if (type === "L") {
170
+ longName = str(body);
171
+ }
172
+ else if (type === "0" || type === "\0") {
173
+ out.set(name.replace(/^\.\//, ""), Buffer.from(body));
174
+ }
175
+ at += 512 + Math.ceil(size / 512) * 512;
176
+ }
177
+ return out;
178
+ }
179
+ /** A distribution's core metadata (RFC 822 headers, then the description as the body). */
180
+ export function parseCoreMetadata(text) {
181
+ const lines = text.replace(/\r\n/g, "\n").split("\n");
182
+ const fields = [];
183
+ let i = 0;
184
+ for (; i < lines.length; i++) {
185
+ const line = lines[i];
186
+ if (line === "")
187
+ break;
188
+ if (/^[ \t]/.test(line) && fields.length > 0) {
189
+ const last = fields[fields.length - 1];
190
+ last[1] = `${last[1]}\n${line.replace(/^ {8}\|?|^\t/, "")}`;
191
+ continue;
192
+ }
193
+ const colon = line.indexOf(":");
194
+ if (colon <= 0)
195
+ continue;
196
+ fields.push([line.slice(0, colon).trim(), line.slice(colon + 1).trim()]);
197
+ }
198
+ const body = lines.slice(i + 1).join("\n").trim();
199
+ if (body && !fields.some(([k]) => k.toLowerCase() === "description"))
200
+ fields.push(["Description", body]);
201
+ const get = (k) => fields.find(([f]) => f.toLowerCase() === k)?.[1] ?? null;
202
+ return { fields, name: get("name"), version: get("version"), metadataVersion: get("metadata-version") };
203
+ }
204
+ /** The upload API's form field for a metadata header, as twine names them. */
205
+ function formField(header) {
206
+ const h = header.toLowerCase();
207
+ const special = { classifier: "classifiers", "project-url": "project_urls", "provides-extra": "provides_extras", "license-file": "license_files", "home-page": "home_page" };
208
+ return special[h] ?? h.replace(/-/g, "_");
209
+ }
210
+ const DIST = /\.(whl|tar\.gz|zip)$/;
211
+ /** Read one distribution file. */
212
+ export function readDistribution(path, abs) {
213
+ const file = basename(abs);
214
+ const bytes = readFileSync(abs);
215
+ const bad = (why) => new PublishTargetError("publish-pypi-not-a-distribution", `${path} is not a wheel or sdist chant can read: ${why}`, "Name the .whl and .tar.gz files the build writes, such as python -m build does.");
216
+ let metadataText = null;
217
+ let sbom = null;
218
+ let filetype;
219
+ let pyversion;
220
+ try {
221
+ if (file.endsWith(".whl")) {
222
+ filetype = "bdist_wheel";
223
+ const parts = file.slice(0, -4).split("-");
224
+ if (parts.length !== 5 && parts.length !== 6)
225
+ throw new Error("its name is not <name>-<version>[-<build>]-<python>-<abi>-<platform>.whl");
226
+ pyversion = parts[parts.length - 3];
227
+ const names = zipEntryNames(bytes);
228
+ const meta = names.find((n) => /^[^/]+\.dist-info\/METADATA$/.test(n));
229
+ if (!meta)
230
+ throw new Error("it holds no .dist-info/METADATA");
231
+ metadataText = zipEntry(bytes, meta)?.toString("utf-8") ?? null;
232
+ sbom = names.find((n) => /^[^/]+\.dist-info\/sboms\/[^/]+$/.test(n)) ?? null;
233
+ }
234
+ else if (file.endsWith(".tar.gz")) {
235
+ filetype = "sdist";
236
+ pyversion = "source";
237
+ const entries = tarEntries(gunzipSync(bytes));
238
+ const meta = [...entries.keys()].find((n) => /^[^/]+\/PKG-INFO$/.test(n));
239
+ if (!meta)
240
+ throw new Error("it holds no <name>-<version>/PKG-INFO");
241
+ metadataText = entries.get(meta).toString("utf-8");
242
+ }
243
+ else if (file.endsWith(".zip")) {
244
+ filetype = "sdist";
245
+ pyversion = "source";
246
+ const meta = zipEntryNames(bytes).find((n) => /^[^/]+\/PKG-INFO$/.test(n));
247
+ if (!meta)
248
+ throw new Error("it holds no <name>-<version>/PKG-INFO");
249
+ metadataText = zipEntry(bytes, meta)?.toString("utf-8") ?? null;
250
+ }
251
+ else {
252
+ throw new Error("its name ends in none of .whl, .tar.gz and .zip");
253
+ }
254
+ }
255
+ catch (err) {
256
+ if (err instanceof PublishTargetError)
257
+ throw err;
258
+ throw bad(err instanceof Error ? err.message : String(err));
259
+ }
260
+ const meta = parseCoreMetadata(metadataText ?? "");
261
+ if (!meta.name || !meta.version || !meta.metadataVersion)
262
+ throw bad("its metadata needs Metadata-Version, Name and Version");
263
+ return { path, abs, file, bytes, digest: bytesDigest(new Uint8Array(bytes)), filetype, pyversion, name: meta.name, version: meta.version, metadata: meta.fields, sbom };
264
+ }
265
+ /** The predicate type of a PyPI publish attestation (PEP 740). */
266
+ export const PYPI_PUBLISH_PREDICATE = "https://docs.pypi.org/attestations/publish/v1";
267
+ /** The in-toto statement a PyPI publish attestation signs: the file's name and SHA-256. */
268
+ export function pypiPublishStatement(file, digest) {
269
+ return { _type: "https://in-toto.io/Statement/v1", subject: [{ name: file, digest: { sha256: digest.replace(/^sha256:/, "") } }], predicateType: PYPI_PUBLISH_PREDICATE, predicate: {} };
270
+ }
271
+ /**
272
+ * A PEP 740 attestation from a Sigstore bundle (v0.3) over a DSSE envelope,
273
+ * as `pypi_attestations.Attestation.from_bundle` makes it: the signing
274
+ * certificate and transparency log entries, and the envelope's statement and
275
+ * signature.
276
+ */
277
+ export function pep740FromBundle(bundle) {
278
+ const b = JSON.parse(Buffer.from(bundle).toString("utf-8"));
279
+ const certificate = b.verificationMaterial?.certificate?.rawBytes ?? b.verificationMaterial?.x509CertificateChain?.certificates?.[0]?.rawBytes;
280
+ const statement = b.dsseEnvelope?.payload;
281
+ const signature = b.dsseEnvelope?.signatures?.[0]?.sig;
282
+ if (!certificate || !statement || !signature)
283
+ throw new PublishTargetError("publish-signing-failed", "the Sigstore bundle for a PyPI attestation has no certificate, DSSE payload or signature");
284
+ return { version: 1, verification_material: { certificate, transparency_entries: b.verificationMaterial?.tlogEntries ?? [] }, envelope: { statement, signature } };
285
+ }
286
+ /** The multipart/form-data body of an upload. */
287
+ function multipart(fields, file) {
288
+ const boundary = `chant-${randomBytes(12).toString("hex")}`;
289
+ const parts = [];
290
+ for (const [k, v] of fields)
291
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${k}"\r\n\r\n${v}\r\n`, "utf-8"));
292
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="content"; filename="${file.name}"\r\nContent-Type: application/octet-stream\r\n\r\n`, "utf-8"), file.bytes, Buffer.from(`\r\n--${boundary}--\r\n`, "utf-8"));
293
+ return { body: new Uint8Array(Buffer.concat(parts)), type: `multipart/form-data; boundary=${boundary}` };
294
+ }
295
+ export function pypiTarget(decl, deps) {
296
+ const fetchImpl = deps.fetch ?? ((url, init) => fetch(url, init));
297
+ const index = pypiIndex(decl);
298
+ const tokenName = pypiTokenEnv(decl);
299
+ /** Every file the declaration names, read and checked, in order. */
300
+ const distributions = (ctx) => {
301
+ const paths = [];
302
+ for (const entry of expandArtifactAssets(ctx.release, decl.files)) {
303
+ const abs = memberFile(ctx.cwd, entry);
304
+ if (statSync(abs).isDirectory()) {
305
+ const found = readdirSync(abs).filter((f) => DIST.test(f) && statSync(join(abs, f)).isFile()).sort();
306
+ if (found.length === 0)
307
+ throw new PublishTargetError("publish-pypi-no-files", `${entry} holds no .whl, .tar.gz or .zip`, "Build the distributions before publishing, such as with python -m build.");
308
+ paths.push(...found.map((f) => join(entry, f)));
309
+ }
310
+ else {
311
+ paths.push(entry);
312
+ }
313
+ }
314
+ const seen = new Set();
315
+ const out = [];
316
+ for (const path of paths) {
317
+ const abs = memberFile(ctx.cwd, path);
318
+ if (seen.has(basename(abs)))
319
+ throw new PublishTargetError("publish-pypi-duplicate-file", `${basename(abs)} is named twice`, "An index takes each file name once; name each file once in files.");
320
+ seen.add(basename(abs));
321
+ const dist = readDistribution(path, abs);
322
+ checkReleaseDigest(ctx.release, "asset", ctx.cwd, path, [dist.digest]);
323
+ const attestations = [];
324
+ if (decl.attestations !== false) {
325
+ for (const f of readdirSync(dirname(abs)).filter((n) => n.startsWith(`${dist.file}.`) && n.endsWith(".attestation")).sort()) {
326
+ const attPath = join(dirname(path), f);
327
+ const text = readFileSync(join(dirname(abs), f), "utf-8");
328
+ try {
329
+ const parsed = JSON.parse(text);
330
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
331
+ throw new Error("not an object");
332
+ }
333
+ catch {
334
+ throw new PublishTargetError("publish-pypi-attestation-invalid", `${attPath} is not a PEP 740 attestation: it is not a JSON object`, "Write it with pypi-attestations sign, or set attestations: false.");
335
+ }
336
+ const digest = bytesDigest(new Uint8Array(Buffer.from(text, "utf-8")));
337
+ checkReleaseDigest(ctx.release, "asset", ctx.cwd, attPath, [digest]);
338
+ attestations.push({ path: attPath, text, digest });
339
+ }
340
+ }
341
+ out.push({ ...dist, attestations });
342
+ }
343
+ if (ctx.requireSbom && decl.sbom !== false) {
344
+ const wheels = out.filter((d) => d.filetype === "bdist_wheel");
345
+ const without = wheels.find((d) => d.sbom === null);
346
+ if (wheels.length === 0 || without) {
347
+ throw new PublishTargetError("publish-sbom-missing", without
348
+ ? `${without.file} carries no SBOM: an index keeps no file beside a distribution, so a wheel carries its SBOM in .dist-info/sboms/ (PEP 770)`
349
+ : `${target.name} publishes no wheel, and an sdist has no place for an SBOM, so nothing it publishes carries one`, "Build wheels that carry an SBOM in .dist-info/sboms/, or set sbom: false to publish without one.");
350
+ }
351
+ }
352
+ return out;
353
+ };
354
+ const destination = (d) => index.site ? `${index.site}/project/${normalizeProjectName(d.name)}/${d.version}/` : `${index.simple}${normalizeProjectName(d.name)}/`;
355
+ const items = (dists) => dists.flatMap((d) => [
356
+ { name: d.file, destination: destination(d), digest: d.digest, ...(d.sbom ? { sbom: d.sbom } : {}) },
357
+ ...d.attestations.map((a) => a.signed
358
+ ? { name: basename(a.path), destination: destination(d), digest: a.digest, attachment: "attestation", signs: [{ name: d.file, digest: d.digest }] }
359
+ : { name: basename(a.path), destination: destination(d), digest: a.digest, attachment: "provenance" }),
360
+ ]);
361
+ const SIGNED = "attestation:";
362
+ /** The attestations the stage signed (#5164), from its state, added to each distribution. */
363
+ const withSigned = (dists, state) => dists.map((d) => {
364
+ const text = state[`${SIGNED}${d.file}`];
365
+ return text ? { ...d, attestations: [...d.attestations, { path: join(dirname(d.path), `${d.file}.publish.attestation`), text, digest: bytesDigest(new Uint8Array(Buffer.from(text, "utf-8"))), signed: true }] } : d;
366
+ });
367
+ /** The token, or null under trusted publishing; refuses a run with neither. */
368
+ const credential = (ctx) => {
369
+ const auth = pypiAuth(decl, ctx.env);
370
+ if (auth === "trusted-publishing") {
371
+ if (!hasIdToken(ctx.env, PYPI_ID_TOKEN_ENV)) {
372
+ throw new PublishTargetError("publish-credentials-missing", `the ${index.label} target publishes with trusted publishing, and this run has no OIDC ID token: not a GitHub Actions job with id-token: write, and ${PYPI_ID_TOKEN_ENV} is not set`, `In GitHub Actions, give the job permissions: id-token: write. In GitLab CI, declare ${PYPI_ID_TOKEN_ENV} under the job's id_tokens with the audience ${index.label === "TestPyPI" ? "testpypi" : "pypi"}.`);
373
+ }
374
+ return { auth, token: null, username: "__token__" };
375
+ }
376
+ const token = readCredential(ctx.env, [tokenName], ctx.redactor);
377
+ if (!token) {
378
+ throw new PublishTargetError("publish-credentials-missing", `the ${index.label} target reads its token from ${tokenName}, and it is not set${index.site ? ", and this run has no OIDC ID token for trusted publishing" : ""}`, index.site ? `Set ${tokenName} to an API token for the project, or publish from a CI job with an OIDC ID token and a trusted publisher registered on ${index.label}.` : `Set ${tokenName} to a token the index takes.`);
379
+ }
380
+ const user = decl.usernameEnv ? readCredential(ctx.env, [decl.usernameEnv], ctx.redactor) : null;
381
+ if (decl.usernameEnv && !user)
382
+ throw new PublishTargetError("publish-credentials-missing", `the ${index.label} target reads its user from ${decl.usernameEnv}, and it is not set`, `Set ${decl.usernameEnv}.`);
383
+ return { auth, token, username: user?.value ?? "__token__" };
384
+ };
385
+ const fail = (ctx, code, what, status, text, fix) => {
386
+ throw new PublishTargetError(code, ctx.redactor.redact(`${what} on ${index.label} answered ${status}${text ? `: ${text.replace(/\s+/g, " ").slice(0, 300)}` : ""}`), fix);
387
+ };
388
+ /** The files the index serves for a project, by file name, with their SHA-256 in hex when it gives one; null when it has no such project. */
389
+ const served = async (ctx, name) => {
390
+ const url = `${index.simple}${normalizeProjectName(name)}/`;
391
+ const res = await fetchImpl(url, { method: "GET", headers: { "user-agent": "chant", accept: "application/vnd.pypi.simple.v1+json, text/html;q=0.1" } });
392
+ const text = await res.text().catch(() => "");
393
+ if (res.status === 404)
394
+ return null;
395
+ if (res.status !== 200)
396
+ fail(ctx, "publish-pypi-failed", `reading ${url}`, res.status, text);
397
+ const out = new Map();
398
+ try {
399
+ const json = JSON.parse(text);
400
+ for (const f of json.files ?? [])
401
+ if (typeof f.filename === "string")
402
+ out.set(f.filename, typeof f.hashes?.sha256 === "string" ? f.hashes.sha256 : null);
403
+ return out;
404
+ }
405
+ catch {
406
+ // PEP 503 HTML: <a href="...#sha256=<hex>">file</a>
407
+ for (const m of text.matchAll(/<a\s[^>]*href="([^"]*)"[^>]*>([^<]+)<\/a>/gi)) {
408
+ const hash = /#sha256=([0-9a-f]{64})/i.exec(m[1]);
409
+ out.set(m[2].trim(), hash ? hash[1].toLowerCase() : null);
410
+ }
411
+ return out;
412
+ }
413
+ };
414
+ /** Each distribution: `present` when the index serves it with the same bytes; refused when it serves the name with others. */
415
+ const presence = async (ctx, dists) => {
416
+ const byProject = new Map();
417
+ const out = new Map();
418
+ for (const d of dists) {
419
+ if (!byProject.has(d.name))
420
+ byProject.set(d.name, await served(ctx, d.name));
421
+ const files = byProject.get(d.name);
422
+ if (!files || !files.has(d.file)) {
423
+ out.set(d.file, false);
424
+ continue;
425
+ }
426
+ const sha = files.get(d.file);
427
+ if (sha && `sha256:${sha}` !== d.digest) {
428
+ throw new PublishTargetError("publish-pypi-file-exists", `${index.label} already serves ${d.file}, with sha256:${sha}, not ${d.digest}`, "An index never takes a file name twice: cut a release with a new version.");
429
+ }
430
+ out.set(d.file, true);
431
+ }
432
+ return out;
433
+ };
434
+ /** Trusted publishing: an upload token for this run, exchanged for its OIDC ID token. It lasts minutes. */
435
+ const mintToken = async (ctx) => {
436
+ const site = index.site;
437
+ const aud = await fetchImpl(`${site}/_/oidc/audience`, { method: "GET", headers: { "user-agent": "chant", accept: "application/json" } });
438
+ const audText = await aud.text().catch(() => "");
439
+ let audience;
440
+ try {
441
+ audience = aud.status === 200 ? JSON.parse(audText).audience : undefined;
442
+ }
443
+ catch {
444
+ audience = undefined;
445
+ }
446
+ if (typeof audience !== "string" || !audience)
447
+ fail(ctx, "publish-pypi-trusted-publishing", `reading the OIDC audience at ${site}/_/oidc/audience`, aud.status, audText, `${index.label} may not take trusted publishing here; publish with a token in ${tokenName}.`);
448
+ const jwt = await runIdToken(ctx, fetchImpl, audience, PYPI_ID_TOKEN_ENV, "publish-pypi-trusted-publishing");
449
+ const res = await fetchImpl(`${site}/_/oidc/mint-token`, { method: "POST", headers: { "user-agent": "chant", "content-type": "application/json" }, body: JSON.stringify({ token: jwt }) });
450
+ const text = await res.text().catch(() => "");
451
+ let body = {};
452
+ try {
453
+ body = JSON.parse(text);
454
+ }
455
+ catch {
456
+ // Reported by its status.
457
+ }
458
+ if (res.status < 200 || res.status > 299 || typeof body.token !== "string" || !body.token) {
459
+ const why = (body.errors ?? []).map((e) => `${typeof e.code === "string" ? `${e.code}: ` : ""}${typeof e.description === "string" ? e.description : ""}`).filter(Boolean).join("; ");
460
+ throw new PublishTargetError("publish-pypi-trusted-publishing", ctx.redactor.redact(`${index.label} gave no upload token for this run's OIDC ID token: it answered ${res.status}${why ? `: ${why}` : typeof body.message === "string" ? `: ${body.message}` : ""}`), `Register this workflow as a trusted publisher of the project at ${site}/manage/account/publishing/ (a pending publisher for a project that does not exist yet).`);
461
+ }
462
+ ctx.redactor.add(body.token);
463
+ return body.token;
464
+ };
465
+ const upload = async (ctx, d, auth) => {
466
+ const fields = [
467
+ [":action", "file_upload"],
468
+ ["protocol_version", "1"],
469
+ ["filetype", d.filetype],
470
+ ["pyversion", d.pyversion],
471
+ ["sha256_digest", d.digest.slice("sha256:".length)],
472
+ ...d.metadata.map(([k, v]) => [formField(k), v]),
473
+ ];
474
+ if (d.attestations.length > 0)
475
+ fields.push(["attestations", JSON.stringify(d.attestations.map((a) => JSON.parse(a.text)))]);
476
+ const form = multipart(fields, { name: d.file, bytes: d.bytes });
477
+ const basic = Buffer.from(`${auth.username}:${auth.password}`, "utf-8").toString("base64");
478
+ ctx.redactor.add(basic);
479
+ ctx.log(`uploading ${d.file} (${d.bytes.byteLength} bytes${d.attestations.length ? `, ${d.attestations.length} attestation${d.attestations.length === 1 ? "" : "s"}` : ""}) to ${index.label}`);
480
+ const res = await fetchImpl(index.upload, { method: "POST", headers: { "user-agent": "chant", "content-type": form.type, authorization: `Basic ${basic}` }, body: form.body });
481
+ const text = await res.text().catch(() => "");
482
+ if (res.status === 200 || res.status === 201)
483
+ return "sent";
484
+ if ((res.status === 400 || res.status === 409) && /already exists/i.test(text)) {
485
+ // Another upload of this name won the race or a record was lost: the index keeps the first bytes it took.
486
+ const files = await served(ctx, d.name);
487
+ const sha = files?.get(d.file);
488
+ if (sha === undefined || (sha !== null && `sha256:${sha}` !== d.digest)) {
489
+ throw new PublishTargetError("publish-pypi-file-exists", ctx.redactor.redact(`${index.label} refused ${d.file}: ${text.replace(/\s+/g, " ").slice(0, 300)}`), "An index never takes a file name twice, even after it was deleted: cut a release with a new version.");
490
+ }
491
+ return "present";
492
+ }
493
+ return fail(ctx, "publish-pypi-failed", `uploading ${d.file}`, res.status, text, res.status === 403 ? "Check that the token or the trusted publisher may upload to this project." : undefined);
494
+ };
495
+ const target = {
496
+ kind: "pypi",
497
+ name: `${index.label} ${decl.files.join(", ")}`,
498
+ destination: index.label,
499
+ credentialEnv: [tokenName, PYPI_ID_TOKEN_ENV, ...(decl.usernameEnv ? [decl.usernameEnv] : [])],
500
+ key: publishTargetKey(decl),
501
+ uploadsAtReveal: true,
502
+ /** #5165: each project the files hold, and the projects their `Requires-Dist` names outside an extra. */
503
+ async names(ctx) {
504
+ let dists;
505
+ try {
506
+ dists = distributions(ctx);
507
+ }
508
+ catch {
509
+ const name = pypiProjectName(ctx.cwd, decl.files);
510
+ return { provides: name ? [trainName("pypi", name)] : [], needs: [] };
511
+ }
512
+ const provides = [...new Set(dists.map((d) => trainName("pypi", d.name)))];
513
+ const needs = new Set(dists.flatMap((d) => pypiRequirements(d.metadata).map((n) => trainName("pypi", n))));
514
+ return { provides, needs: [...needs].filter((n) => !provides.includes(n)) };
515
+ },
516
+ /** #5165: whether the index serves a file of the release's version of the project. */
517
+ async published(ctx) {
518
+ const name = pypiProjectName(ctx.cwd, decl.files);
519
+ const version = releaseVersion(ctx.label);
520
+ if (!name || !version)
521
+ return null;
522
+ const files = await served(ctx, name);
523
+ if (!files)
524
+ return false;
525
+ const want = pep440Version(version);
526
+ return [...files.keys()].some((f) => {
527
+ const v = pypiFileVersion(f);
528
+ return v !== null && pep440Version(v.version) === want;
529
+ });
530
+ },
531
+ /** #5165: wait until the simple API lists each file the reveal uploaded. */
532
+ async visible(ctx, published) {
533
+ const files = published.items.filter((i) => i.attachment === undefined && !i.refused).map((i) => ({ file: i.name, project: pypiFileVersion(i.name)?.name })).filter((f) => f.project !== undefined);
534
+ if (files.length === 0)
535
+ return;
536
+ await waitUntilServed(ctx, deps, {
537
+ what: index.label,
538
+ code: "publish-pypi-not-served",
539
+ check: async () => {
540
+ const byProject = new Map();
541
+ const missing = [];
542
+ for (const f of files) {
543
+ if (!byProject.has(f.project))
544
+ byProject.set(f.project, await served(ctx, f.project));
545
+ if (!byProject.get(f.project)?.has(f.file))
546
+ missing.push(f.file);
547
+ }
548
+ return missing;
549
+ },
550
+ });
551
+ },
552
+ async plan(ctx) {
553
+ const dists = distributions(ctx);
554
+ credential(ctx);
555
+ return items(dists);
556
+ },
557
+ async stage(ctx) {
558
+ let dists = distributions(ctx);
559
+ const cred = credential(ctx);
560
+ if (cred.token)
561
+ ctx.log(`using the token from ${cred.token.from}; ${index.label} has no read-only check of a token, so whether it may upload shows at the reveal`);
562
+ else {
563
+ await mintToken(ctx);
564
+ ctx.log(`${index.label} takes this run as a trusted publisher; the reveal asks for a new token, since one lasts minutes`);
565
+ }
566
+ const present = await presence(ctx, dists);
567
+ const state = {};
568
+ if (ctx.signing && decl.attestations !== false) {
569
+ const unsigned = dists.filter((d) => !present.get(d.file) && d.attestations.length === 0);
570
+ if (cred.auth !== "trusted-publishing") {
571
+ if (unsigned.length > 0)
572
+ ctx.log(`${index.label} takes attestations only from a trusted publisher, so ${unsigned.map((d) => d.file).join(", ")} ${unsigned.length === 1 ? "goes" : "go"} without a signed attestation under a token`);
573
+ }
574
+ else {
575
+ for (const d of unsigned) {
576
+ ctx.log(`signing a PyPI publish attestation for ${d.file} with ${ctx.signing.signer.name}`);
577
+ state[`${SIGNED}${d.file}`] = JSON.stringify(pep740FromBundle(await ctx.signing.signer.signStatement(pypiPublishStatement(d.file, d.digest))));
578
+ }
579
+ }
580
+ }
581
+ dists = withSigned(dists, state);
582
+ const all = items(dists);
583
+ const out = all.map((i) => {
584
+ const d = dists.find((x) => x.file === i.name || x.attestations.some((a) => basename(a.path) === i.name));
585
+ return present.get(d.file) ? { ...i, present: true } : i;
586
+ });
587
+ const waiting = dists.filter((d) => !present.get(d.file));
588
+ ctx.log(waiting.length === 0
589
+ ? `${index.label} already serves every file with the same bytes`
590
+ : `${waiting.map((d) => d.file).join(", ")} ${waiting.length === 1 ? "is" : "are"} uploaded at the reveal, since ${index.label} has no draft`);
591
+ const staged = { target: target.name, destination: target.destination, items: out, state: waiting.length === 0 ? { present: "true" } : state };
592
+ return staged;
593
+ },
594
+ async reveal(ctx, staged) {
595
+ if (staged.state.present === "true")
596
+ return { target: target.name, destination: target.destination, items: staged.items.map((i) => ({ ...i, present: true })) };
597
+ const dists = withSigned(distributions(ctx), staged.state);
598
+ const cred = credential(ctx);
599
+ // Read again: a reveal run after an upload whose record was lost finds the files there.
600
+ const present = await presence(ctx, dists);
601
+ const sent = new Set();
602
+ let password = cred.token?.value ?? null;
603
+ const done = [];
604
+ for (const d of dists) {
605
+ if (present.get(d.file))
606
+ continue;
607
+ password ?? (password = await mintToken(ctx));
608
+ try {
609
+ if ((await upload(ctx, d, { username: cred.username, password })) === "sent")
610
+ sent.add(d.file);
611
+ }
612
+ catch (err) {
613
+ if (err instanceof PublishTargetError && done.length > 0) {
614
+ throw new PublishTargetError(err.code, `${err.message}. Uploaded before it: ${done.join(", ")}; the same publish run again uploads only the rest`, err.fix);
615
+ }
616
+ throw err;
617
+ }
618
+ done.push(d.file);
619
+ }
620
+ return {
621
+ target: target.name,
622
+ destination: target.destination,
623
+ items: items(dists).map((i) => {
624
+ const d = dists.find((x) => x.file === i.name || x.attestations.some((a) => basename(a.path) === i.name));
625
+ return sent.has(d.file) ? i : { ...i, present: true };
626
+ }),
627
+ };
628
+ },
629
+ };
630
+ return target;
631
+ }
632
+ /** The project name the member builds, for the doctor: from a built distribution, else `[project] name` in `pyproject.toml`. */
633
+ export function pypiProjectName(cwd, files) {
634
+ for (const entry of files) {
635
+ if (entry.startsWith("artifact:"))
636
+ continue;
637
+ const abs = join(cwd, entry);
638
+ if (!existsSync(abs))
639
+ continue;
640
+ const candidates = statSync(abs).isDirectory() ? readdirSync(abs).filter((f) => DIST.test(f)).map((f) => join(abs, f)) : [abs];
641
+ for (const c of candidates) {
642
+ try {
643
+ return readDistribution(relative(cwd, c), c).name;
644
+ }
645
+ catch {
646
+ // Try the next.
647
+ }
648
+ }
649
+ }
650
+ const pyproject = join(cwd, "pyproject.toml");
651
+ if (!existsSync(pyproject))
652
+ return null;
653
+ const text = readFileSync(pyproject, "utf-8");
654
+ const section = /^\[project\][^\n]*\n([\s\S]*?)(?=^\[|$(?![\s\S]))/m.exec(text);
655
+ const name = section ? /^name\s*=\s*["']([^"']+)["']/m.exec(section[1]) : null;
656
+ return name ? name[1] : null;
657
+ }