@intentius/chant 0.124.100 → 0.124.102

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 (270) 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-evidence-claims.d.ts +12 -0
  6. package/dist/ci-evidence-claims.js +12 -0
  7. package/dist/ci-system.d.ts +66 -0
  8. package/dist/ci-system.js +61 -0
  9. package/dist/cli/handlers/build.js +27 -0
  10. package/dist/cli/handlers/release-doctor.d.ts +12 -0
  11. package/dist/cli/handlers/release-doctor.js +118 -0
  12. package/dist/cli/handlers/release-init.d.ts +10 -0
  13. package/dist/cli/handlers/release-init.js +374 -0
  14. package/dist/cli/handlers/release.d.ts +43 -2
  15. package/dist/cli/handlers/release.js +667 -39
  16. package/dist/cli/handlers/run-generate.js +11 -0
  17. package/dist/cli/main.d.ts +2 -0
  18. package/dist/cli/main.js +44 -101
  19. package/dist/cli/parse-args.js +48 -0
  20. package/dist/cli/registry.d.ts +16 -0
  21. package/dist/cli/release-commands/artifacts.d.ts +3 -0
  22. package/dist/cli/release-commands/artifacts.js +14 -0
  23. package/dist/cli/release-commands/candidates.d.ts +3 -0
  24. package/dist/cli/release-commands/candidates.js +16 -0
  25. package/dist/cli/release-commands/changed.d.ts +3 -0
  26. package/dist/cli/release-commands/changed.js +14 -0
  27. package/dist/cli/release-commands/compose.d.ts +3 -0
  28. package/dist/cli/release-commands/compose.js +16 -0
  29. package/dist/cli/release-commands/cut.d.ts +3 -0
  30. package/dist/cli/release-commands/cut.js +50 -0
  31. package/dist/cli/release-commands/doctor.d.ts +3 -0
  32. package/dist/cli/release-commands/doctor.js +14 -0
  33. package/dist/cli/release-commands/export.d.ts +3 -0
  34. package/dist/cli/release-commands/export.js +12 -0
  35. package/dist/cli/release-commands/images.d.ts +3 -0
  36. package/dist/cli/release-commands/images.js +13 -0
  37. package/dist/cli/release-commands/index.d.ts +8 -0
  38. package/dist/cli/release-commands/index.js +52 -0
  39. package/dist/cli/release-commands/init.d.ts +3 -0
  40. package/dist/cli/release-commands/init.js +19 -0
  41. package/dist/cli/release-commands/list.d.ts +3 -0
  42. package/dist/cli/release-commands/list.js +10 -0
  43. package/dist/cli/release-commands/next.d.ts +3 -0
  44. package/dist/cli/release-commands/next.js +13 -0
  45. package/dist/cli/release-commands/publish.d.ts +3 -0
  46. package/dist/cli/release-commands/publish.js +22 -0
  47. package/dist/cli/release-commands/stamp.d.ts +3 -0
  48. package/dist/cli/release-commands/stamp.js +15 -0
  49. package/dist/cli/release-commands/status.d.ts +3 -0
  50. package/dist/cli/release-commands/status.js +17 -0
  51. package/dist/cli/release-commands/tag.d.ts +3 -0
  52. package/dist/cli/release-commands/tag.js +12 -0
  53. package/dist/cli/release-commands/types.d.ts +20 -0
  54. package/dist/cli/release-commands/types.js +1 -0
  55. package/dist/cli/release-commands/verify.d.ts +3 -0
  56. package/dist/cli/release-commands/verify.js +15 -0
  57. package/dist/cli/release-commands/workflow.d.ts +3 -0
  58. package/dist/cli/release-commands/workflow.js +15 -0
  59. package/dist/cloud-lister/index.d.ts +4 -1
  60. package/dist/cloud-lister/index.js +2 -1
  61. package/dist/cloud-lister/kubernetes-components.d.ts +56 -0
  62. package/dist/cloud-lister/kubernetes-components.js +642 -0
  63. package/dist/cloud-lister/kubernetes.d.ts +18 -0
  64. package/dist/cloud-lister/kubernetes.js +26 -1
  65. package/dist/cloud-lister/mask.d.ts +5 -1
  66. package/dist/cloud-lister/mask.js +14 -5
  67. package/dist/components/cli-support.d.ts +1 -1
  68. package/dist/components/cli-support.js +1 -1
  69. package/dist/config-environments.d.ts +8 -1
  70. package/dist/config-environments.js +2 -0
  71. package/dist/config-import.d.ts +1 -1
  72. package/dist/config-import.js +6 -2
  73. package/dist/config-sandbox.d.ts +1 -1
  74. package/dist/config-sandbox.js +3 -3
  75. package/dist/config.d.ts +369 -10
  76. package/dist/config.js +127 -7
  77. package/dist/deep-observation.js +9 -3
  78. package/dist/floor-table.data.js +21 -1
  79. package/dist/forge-remote.d.ts +13 -0
  80. package/dist/forge-remote.js +15 -0
  81. package/dist/lexicon.d.ts +45 -4
  82. package/dist/lifecycle/__fixtures__/package-files.d.ts +32 -0
  83. package/dist/lifecycle/__fixtures__/package-files.js +72 -0
  84. package/dist/lifecycle/__fixtures__/publish-fakes.d.ts +62 -0
  85. package/dist/lifecycle/__fixtures__/publish-fakes.js +275 -3
  86. package/dist/lifecycle/publish-attachments.d.ts +2 -1
  87. package/dist/lifecycle/publish-attachments.js +19 -2
  88. package/dist/lifecycle/publish-cargo.d.ts +99 -0
  89. package/dist/lifecycle/publish-cargo.js +412 -0
  90. package/dist/lifecycle/publish-credentials.d.ts +1 -1
  91. package/dist/lifecycle/publish-credentials.js +13 -0
  92. package/dist/lifecycle/publish-declaration.d.ts +322 -4
  93. package/dist/lifecycle/publish-declaration.js +340 -9
  94. package/dist/lifecycle/publish-forge.d.ts +45 -2
  95. package/dist/lifecycle/publish-forge.js +434 -34
  96. package/dist/lifecycle/publish-git-ssh.d.ts +15 -0
  97. package/dist/lifecycle/publish-git-ssh.js +30 -4
  98. package/dist/lifecycle/publish-github.d.ts +40 -2
  99. package/dist/lifecycle/publish-github.js +100 -3
  100. package/dist/lifecycle/publish-helm.d.ts +83 -0
  101. package/dist/lifecycle/publish-helm.js +452 -0
  102. package/dist/lifecycle/publish-homebrew.d.ts +7 -9
  103. package/dist/lifecycle/publish-homebrew.js +34 -197
  104. package/dist/lifecycle/publish-index.d.ts +141 -0
  105. package/dist/lifecycle/publish-index.js +719 -0
  106. package/dist/lifecycle/publish-marketplace.js +77 -0
  107. package/dist/lifecycle/publish-maven.d.ts +79 -0
  108. package/dist/lifecycle/publish-maven.js +364 -0
  109. package/dist/lifecycle/publish-mcp-registry.d.ts +66 -0
  110. package/dist/lifecycle/publish-mcp-registry.js +305 -0
  111. package/dist/lifecycle/publish-npm.d.ts +27 -1
  112. package/dist/lifecycle/publish-npm.js +216 -3
  113. package/dist/lifecycle/publish-nuget.d.ts +93 -0
  114. package/dist/lifecycle/publish-nuget.js +377 -0
  115. package/dist/lifecycle/publish-oci.d.ts +91 -2
  116. package/dist/lifecycle/publish-oci.js +247 -8
  117. package/dist/lifecycle/publish-package-files.d.ts +16 -0
  118. package/dist/lifecycle/publish-package-files.js +39 -0
  119. package/dist/lifecycle/publish-pypi.d.ts +138 -0
  120. package/dist/lifecycle/publish-pypi.js +657 -0
  121. package/dist/lifecycle/publish-record.d.ts +6 -3
  122. package/dist/lifecycle/publish-record.js +6 -3
  123. package/dist/lifecycle/publish-rubygems.d.ts +84 -0
  124. package/dist/lifecycle/publish-rubygems.js +366 -0
  125. package/dist/lifecycle/publish-signing.d.ts +147 -0
  126. package/dist/lifecycle/publish-signing.js +257 -0
  127. package/dist/lifecycle/publish-targets.d.ts +37 -1
  128. package/dist/lifecycle/publish-targets.js +102 -0
  129. package/dist/lifecycle/publish-tauri.js +43 -0
  130. package/dist/lifecycle/publish-train-names.d.ts +57 -0
  131. package/dist/lifecycle/publish-train-names.js +123 -0
  132. package/dist/lifecycle/publish-verify.d.ts +121 -0
  133. package/dist/lifecycle/publish-verify.js +130 -0
  134. package/dist/lifecycle/query.js +8 -0
  135. package/dist/lifecycle/release-artifacts.d.ts +290 -0
  136. package/dist/lifecycle/release-artifacts.js +808 -0
  137. package/dist/lifecycle/release-changelog.d.ts +13 -1
  138. package/dist/lifecycle/release-changelog.js +35 -2
  139. package/dist/lifecycle/release-cut.d.ts +64 -4
  140. package/dist/lifecycle/release-cut.js +147 -34
  141. package/dist/lifecycle/release-doctor.d.ts +113 -0
  142. package/dist/lifecycle/release-doctor.js +1198 -0
  143. package/dist/lifecycle/release-green.d.ts +86 -0
  144. package/dist/lifecycle/release-green.js +286 -0
  145. package/dist/lifecycle/release-init-registries.d.ts +48 -0
  146. package/dist/lifecycle/release-init-registries.js +97 -0
  147. package/dist/lifecycle/release-init.d.ts +275 -0
  148. package/dist/lifecycle/release-init.js +984 -0
  149. package/dist/lifecycle/release-intents.d.ts +73 -0
  150. package/dist/lifecycle/release-intents.js +128 -0
  151. package/dist/lifecycle/release-next.d.ts +111 -0
  152. package/dist/lifecycle/release-next.js +251 -0
  153. package/dist/lifecycle/release-prerelease.d.ts +19 -0
  154. package/dist/lifecycle/release-prerelease.js +30 -0
  155. package/dist/lifecycle/release-publish.d.ts +256 -10
  156. package/dist/lifecycle/release-publish.js +247 -35
  157. package/dist/lifecycle/release-status-change.d.ts +226 -0
  158. package/dist/lifecycle/release-status-change.js +478 -0
  159. package/dist/lifecycle/release-status.d.ts +11 -0
  160. package/dist/lifecycle/release-status.js +1 -1
  161. package/dist/lifecycle/release-store.d.ts +73 -2
  162. package/dist/lifecycle/release-store.js +32 -1
  163. package/dist/lifecycle/release-tag.d.ts +142 -0
  164. package/dist/lifecycle/release-tag.js +322 -0
  165. package/dist/lifecycle/release-verify.d.ts +73 -1
  166. package/dist/lifecycle/release-verify.js +117 -2
  167. package/dist/lifecycle/release-version-formats.d.ts +73 -0
  168. package/dist/lifecycle/release-version-formats.js +570 -0
  169. package/dist/lifecycle/release-version.d.ts +58 -10
  170. package/dist/lifecycle/release-version.js +164 -36
  171. package/dist/lifecycle/release-workstation.d.ts +3 -2
  172. package/dist/lifecycle/release-workstation.js +3 -2
  173. package/dist/op/generate-pipeline.js +1 -1
  174. package/dist/op/local-executor.d.ts +1 -1
  175. package/dist/op/local-executor.js +2 -2
  176. package/dist/op/op-waves-evidence.js +9 -2
  177. package/dist/pr-forge-base.js +4 -2
  178. package/dist/pr-forge.d.ts +20 -2
  179. package/dist/pr-forge.js +46 -10
  180. package/dist/release-floors.d.ts +8 -1
  181. package/dist/release-floors.js +9 -2
  182. package/dist/sensitive-key.d.ts +12 -0
  183. package/dist/sensitive-key.js +52 -0
  184. package/dist/tool-pins.d.ts +40 -0
  185. package/dist/tool-pins.js +66 -0
  186. package/dist/ts-loader.d.ts +8 -0
  187. package/dist/ts-loader.js +19 -0
  188. package/dist/wave-runtime.mjs +345 -342
  189. package/dist/workspace/ci-forge.d.ts +17 -0
  190. package/dist/workspace/ci-forge.js +17 -0
  191. package/dist/workspace/ci-init.js +1 -1
  192. package/dist/workspace/composites.schema.json +1 -0
  193. package/dist/workspace/declaration.d.ts +8 -0
  194. package/dist/workspace/declaration.js +12 -0
  195. package/dist/workspace/declaration.schema.json +8 -0
  196. package/dist/workspace/environments.d.ts +2 -0
  197. package/dist/workspace/environments.js +1 -1
  198. package/dist/workspace/identity-gate-rule.d.ts +61 -5
  199. package/dist/workspace/identity-gate-rule.js +81 -12
  200. package/dist/workspace/lexicon-outputs.d.ts +1 -1
  201. package/dist/workspace/lexicon-outputs.js +1 -1
  202. package/dist/workspace/member-pipeline.d.ts +2 -1
  203. package/dist/workspace/member-pipeline.js +5 -2
  204. package/dist/workspace/reason-codes.d.ts +2 -0
  205. package/dist/workspace/reason-codes.js +3 -1
  206. package/dist/workspace/release-changed.d.ts +75 -4
  207. package/dist/workspace/release-changed.js +205 -34
  208. package/dist/workspace/release-changed.schema.json +20 -2
  209. package/dist/workspace/release-steps/artifacts.d.ts +7 -0
  210. package/dist/workspace/release-steps/artifacts.js +45 -0
  211. package/dist/workspace/release-steps/builds.d.ts +12 -0
  212. package/dist/workspace/release-steps/builds.js +38 -0
  213. package/dist/workspace/release-steps/doctor.d.ts +8 -0
  214. package/dist/workspace/release-steps/doctor.js +14 -0
  215. package/dist/workspace/release-steps/goreleaser.d.ts +16 -0
  216. package/dist/workspace/release-steps/goreleaser.js +36 -0
  217. package/dist/workspace/release-steps/green.d.ts +3 -0
  218. package/dist/workspace/release-steps/green.js +6 -0
  219. package/dist/workspace/release-steps/images.d.ts +22 -0
  220. package/dist/workspace/release-steps/images.js +59 -0
  221. package/dist/workspace/release-steps/index.d.ts +9 -0
  222. package/dist/workspace/release-steps/index.js +50 -0
  223. package/dist/workspace/release-steps/nfpm.d.ts +13 -0
  224. package/dist/workspace/release-steps/nfpm.js +29 -0
  225. package/dist/workspace/release-steps/nuget.d.ts +14 -0
  226. package/dist/workspace/release-steps/nuget.js +16 -0
  227. package/dist/workspace/release-steps/pypi.d.ts +15 -0
  228. package/dist/workspace/release-steps/pypi.js +21 -0
  229. package/dist/workspace/release-steps/qemu.d.ts +21 -0
  230. package/dist/workspace/release-steps/qemu.js +35 -0
  231. package/dist/workspace/release-steps/signing.d.ts +18 -0
  232. package/dist/workspace/release-steps/signing.js +30 -0
  233. package/dist/workspace/release-steps/stamp.d.ts +3 -0
  234. package/dist/workspace/release-steps/stamp.js +4 -0
  235. package/dist/workspace/release-steps/targets.d.ts +31 -0
  236. package/dist/workspace/release-steps/targets.js +40 -0
  237. package/dist/workspace/release-steps/types.d.ts +104 -0
  238. package/dist/workspace/release-steps/types.js +2 -0
  239. package/dist/workspace/release-steps/verify.d.ts +3 -0
  240. package/dist/workspace/release-steps/verify.js +4 -0
  241. package/dist/workspace/release-toolchains.d.ts +59 -0
  242. package/dist/workspace/release-toolchains.js +133 -0
  243. package/dist/workspace/release-train-workflow.d.ts +36 -0
  244. package/dist/workspace/release-train-workflow.js +121 -0
  245. package/dist/workspace/release-train.d.ts +3 -1
  246. package/dist/workspace/release-train.js +20 -3
  247. package/dist/workspace/release-workflow.d.ts +183 -59
  248. package/dist/workspace/release-workflow.js +570 -201
  249. package/dist/workspace/releases.schema.json +70 -1
  250. package/dist/workspace/search-contract.d.ts +1 -1
  251. package/dist/workspace/security.js +9 -2
  252. package/dist/workspace/train-cut.d.ts +182 -0
  253. package/dist/workspace/train-cut.js +504 -0
  254. package/dist/workspace/train-prepare.d.ts +64 -0
  255. package/dist/workspace/train-prepare.js +313 -0
  256. package/dist/workspace/train-publish.d.ts +177 -0
  257. package/dist/workspace/train-publish.js +574 -0
  258. package/dist/workspace/train-range-labels.d.ts +33 -0
  259. package/dist/workspace/train-range-labels.js +109 -0
  260. package/dist/workspace/train-shell.d.ts +5 -0
  261. package/dist/workspace/train-shell.js +17 -0
  262. package/dist/workspace/trust/check-evidence-report.d.ts +3 -7
  263. package/dist/workspace/trust/check-evidence-report.js +3 -7
  264. package/dist/workspace/trust/seal.d.ts +13 -3
  265. package/dist/workspace/trust/seal.js +14 -4
  266. package/dist/workspace/work-cli.d.ts +3 -2
  267. package/dist/workspace/work-cli.js +3 -2
  268. package/dist/workspace/workspace-ledger.d.ts +14 -1
  269. package/dist/workspace/workspace-ledger.js +33 -7
  270. package/package.json +1 -1
@@ -0,0 +1,984 @@
1
+ /**
2
+ * `chant release init` (#5160): the first setup of `chant release` in a
3
+ * project that has never used chant.
4
+ *
5
+ * It reads the project ({@link detectProject}): the package.json and its
6
+ * npm, pnpm or yarn workspaces, go.mod, Cargo.toml, pyproject.toml,
7
+ * Dockerfiles, a goreleaser config, Helm charts and an nfpm config (#5233),
8
+ * the forge `origin` names, and the tags
9
+ * releases were made under so far. From that it plans a `release` block
10
+ * ({@link planRelease}): the tag template, `legacyTags`, the green gate, the
11
+ * version stamping, the publish targets it can infer, and a dispatched
12
+ * release workflow. Then it writes that block into `chant.config.ts`
13
+ * ({@link insertReleaseBlock}), making a config of the block alone when
14
+ * there is none.
15
+ *
16
+ * Detection reads files and local git only; it never reaches a registry or
17
+ * the forge. Everything it can't set up from the repository, such as an npm
18
+ * trusted publisher, is a step printed for a person ({@link ReleaseInitPlan.registry}).
19
+ */
20
+ import { execFileSync } from "node:child_process";
21
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
22
+ import { basename, join, posix, relative, sep } from "node:path";
23
+ import { GENERATED_MARKER } from "../discovery/files.js";
24
+ import { forgeOfRemote } from "../forge-remote.js";
25
+ import { detectRegistryProjects, planRegistryTargets } from "./release-init-registries.js";
26
+ /** A refusal of `chant release init`, with its code. */
27
+ export class ReleaseInitError extends Error {
28
+ constructor(code, message, fix) {
29
+ super(message);
30
+ this.code = code;
31
+ this.fix = fix;
32
+ this.name = "ReleaseInitError";
33
+ }
34
+ }
35
+ const VERSION_TAG = /^(.*?)(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/;
36
+ /** The characters a `release.tag` template may hold around its placeholder. */
37
+ const TEMPLATE_PREFIX = /^[A-Za-z0-9._+/-]*$/;
38
+ function compareVersions(a, b) {
39
+ const pa = a.split(/[-+]/)[0].split(".").map(Number);
40
+ const pb = b.split(/[-+]/)[0].split(".").map(Number);
41
+ for (let i = 0; i < 3; i++)
42
+ if (pa[i] !== pb[i])
43
+ return pa[i] - pb[i];
44
+ // A release sorts after its prereleases.
45
+ const ra = a.includes("-") ? 0 : 1;
46
+ const rb = b.includes("-") ? 0 : 1;
47
+ return ra - rb;
48
+ }
49
+ /**
50
+ * The tag history of a list of tags: version tags grouped by their prefix,
51
+ * the largest group first. `ci/` and `chant/` tags are chant's own and
52
+ * left out.
53
+ */
54
+ export function readTagHistory(tags) {
55
+ const groups = new Map();
56
+ for (const t of tags) {
57
+ if (t.startsWith("ci/") || t.startsWith("chant/"))
58
+ continue;
59
+ const m = VERSION_TAG.exec(t);
60
+ if (!m)
61
+ continue;
62
+ const prefix = m[1];
63
+ groups.set(prefix, [...(groups.get(prefix) ?? []), m[2]]);
64
+ }
65
+ const ranked = [...groups.entries()].sort((a, b) => b[1].length - a[1].length || a[0].localeCompare(b[0]));
66
+ if (ranked.length === 0)
67
+ return { prefix: null, count: 0, newest: null, others: [] };
68
+ const [prefix, versions] = ranked[0];
69
+ const newest = [...versions].sort(compareVersions).pop();
70
+ return { prefix, count: versions.length, newest: `${prefix}${newest}`, others: ranked.slice(1).map(([p, v]) => ({ prefix: p, count: v.length })) };
71
+ }
72
+ function readJson(file) {
73
+ try {
74
+ return JSON.parse(readFileSync(file, "utf-8"));
75
+ }
76
+ catch {
77
+ return null;
78
+ }
79
+ }
80
+ function readText(file) {
81
+ try {
82
+ return readFileSync(file, "utf-8");
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ }
88
+ function isDir(p) {
89
+ try {
90
+ return statSync(p).isDirectory();
91
+ }
92
+ catch {
93
+ return false;
94
+ }
95
+ }
96
+ function readPackage(root, dir) {
97
+ const pkg = readJson(join(root, dir, "package.json"));
98
+ if (!pkg)
99
+ return null;
100
+ const obj = (v) => (v && typeof v === "object" ? v : {});
101
+ const engines = obj(pkg.engines);
102
+ const publishConfig = obj(pkg.publishConfig);
103
+ return {
104
+ dir,
105
+ name: typeof pkg.name === "string" ? pkg.name : null,
106
+ private: pkg.private === true,
107
+ access: typeof publishConfig.access === "string" ? publishConfig.access : null,
108
+ vscode: typeof engines.vscode === "string",
109
+ publisher: typeof pkg.publisher === "string" ? pkg.publisher : null,
110
+ deps: [...new Set([pkg.dependencies, pkg.peerDependencies, pkg.optionalDependencies].flatMap((d) => Object.keys(obj(d))))],
111
+ scripts: Object.keys(obj(pkg.scripts)),
112
+ packList: Array.isArray(pkg.files) || existsSync(join(root, dir, ".npmignore")),
113
+ };
114
+ }
115
+ const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "vendor", "target", "build", ".venv", "venv"]);
116
+ /** The directories a workspace pattern such as `packages/*` or `apps/**` names, from `root`. */
117
+ export function expandWorkspacePattern(root, pattern) {
118
+ const parts = pattern.replace(/^\.\//, "").replace(/\/+$/, "").split("/").filter((p) => p !== "" && p !== ".");
119
+ let dirs = [""];
120
+ for (const part of parts) {
121
+ const next = [];
122
+ for (const d of dirs) {
123
+ const abs = join(root, d);
124
+ if (part === "**") {
125
+ const walk = (rel, depth) => {
126
+ next.push(rel);
127
+ if (depth === 0)
128
+ return;
129
+ for (const e of safeReaddir(join(root, rel)))
130
+ if (isDir(join(root, rel, e)) && !SKIP_DIRS.has(e) && !e.startsWith("."))
131
+ walk(rel ? `${rel}/${e}` : e, depth - 1);
132
+ };
133
+ walk(d, 3);
134
+ }
135
+ else if (part.includes("*")) {
136
+ const re = new RegExp(`^${part.split("*").map((s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("[^/]*")}$`);
137
+ for (const e of safeReaddir(abs))
138
+ if (re.test(e) && !SKIP_DIRS.has(e) && isDir(join(abs, e)))
139
+ next.push(d ? `${d}/${e}` : e);
140
+ }
141
+ else if (isDir(join(abs, part))) {
142
+ next.push(d ? `${d}/${part}` : part);
143
+ }
144
+ }
145
+ dirs = next;
146
+ }
147
+ return [...new Set(dirs)].filter((d) => d !== "").sort();
148
+ }
149
+ function safeReaddir(dir) {
150
+ try {
151
+ return readdirSync(dir);
152
+ }
153
+ catch {
154
+ return [];
155
+ }
156
+ }
157
+ /** The workspace patterns of a package.json (`workspaces` as a list or `{ packages }`) or a pnpm-workspace.yaml. */
158
+ export function workspacePatterns(root) {
159
+ const pnpm = readText(join(root, "pnpm-workspace.yaml"));
160
+ if (pnpm !== null) {
161
+ const out = [];
162
+ let inPackages = false;
163
+ for (const line of pnpm.split("\n")) {
164
+ if (/^packages\s*:/.test(line)) {
165
+ inPackages = true;
166
+ continue;
167
+ }
168
+ if (inPackages && /^\S/.test(line))
169
+ inPackages = false;
170
+ const m = inPackages ? /^\s*-\s*['"]?([^'"#]+?)['"]?\s*(#.*)?$/.exec(line) : null;
171
+ if (m)
172
+ out.push(m[1]);
173
+ }
174
+ return out;
175
+ }
176
+ const pkg = readJson(join(root, "package.json"));
177
+ const ws = pkg?.workspaces;
178
+ if (Array.isArray(ws))
179
+ return ws.filter((w) => typeof w === "string");
180
+ if (ws && typeof ws === "object" && Array.isArray(ws.packages))
181
+ return (ws.packages).filter((w) => typeof w === "string");
182
+ return null;
183
+ }
184
+ function git(cwd, args) {
185
+ try {
186
+ return execFileSync("git", args, { cwd, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
187
+ }
188
+ catch {
189
+ return null;
190
+ }
191
+ }
192
+ /** Dockerfiles at the project root and one or two directories below it, `node_modules` and the like left out. */
193
+ function findDockerfiles(root) {
194
+ const out = [];
195
+ const isDockerfile = (n) => n === "Dockerfile" || n === "Containerfile";
196
+ const walk = (rel, depth) => {
197
+ for (const e of safeReaddir(join(root, rel))) {
198
+ const p = rel ? `${rel}/${e}` : e;
199
+ if (isDockerfile(e) && !isDir(join(root, p)))
200
+ out.push(p);
201
+ else if (depth > 0 && !SKIP_DIRS.has(e) && !e.startsWith(".") && isDir(join(root, p)))
202
+ walk(p, depth - 1);
203
+ }
204
+ };
205
+ walk("", 2);
206
+ return out.sort((a, b) => a.split("/").length - b.split("/").length || a.localeCompare(b));
207
+ }
208
+ /** Directories holding a `Chart.yaml`, up to three levels down, not looking inside a chart (#5233). */
209
+ function findCharts(root) {
210
+ const out = [];
211
+ const walk = (rel, depth) => {
212
+ const here = join(root, rel);
213
+ if (existsSync(join(here, "Chart.yaml")) && !isDir(join(here, "Chart.yaml"))) {
214
+ out.push({ dir: rel || ".", name: /^name:[ \t]*["']?([^"'\s#]+)/m.exec(readText(join(here, "Chart.yaml")) ?? "")?.[1] ?? null });
215
+ return;
216
+ }
217
+ if (depth === 0)
218
+ return;
219
+ for (const e of safeReaddir(here)) {
220
+ const p = rel ? `${rel}/${e}` : e;
221
+ if (!SKIP_DIRS.has(e) && !e.startsWith(".") && isDir(join(root, p)))
222
+ walk(p, depth - 1);
223
+ }
224
+ };
225
+ walk("", 3);
226
+ return out.sort((a, b) => a.dir.localeCompare(b.dir));
227
+ }
228
+ /** The nfpm config files `release init` looks for (#5233). */
229
+ const NFPM_FILES = ["nfpm.yaml", "nfpm.yml", ".nfpm.yaml", ".nfpm.yml"];
230
+ const GORELEASER_FILES = [".goreleaser.yaml", ".goreleaser.yml", "goreleaser.yaml", "goreleaser.yml"];
231
+ /** Whether a goreleaser config sets `snapshot.version_template` to the release label. */
232
+ export function goreleaserFacts(text) {
233
+ return {
234
+ labelTemplate: /version_template\s*:\s*["']?\{\{\s*\.Env\.CHANT_RELEASE_LABEL\s*\}\}/.test(text),
235
+ snapshot: /^snapshot\s*:/m.test(text),
236
+ images: /^(dockers|dockers_v2|kos)\s*:/m.test(text),
237
+ };
238
+ }
239
+ /** The lines a goreleaser config needs so its snapshot build carries the release's label. */
240
+ export const GORELEASER_SNAPSHOT = 'snapshot:\n version_template: "{{ .Env.CHANT_RELEASE_LABEL }}"\n';
241
+ /** Read the project at `root` (the directory `chant release init` runs in). */
242
+ /** The sections of a TOML file by header, each holding its own lines only. */
243
+ function tomlSections(text) {
244
+ const out = new Map();
245
+ let name = "";
246
+ for (const line of text.split(/\r?\n/)) {
247
+ const h = /^\s*\[{1,2}\s*([^\]]+?)\s*\]{1,2}\s*(#.*)?$/.exec(line);
248
+ if (h) {
249
+ name = h[1];
250
+ continue;
251
+ }
252
+ out.set(name, `${out.get(name) ?? ""}${line}\n`);
253
+ }
254
+ return out;
255
+ }
256
+ /** A `Cargo.toml`'s name, workspace, stampable version and `publish = false`. */
257
+ export function cargoFacts(text) {
258
+ const sections = tomlSections(text);
259
+ const pkg = sections.get("package") ?? "";
260
+ const str = (body, key) => new RegExp(`^${key}\\s*=\\s*"([^"]*)"`, "m").exec(body)?.[1] ?? null;
261
+ return {
262
+ name: str(pkg, "name"),
263
+ workspace: sections.has("workspace"),
264
+ version: str(pkg, "version") !== null || str(sections.get("workspace.package") ?? "", "version") !== null,
265
+ unpublishable: /^publish\s*=\s*false\b/m.test(pkg),
266
+ };
267
+ }
268
+ /** A `pyproject.toml`'s project name, and whether its version is a static string that `release.version.files` can stamp. */
269
+ export function pyprojectFacts(text) {
270
+ const sections = tomlSections(text);
271
+ const str = (body, key) => new RegExp(`^${key}\\s*=\\s*["']([^"']*)["']`, "m").exec(body)?.[1] ?? null;
272
+ const project = sections.get("project") ?? "";
273
+ const poetry = sections.get("tool.poetry") ?? "";
274
+ const name = str(project, "name") ?? str(poetry, "name");
275
+ return { name, pyproject: true, version: str(project, "version") !== null || str(poetry, "version") !== null };
276
+ }
277
+ export function detectProject(root) {
278
+ const top = git(root, ["rev-parse", "--show-toplevel"])?.trim() || root;
279
+ const fromTop = relative(top, root).split(sep).join("/");
280
+ const path = fromTop === "" ? null : fromTop;
281
+ const remote = git(root, ["remote", "get-url", "origin"])?.trim();
282
+ const at = remote ? forgeOfRemote(remote) : undefined;
283
+ const origin = at ? { kind: at.kind, host: at.host, repo: at.repo } : null;
284
+ const workflowForge = isDir(join(top, ".github", "workflows")) ? "github" : isDir(join(top, ".forgejo", "workflows")) ? "forgejo" : existsSync(join(top, ".gitlab-ci.yml")) ? "gitlab" : (origin?.kind ?? "github");
285
+ const ciFiles = [
286
+ ...[".github/workflows", ".forgejo/workflows", ".gitea/workflows"].flatMap((d) => safeReaddir(join(top, d)).filter((f) => /\.ya?ml$/.test(f) && f !== "chant-release.yml").map((f) => `${d}/${f}`)),
287
+ ...(existsSync(join(top, ".gitlab-ci.yml")) ? [".gitlab-ci.yml"] : []),
288
+ ];
289
+ const publishWorkflows = ciFiles.filter((f) => {
290
+ if (!f.startsWith(".github/workflows/"))
291
+ return false;
292
+ const text = readText(join(top, f));
293
+ if (text === null || text.includes(GENERATED_MARKER) || !NPM_PUBLISH.test(text))
294
+ return false;
295
+ // A project below the repository root: only a workflow that names its directory publishes it.
296
+ return path === null || text.includes(path);
297
+ });
298
+ let node = null;
299
+ const rootPkg = readPackage(root, ".");
300
+ if (rootPkg) {
301
+ const lockfile = ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "npm-shrinkwrap.json"].find((f) => existsSync(join(root, f))) ?? null;
302
+ const manager = existsSync(join(root, "pnpm-lock.yaml")) || existsSync(join(root, "pnpm-workspace.yaml")) ? "pnpm" : existsSync(join(root, "yarn.lock")) || existsSync(join(root, ".yarnrc.yml")) ? "yarn" : "npm";
303
+ const patterns = workspacePatterns(root);
304
+ const workspaces = patterns === null
305
+ ? null
306
+ : [...new Set(patterns.filter((p) => !p.startsWith("!")).flatMap((p) => expandWorkspacePattern(root, p)))]
307
+ .filter((d) => !patterns.some((p) => p.startsWith("!") && expandWorkspacePattern(root, p.slice(1)).includes(d)))
308
+ .map((d) => readPackage(root, d))
309
+ .filter((p) => p !== null);
310
+ const pkg = readJson(join(root, "package.json"));
311
+ const allDeps = [pkg?.dependencies, pkg?.devDependencies].flatMap((d) => Object.keys(d && typeof d === "object" ? d : {}));
312
+ node = { manager, lockfile, yarnBerry: existsSync(join(root, ".yarnrc.yml")), root: rootPkg, workspaces, hasChant: allDeps.includes("@intentius/chant") };
313
+ }
314
+ const gomod = readText(join(root, "go.mod"));
315
+ const go = gomod === null ? null : { module: /^module\s+(\S+)/m.exec(gomod)?.[1] ?? null };
316
+ const cargo = readText(join(root, "Cargo.toml"));
317
+ const rust = cargo === null ? null : cargoFacts(cargo);
318
+ const pyproject = readText(join(root, "pyproject.toml"));
319
+ const python = pyproject === null ? (existsSync(join(root, "setup.py")) ? { name: null, pyproject: false, version: false } : null) : pyprojectFacts(pyproject);
320
+ const grFile = GORELEASER_FILES.find((f) => existsSync(join(root, f)));
321
+ const goreleaser = grFile ? { file: grFile, ...goreleaserFacts(readText(join(root, grFile)) ?? "") } : null;
322
+ const nfpmFile = NFPM_FILES.find((f) => existsSync(join(root, f)));
323
+ const nfpmVersion = nfpmFile ? /^version:[ \t]*["']?[^\n]*\$\{?CHANT_RELEASE_(VERSION|LABEL)/m.test(readText(join(root, nfpmFile)) ?? "") : false;
324
+ const tagList = (git(top, ["tag", "--list"]) ?? "").split("\n").map((t) => t.trim()).filter(Boolean);
325
+ const chantDecl = readJson(join(root, "chant.workspace.json"));
326
+ const ciGreen = !!(chantDecl?.ci && typeof chantDecl.ci === "object" && chantDecl.ci.green);
327
+ const gitignore = [readText(join(root, ".gitignore")), path ? readText(join(top, ".gitignore")) : null].filter((t) => t !== null).join("\n");
328
+ return {
329
+ path,
330
+ origin,
331
+ workflowForge,
332
+ ciFiles,
333
+ publishWorkflows,
334
+ node,
335
+ go,
336
+ rust,
337
+ python,
338
+ dockerfiles: findDockerfiles(root),
339
+ goreleaser,
340
+ charts: findCharts(root),
341
+ nfpm: nfpmFile ? { file: nfpmFile, version: nfpmVersion } : null,
342
+ tags: readTagHistory(tagList),
343
+ chantCi: ciGreen || tagList.some((t) => t.startsWith("ci/green/") || /^ci\/green-[^/]+\//.test(t)),
344
+ distIgnored: /^\/?dist\/?\s*$/m.test(gitignore) || /^\/?dist\/\*\s*$/m.test(gitignore),
345
+ registries: detectRegistryProjects(root),
346
+ };
347
+ }
348
+ /** A command that publishes to npm: `npm publish`, `pnpm publish`, `yarn publish` or `yarn npm publish`. */
349
+ const NPM_PUBLISH = /\b(?:npm|pnpm|yarn(?:\s+npm)?)\s+publish\b/;
350
+ /** The default release workflow file for a forge, from the repository root. */
351
+ const DEFAULT_WORKFLOW_FILES = { github: ".github/workflows/chant-release.yml", forgejo: ".forgejo/workflows/chant-release.yml", gitlab: ".gitlab/chant-release.yml" };
352
+ /**
353
+ * The workflow file a release that publishes to npm runs from: the one
354
+ * workflow under `.github/workflows` that already runs `npm publish`, since
355
+ * the package's npm trusted publisher names that file, else chant's default.
356
+ * Several such files adopt none, and say so in `notes`.
357
+ */
358
+ function releaseWorkflowFile(facts, publishesNpm, notes) {
359
+ const forge = facts.workflowForge;
360
+ const found = forge === "github" && publishesNpm ? (facts.publishWorkflows ?? []) : [];
361
+ if (found.length === 1)
362
+ return { file: found[0], adopted: true };
363
+ if (found.length > 1)
364
+ notes.push(`Several workflows run npm publish (${found.join(", ")}), so the release workflow is a new file: set release.workflow.file to the one npm's trusted publisher names to release from it instead.`);
365
+ return { file: DEFAULT_WORKFLOW_FILES[forge], adopted: false };
366
+ }
367
+ /** Packages in dependency order: each after the packages of the list it depends on, ties by directory. */
368
+ export function dependencyOrder(pkgs) {
369
+ const byName = new Map(pkgs.filter((p) => p.name).map((p) => [p.name, p]));
370
+ const out = [];
371
+ const seen = new Set();
372
+ const visit = (p, stack) => {
373
+ if (seen.has(p.dir) || stack.has(p.dir))
374
+ return;
375
+ stack.add(p.dir);
376
+ for (const d of [...p.deps].sort()) {
377
+ const dep = byName.get(d);
378
+ if (dep)
379
+ visit(dep, stack);
380
+ }
381
+ stack.delete(p.dir);
382
+ seen.add(p.dir);
383
+ out.push(p);
384
+ };
385
+ for (const p of [...pkgs].sort((a, b) => a.dir.localeCompare(b.dir)))
386
+ visit(p, new Set());
387
+ return out;
388
+ }
389
+ /** The OCI repository an image is pushed to on the origin's forge registry, or null for a forge without one chant knows. */
390
+ function imageRepository(origin, image, single) {
391
+ if (!origin)
392
+ return null;
393
+ const repo = origin.repo.toLowerCase();
394
+ const suffix = single ? "" : `/${image}`;
395
+ if (origin.kind === "github")
396
+ return origin.host === "github.com" ? `ghcr.io/${repo}${suffix}` : null;
397
+ if (origin.kind === "gitlab")
398
+ return origin.host === "gitlab.com" ? `registry.gitlab.com/${repo}${suffix}` : null;
399
+ return `${origin.host}/${repo}${suffix}`;
400
+ }
401
+ function imageName(dockerfile, fallback) {
402
+ const dir = posix.dirname(dockerfile);
403
+ const raw = dir === "." ? fallback : basename(dir);
404
+ return raw.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[^a-z0-9]+/, "") || "image";
405
+ }
406
+ /** A tag prefix a `release.tag` template can hold. */
407
+ function templatePrefix(prefix) {
408
+ return TEMPLATE_PREFIX.test(prefix) && !prefix.startsWith("/") && !prefix.includes("..") && !prefix.includes("//");
409
+ }
410
+ /**
411
+ * The tag template a project's history asks for, and the prefixes to read
412
+ * older releases by. `packages` is how many packages one release publishes:
413
+ * with more than one, a prefix other than `v` names one package's tags, so
414
+ * the release gets `v{version}` and the older tags are only read.
415
+ */
416
+ export function tagTemplateOf(facts, packages = 1) {
417
+ const h = facts.tags;
418
+ const goSub = facts.go && facts.path;
419
+ const legacy = [h.prefix, ...h.others.map((o) => o.prefix)].filter((p) => p !== null && p !== "" && templatePrefix(p));
420
+ const follows = h.prefix !== null && templatePrefix(h.prefix) && (packages <= 1 || h.prefix === "v" || h.prefix === "");
421
+ if (follows) {
422
+ const template = `${h.prefix}{version}`;
423
+ const goNote = facts.go && h.prefix !== (goSub ? `${facts.path}/v` : "v") ? `The Go module proxy reads ${goSub ? `${facts.path}/v<version>` : "v<version>"} tags, and this repository's are ${h.prefix}<version>.` : null;
424
+ return {
425
+ template,
426
+ legacy,
427
+ reason: `release.tag "${template}": ${h.count} existing tag${h.count === 1 ? "" : "s"} name releases this way, the newest ${h.newest}`,
428
+ note: goNote,
429
+ };
430
+ }
431
+ const template = goSub ? "{path}/v{version}" : "v{version}";
432
+ const why = h.prefix === null
433
+ ? "no tag in the repository names a version"
434
+ : !templatePrefix(h.prefix)
435
+ ? `the existing tags (${h.prefix}<version>) hold a character a release.tag template can't`
436
+ : `one release publishes ${packages} packages, and the existing ${h.prefix}<version> tags name one package's releases`;
437
+ return { template, legacy, reason: `release.tag "${template}": ${why}${goSub ? ", and a Go module in a subdirectory is tagged <path>/v<version>" : ""}`, note: null };
438
+ }
439
+ /** `release.green` for the project, with its reason, and a note when nothing checks its commits. */
440
+ function greenOf(facts, reasons, notes) {
441
+ reasons.push(facts.chantCi ? 'release.green "chant": chant ci writes ci/green tags here' : 'release.green "forge-checks": a commit may be released when its checks on the forge passed');
442
+ if (!facts.chantCi && facts.ciFiles.length === 0)
443
+ notes.push("No CI workflow runs on this repository's commits, and a cut refuses a commit with no checks: add CI, or set release.green to \"none\" to release with no gate.");
444
+ return facts.chantCi ? "chant" : "forge-checks";
445
+ }
446
+ /** The workflow's chant, install and build for a Node project, with their reasons. */
447
+ function nodeWorkflow(node, opts, workflow, reasons) {
448
+ if (!node.hasChant) {
449
+ workflow.chant = `npx --yes @intentius/chant@${opts.chantVersion}`;
450
+ reasons.push(`release.workflow.chant: @intentius/chant is not a dependency here, so the jobs run it from npm at ${opts.chantVersion}`);
451
+ }
452
+ const lockless = node.lockfile === null;
453
+ if (node.manager === "pnpm")
454
+ workflow.install = "corepack enable && pnpm install --frozen-lockfile";
455
+ else if (node.manager === "yarn")
456
+ workflow.install = `corepack enable && yarn install ${node.yarnBerry ? "--immutable" : "--frozen-lockfile"}`;
457
+ else if (lockless)
458
+ workflow.install = "npm install";
459
+ if (workflow.install)
460
+ reasons.push(`release.workflow.install: ${node.manager === "npm" ? "there is no package-lock.json for npm ci" : `the lockfile is ${node.manager}'s`}`);
461
+ if (node.manager !== "npm" && node.root.scripts.includes("build"))
462
+ workflow.build = `${node.manager} run build`;
463
+ }
464
+ /** Plan the `release` block for a project. */
465
+ export function planRelease(facts, opts) {
466
+ const release = {};
467
+ const reasons = [];
468
+ const notes = [];
469
+ const registry = [];
470
+ const publish = [];
471
+ const workflow = { trigger: "dispatch" };
472
+ const forge = facts.workflowForge;
473
+ const node0 = facts.node;
474
+ const publishedCount = node0 ? (node0.workspaces ? [...(node0.root.private ? [] : [node0.root]), ...node0.workspaces] : [node0.root]).filter((p) => p.name && !p.private && !p.vscode).length : 0;
475
+ const { file: workflowFile, adopted } = releaseWorkflowFile(facts, publishedCount > 0, notes);
476
+ const workflowName = posix.basename(workflowFile);
477
+ if (adopted)
478
+ workflow.file = workflowFile;
479
+ const tag = tagTemplateOf(facts, publishedCount);
480
+ release.tag = tag.template;
481
+ reasons.push(tag.reason);
482
+ if (tag.note)
483
+ notes.push(tag.note);
484
+ if (tag.legacy.length > 0) {
485
+ release.legacyTags = tag.legacy;
486
+ reasons.push(`release.legacyTags ${JSON.stringify(tag.legacy)}: chant release next and release changed read the newest ${tag.legacy.map((p) => `${p}<version>`).join(" or ")} tag as the last release until chant has cut one`);
487
+ }
488
+ const unread = [facts.tags.prefix, ...facts.tags.others.map((o) => o.prefix)].filter((p) => p !== null && p !== "" && !templatePrefix(p));
489
+ if (unread.length > 0)
490
+ notes.push(`Tags that no release.tag can make are left as they are: ${unread.slice(0, 5).map((p) => `${p}<version>`).join(", ")}.`);
491
+ release.green = greenOf(facts, reasons, notes);
492
+ // npm packages, and VS Code extensions.
493
+ const node = facts.node;
494
+ if (node) {
495
+ const candidates = node.workspaces ? [...(node.root.private ? [] : [node.root]), ...node.workspaces] : [node.root];
496
+ const named = candidates.filter((p) => p.name);
497
+ const extensions = named.filter((p) => p.vscode && !p.private);
498
+ const packages = dependencyOrder(named.filter((p) => !p.private && !p.vscode));
499
+ const skipped = named.filter((p) => p.private);
500
+ if (packages.length > 0) {
501
+ const dirs = packages.map((p) => p.dir);
502
+ const scopedUnset = packages.filter((p) => p.name.startsWith("@") && p.access === null);
503
+ const target = { type: "npm", packages: dirs };
504
+ if (scopedUnset.length > 0)
505
+ target.access = "public";
506
+ publish.push(target);
507
+ reasons.push(`npm target: ${packages.map((p) => p.name).join(", ")}${packages.length > 1 ? ", in dependency order" : ""}${scopedUnset.length > 0 ? `; access "public", since ${scopedUnset.map((p) => p.name).join(", ")} ${scopedUnset.length === 1 ? "is a scoped package" : "are scoped packages"} with no publishConfig.access` : ""}`);
508
+ const names = new Set(packages.map((p) => p.name));
509
+ const internal = packages.some((p) => p.deps.some((d) => names.has(d)));
510
+ release.version = internal ? { packages: dirs, ranges: "exact" } : { packages: dirs };
511
+ reasons.push(`release.version: the release stamps its label into ${dirs.length === 1 ? "the package's" : "each package's"} package.json, so a release needs no version commit${internal ? '; ranges "exact", so each package depends on the versions released beside it' : ""}`);
512
+ const list = packages.map((p) => p.name).join(", ");
513
+ const one = packages.length === 1;
514
+ registry.push(adopted
515
+ ? `npm ${list}: the trusted publisher on npmjs.com that names ${facts.origin?.repo ?? "this repository"} and the workflow file ${workflowName} keeps working, since the release runs from that file; edit it to allow npm dist-tag, since the reveal moves latest.${one ? "" : " A package with no trusted publisher yet needs one naming the same file."}`
516
+ : `npm ${list}: on npmjs.com, add a trusted publisher to ${one ? "the package" : "each package"} for ${forge === "gitlab" ? `GitLab CI/CD naming ${facts.origin?.repo ?? "this project"} and the top-level config .gitlab-ci.yml` : `${forge === "github" ? "GitHub Actions" : "this forge"} naming ${facts.origin?.repo ?? "this repository"} and the workflow file ${workflowName}`}, and allow npm dist-tag, since the reveal moves latest. A package that is not on npm yet needs its first version published by hand before it has settings.`);
517
+ }
518
+ if (skipped.length > 0)
519
+ notes.push(`Not published, being private: ${skipped.map((p) => p.name).join(", ")}.`);
520
+ for (const ext of extensions) {
521
+ const vsix = `${ext.dir === "." ? "" : `${ext.dir}/`}dist/${ext.name.replace(/^@[^/]+\//, "")}.vsix`;
522
+ publish.push({ type: "marketplace", marketplace: "vscode", vsix });
523
+ publish.push({ type: "marketplace", marketplace: "openvsx", vsix, auth: "trusted-publishing" });
524
+ reasons.push(`marketplace targets: ${ext.name} is a VS Code extension, published to the VS Code Marketplace and Open VSX from ${vsix}`);
525
+ notes.push(`The build must write ${vsix}, such as with vsce package -o ${vsix}, and the VS Code Marketplace target needs vsce on PATH.`);
526
+ // A GitLab job gets the project's CI/CD variables as they are.
527
+ if (forge !== "gitlab")
528
+ workflow.env = { ...(workflow.env ?? {}), VSCE_PAT: "${{ secrets.VSCE_PAT }}" };
529
+ registry.push(`VS Code Marketplace ${ext.publisher ?? "<publisher>"}.${ext.name}: create a personal access token with Marketplace (Manage) scope and store it as the ${forge === "gitlab" ? "masked CI/CD variable" : "repository secret"} VSCE_PAT.`);
530
+ registry.push(`Open VSX ${ext.publisher ?? "<publisher>"}.${ext.name}: create the namespace ${ext.publisher ?? "<publisher>"} once, and add ${facts.origin?.repo ?? "this repository"} with the workflow file ${workflowName} under the extension's trusted publishers at https://open-vsx.org/user-settings/trusted-publishers.`);
531
+ }
532
+ nodeWorkflow(node, opts, workflow, reasons);
533
+ }
534
+ // Images.
535
+ const goreleaserImages = facts.goreleaser?.images ?? false;
536
+ const dockerfiles = goreleaserImages ? [] : facts.dockerfiles;
537
+ if (goreleaserImages && facts.dockerfiles.length > 0)
538
+ notes.push(`${facts.goreleaser.file} builds the images, so no Dockerfile is declared in release.images.`);
539
+ const fallbackName = (facts.origin?.repo.split("/").pop() ?? facts.node?.root.name?.replace(/^@[^/]+\//, "") ?? facts.go?.module?.split("/").pop() ?? "app");
540
+ const images = [];
541
+ const usedNames = new Set();
542
+ for (const dockerfile of dockerfiles) {
543
+ let name = imageName(dockerfile, fallbackName);
544
+ while (usedNames.has(name))
545
+ name = `${name}-${usedNames.size}`;
546
+ usedNames.add(name);
547
+ const dir = posix.dirname(dockerfile);
548
+ images.push(dir === "." ? { name, dockerfile } : { name, dockerfile, context: dir });
549
+ const repository = imageRepository(facts.origin, name, dockerfiles.length === 1);
550
+ if (repository) {
551
+ publish.push({ type: "oci", image: `dist/images/${name}.tar`, repository });
552
+ if (repository.startsWith("ghcr.io/"))
553
+ registry.push(`${repository}: the workflow pushes with the run's token. The first push makes the package private; make it public in the package's settings if it should be.`);
554
+ else
555
+ registry.push(`${repository}: set OCI_USERNAME and OCI_PASSWORD for the release workflow, as ${forge === "gitlab" ? "masked CI/CD variables" : "secrets in release.workflow.env"}, with push access to the registry.`);
556
+ }
557
+ else
558
+ notes.push(`${dockerfile} is built into release.images as ${name}, and no oci target is declared: origin names no registry chant knows. Add { type: "oci", image: "dist/images/${name}.tar", repository: "<registry>/<name>" }.`);
559
+ }
560
+ if (images.length > 0) {
561
+ release.images = images;
562
+ reasons.push(`release.images: ${dockerfiles.join(", ")} built once at the cut as reproducible OCI archives${publish.some((p) => p.type === "oci") ? ", pushed by the oci target" : ""}`);
563
+ }
564
+ // goreleaser.
565
+ let goreleaserPatch = null;
566
+ if (facts.goreleaser) {
567
+ const gr = facts.goreleaser;
568
+ if (!gr.labelTemplate) {
569
+ goreleaserPatch = gr.snapshot
570
+ ? { file: gr.file, append: null, manual: `Set snapshot.version_template to "{{ .Env.CHANT_RELEASE_LABEL }}" in ${gr.file}, so the snapshot build carries the release's label.` }
571
+ : { file: gr.file, append: GORELEASER_SNAPSHOT, manual: null };
572
+ }
573
+ release.artifacts = [{ name: "goreleaser", goreleaser: {} }];
574
+ reasons.push(`release.artifacts: ${gr.file} builds the binaries and archives once at the cut with goreleaser release --snapshot, and the release records each file`);
575
+ if (facts.origin) {
576
+ publish.push({ type: "forge", forge: facts.origin.kind, repo: facts.origin.repo, assets: ["artifact:goreleaser"], notes: { generate: "forge" } });
577
+ reasons.push(`forge target: the goreleaser files as assets of the ${facts.origin.kind} release ${facts.origin.repo}, with generated notes`);
578
+ }
579
+ else
580
+ notes.push(`No forge release is declared for ${gr.file}'s files: origin names no GitHub, GitLab or Forgejo repository.`);
581
+ }
582
+ // #5233: Helm charts, packed at the cut and pushed to the registry beside the images.
583
+ const charts = facts.charts ?? [];
584
+ if (charts.length > 0) {
585
+ const entries = charts.map((c, n) => ({ name: charts.length === 1 ? "chart" : `chart-${(c.name ?? `${n + 1}`).toLowerCase().replace(/[^a-z0-9._-]+/g, "-")}`, chart: c.dir }));
586
+ release.artifacts = [...(release.artifacts ?? []), ...entries.map((e) => ({ name: e.name, helm: { chart: e.chart } }))];
587
+ reasons.push(`release.artifacts: ${charts.map((c) => `${c.dir}/Chart.yaml`.replace(/^\.\//, "")).join(", ")} packed once at the cut, with the chart's version set from the label`);
588
+ const repository = imageRepository(facts.origin, "charts", false);
589
+ if (repository) {
590
+ publish.push({ type: "helm", charts: entries.map((e) => `artifact:${e.name}`), oci: { repository } });
591
+ reasons.push(`helm target: ${charts.length === 1 ? "the chart" : "each chart"} pushed to ${repository}/<chart>, tagged with its version, for helm install oci://${repository}/<chart>`);
592
+ if (repository.startsWith("ghcr.io/"))
593
+ registry.push(`${repository}: the workflow pushes the charts with the run's token. The first push makes each package private; make it public in the package's settings if it should be.`);
594
+ else
595
+ registry.push(`${repository}: set OCI_USERNAME and OCI_PASSWORD for the release workflow, as ${forge === "gitlab" ? "masked CI/CD variables" : "secrets in release.workflow.env"}, with push access to the registry.`);
596
+ }
597
+ else
598
+ notes.push(`The charts are packed into release.artifacts, and no helm target is declared: origin names no registry chant knows. Add { type: "helm", charts: [${entries.map((e) => `"artifact:${e.name}"`).join(", ")}], oci: { repository: "<registry>/<path>" } }.`);
599
+ }
600
+ // #5233: Linux packages nfpm builds, attached to the forge release.
601
+ if (facts.nfpm) {
602
+ const nf = facts.nfpm;
603
+ release.artifacts = [...(release.artifacts ?? []), { name: "packages", nfpm: nf.file === "nfpm.yaml" ? {} : { config: nf.file } }];
604
+ reasons.push(`release.artifacts: ${nf.file} packages a deb and an rpm once at the cut with nfpm, and the release records each`);
605
+ notes.push(`${nf.file} packs files the cut must build first: declare the build that writes them in release.artifacts before "packages".`);
606
+ if (!nf.version)
607
+ notes.push(`Set version: "\${CHANT_RELEASE_VERSION}" in ${nf.file}: the cut refuses a config whose packages would not carry the release's version.`);
608
+ const forgeTarget = publish.find((p) => p.type === "forge");
609
+ if (forgeTarget) {
610
+ forgeTarget.assets = [...forgeTarget.assets, "artifact:packages"];
611
+ reasons.push(`forge target: the deb and rpm packages are attached beside the other assets`);
612
+ }
613
+ else if (facts.origin) {
614
+ publish.push({ type: "forge", forge: facts.origin.kind, repo: facts.origin.repo, assets: ["artifact:packages"], notes: { generate: "forge" } });
615
+ reasons.push(`forge target: the deb and rpm packages as assets of the ${facts.origin.kind} release ${facts.origin.repo}, with generated notes`);
616
+ }
617
+ else
618
+ notes.push(`No forge release is declared for ${nf.file}'s packages: origin names no GitHub, GitLab or Forgejo repository.`);
619
+ }
620
+ // Python and Rust packages.
621
+ const versionFiles = [];
622
+ const trustedRepo = facts.origin?.repo ?? "this repository";
623
+ const trustedFor = (what) => forge === "gitlab" ? `GitLab CI/CD naming ${trustedRepo} and the top-level pipeline file .gitlab-ci.yml` : `${what} naming ${trustedRepo} and the workflow file ${workflowName}`;
624
+ const py = facts.python;
625
+ if (py?.pyproject && py.name) {
626
+ const forgejo = forge === "forgejo";
627
+ const entry = { name: "python", build: "python -m pip install build && python -m build", outputs: ["dist/*"] };
628
+ release.artifacts = [...(release.artifacts ?? []), entry];
629
+ publish.push({ type: "pypi", files: ["artifact:python"], auth: forgejo ? "token" : "trusted-publishing" });
630
+ reasons.push(`release.artifacts: ${py.name} is built once at the cut with python -m build, and the release records the sdist and wheel in dist/`);
631
+ reasons.push(`pypi target: the recorded files of ${py.name}, uploaded to PyPI ${forgejo ? "with the token in PYPI_TOKEN" : "with trusted publishing"}`);
632
+ if (py.version)
633
+ versionFiles.push("pyproject.toml");
634
+ else
635
+ notes.push("pyproject.toml has no static version (it is dynamic, or unset), so release.version does not stamp it: the build takes the version from wherever the project sets it.");
636
+ if (forgejo) {
637
+ workflow.env = { ...(workflow.env ?? {}), PYPI_TOKEN: "${{ secrets.PYPI_TOKEN }}" };
638
+ registry.push(`PyPI ${py.name}: create an API token for the project on pypi.org and store it as the secret PYPI_TOKEN; PyPI has no trusted publisher for this forge.`);
639
+ }
640
+ else {
641
+ registry.push(`PyPI ${py.name}: on pypi.org add a trusted publisher to the project's publishing settings (a pending publisher if the project does not exist yet) for ${trustedFor("GitHub Actions")}.${forge === "github" ? " A GitHub publisher can name an environment; leave it empty, since the workflow runs in none." : ""}`);
642
+ }
643
+ }
644
+ else if (py)
645
+ notes.push(`${py.name ?? "The Python package"} is tagged and not published to PyPI: ${py.pyproject ? "pyproject.toml has no [project] name" : "there is no pyproject.toml for python -m build to read"}. Add a pypi target to release.publish when it is.`);
646
+ const rs = facts.rust;
647
+ if (rs && !rs.unpublishable && (rs.name || rs.workspace)) {
648
+ publish.push({ type: "cargo" });
649
+ reasons.push(`cargo target: ${rs.name ?? "the workspace's crates"}${rs.workspace && rs.name ? " and its workspace members" : ""} published with cargo publish, in dependency order`);
650
+ if (rs.version)
651
+ versionFiles.push("Cargo.toml");
652
+ else
653
+ notes.push("Cargo.toml has no [package] or [workspace.package] version at the root, so release.version does not stamp it: add the member crates' Cargo.toml files to release.version.files.");
654
+ registry.push(`crates.io ${rs.name ?? "each crate"}: ${forge === "github" ? `add a trusted publisher to ${rs.name ? "the crate" : "each crate"} on crates.io for GitHub Actions naming ${trustedRepo} and the workflow file ${workflowName}. A crate's first version can't be published that way: publish it by hand, or store a token that may publish new crates as the secret CARGO_REGISTRY_TOKEN and set CARGO_REGISTRY_TOKEN: "\${{ secrets.CARGO_REGISTRY_TOKEN }}" in release.workflow.env.` : `create an API token that may publish ${rs.name ? "the crate" : "the crates"} and store it as the ${forge === "gitlab" ? "masked CI/CD variable" : "secret"} CARGO_REGISTRY_TOKEN${forge === "gitlab" ? "." : ", and set CARGO_REGISTRY_TOKEN: \"${{ secrets.CARGO_REGISTRY_TOKEN }}\" in release.workflow.env."}`}`);
655
+ }
656
+ else if (rs)
657
+ notes.push(`${rs.name ?? "The crate"} is tagged and not published to crates.io: ${rs.unpublishable ? "Cargo.toml sets publish = false" : "Cargo.toml has no [package] name or [workspace]"}.`);
658
+ // Maven, .NET and Ruby packages (#5232).
659
+ if (facts.registries) {
660
+ const r = planRegistryTargets(facts.registries, { forge, repo: trustedRepo, workflowName });
661
+ if (r.artifacts.length > 0)
662
+ release.artifacts = [...(release.artifacts ?? []), ...r.artifacts];
663
+ publish.push(...r.publish);
664
+ reasons.push(...r.reasons);
665
+ notes.push(...r.notes);
666
+ registry.push(...r.registry);
667
+ if (Object.keys(r.env).length > 0)
668
+ workflow.env = { ...(workflow.env ?? {}), ...r.env };
669
+ }
670
+ if (versionFiles.length > 0) {
671
+ const current = release.version ?? {};
672
+ release.version = { ...current, files: versionFiles };
673
+ reasons.push(`release.version.files: the release stamps its label into ${versionFiles.join(" and ")}, so a release needs no version commit`);
674
+ }
675
+ if (facts.go && !facts.goreleaser)
676
+ reasons.push(`Go module ${facts.go.module ?? ""}: the tag is the release the Go module proxy reads; nothing else is published`.replace(" ", " "));
677
+ if (publish.length > 0)
678
+ release.publish = publish;
679
+ else
680
+ notes.push("No publish target was found: the release records the commit and makes its tag. Add targets to release.publish as the project needs them.");
681
+ release.workflow = workflow;
682
+ reasons.push(`release.workflow: a release started by hand with its label from ${workflowFile}, which cuts a green commit and publishes it`);
683
+ if (adopted)
684
+ reasons.push(`release.workflow.file ${workflowFile}: it runs npm publish today, so the npm trusted publisher that names it keeps working; the release workflow replaces it rather than publishing from a second file`);
685
+ if (!facts.distIgnored && (images.length > 0 || facts.goreleaser || charts.length > 0 || facts.nfpm || publish.some((p) => ["pypi", "nuget", "rubygems"].includes(p.type ?? "")) || publish.some((p) => p.type === "marketplace")))
686
+ notes.push("dist/ is not in .gitignore: the publish refuses a tree with build outputs git does not ignore.");
687
+ if (forge === "gitlab")
688
+ registry.push(`GitLab: include ${workflowFile} from .gitlab-ci.yml, and store a project access token with write_repository as the masked CI/CD variable CHANT_RELEASE_TOKEN; the cut and publish jobs push with it.`);
689
+ const h = facts.tags.prefix;
690
+ const readsHistory = h !== null && (tag.legacy.includes(h) || tag.template === `${h}{version}`);
691
+ return { release, reasons, notes, registry, workflowFile, goreleaserPatch, readsHistory };
692
+ }
693
+ /** The environment a planned train is recorded for. */
694
+ export const TRAIN_ENV = "npm";
695
+ /**
696
+ * Whether the project's npm, pnpm or yarn workspaces can release as a train:
697
+ * one member per publishable package (#5154). `why` says why a project with
698
+ * several packages gets one release instead, and is null for a project with
699
+ * fewer than two.
700
+ */
701
+ export function trainFit(facts) {
702
+ const node = facts.node;
703
+ if (!node?.workspaces)
704
+ return { train: false, why: null };
705
+ const published = (p) => p.name !== null && !p.private && !p.vscode;
706
+ const packages = node.workspaces.filter(published);
707
+ const rootPublished = published(node.root);
708
+ if (packages.length + (rootPublished ? 1 : 0) < 2)
709
+ return { train: false, why: null };
710
+ if (rootPublished)
711
+ return { train: false, why: `the root package ${node.root.name} is published too, and a train releases the packages below the root` };
712
+ const ext = [node.root, ...node.workspaces].find((p) => p.vscode && !p.private && p.name);
713
+ if (ext)
714
+ return { train: false, why: `${ext.name} is a VS Code extension, and its .vsix is a file the train workflow does not hand from its cut job to its publish job` };
715
+ if (facts.goreleaser)
716
+ return { train: false, why: `${facts.goreleaser.file} builds files at the cut, which the train workflow does not hand between its jobs` };
717
+ if (facts.dockerfiles.length > 0)
718
+ return { train: false, why: `${facts.dockerfiles[0]} is an image built at the cut, which the train workflow does not hand between its jobs` };
719
+ if ((facts.charts?.length ?? 0) > 0)
720
+ return { train: false, why: `${facts.charts[0].dir}/Chart.yaml is a chart packed at the cut, which the train workflow does not hand between its jobs` };
721
+ if (facts.nfpm)
722
+ return { train: false, why: `${facts.nfpm.file} packages files at the cut, which the train workflow does not hand between its jobs` };
723
+ if (facts.python?.pyproject && facts.python.name)
724
+ return { train: false, why: "pyproject.toml is built at the cut, which the train workflow does not hand between its jobs" };
725
+ if (facts.rust && !facts.rust.unpublishable && (facts.rust.name || facts.rust.workspace))
726
+ return { train: false, why: "Cargo.toml's crates publish beside the npm packages, and a train releases npm packages" };
727
+ if (facts.workflowForge === "gitlab")
728
+ return { train: false, why: "the train workflow renders for GitHub and Forgejo, and this repository runs GitLab CI" };
729
+ return { train: true };
730
+ }
731
+ /** A workspace member name (lowercase letters, digits and dashes, at most 40) for a package. */
732
+ export function memberNameOf(pkg) {
733
+ const clean = (s) => s.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/-+$/, "").slice(0, 40).replace(/-+$/, "");
734
+ return clean(pkg.name?.replace(/^@[^/]+\//, "") ?? "") || clean(posix.basename(pkg.dir)) || "package";
735
+ }
736
+ /** The tag prefixes of a history that name one package's releases: `core-v`, `core/v`, `@acme/core@`, `packages/core/v`. */
737
+ function ownPrefixes(h, pkg, member) {
738
+ const names = new Set([pkg.name, pkg.name?.replace(/^@[^/]+\//, ""), member, pkg.dir, posix.basename(pkg.dir)].filter((n) => !!n));
739
+ return [h.prefix, ...h.others.map((o) => o.prefix)].filter((p) => p !== null && p !== "" && names.has(p.replace(/[/@_-]v?$/, "")));
740
+ }
741
+ /**
742
+ * Plan a train for a project {@link trainFit} accepts: a member per
743
+ * publishable workspace package, each stamping and publishing its own
744
+ * package, and the root's `release.train` with a dispatched workflow.
745
+ */
746
+ export function planTrain(facts, opts) {
747
+ const node = facts.node;
748
+ const reasons = [];
749
+ const notes = [];
750
+ const registry = [];
751
+ const forge = facts.workflowForge;
752
+ const { file: workflowFile, adopted } = releaseWorkflowFile(facts, true, notes);
753
+ const workflowName = posix.basename(workflowFile);
754
+ const env = TRAIN_ENV;
755
+ const named = node.workspaces.filter((p) => p.name);
756
+ const packages = dependencyOrder(named.filter((p) => !p.private && !p.vscode));
757
+ const skipped = named.filter((p) => p.private);
758
+ const names = new Set(packages.map((p) => p.name));
759
+ const greenReasons = [];
760
+ const green = greenOf(facts, greenReasons, notes);
761
+ // Member names, unique.
762
+ const used = new Set();
763
+ const memberNames = packages.map((p) => {
764
+ const base = memberNameOf(p);
765
+ let name = base;
766
+ for (let i = 2; used.has(name); i++)
767
+ name = `${base.slice(0, 38)}-${i}`;
768
+ used.add(name);
769
+ return name;
770
+ });
771
+ // Tags: a package's own history keeps its prefix; tags shared by every package are the root's legacy tags.
772
+ const h = facts.tags;
773
+ const claimed = new Set();
774
+ const members = packages.map((p, i) => {
775
+ const name = memberNames[i];
776
+ const own = ownPrefixes(h, p, name);
777
+ for (const o of own)
778
+ claimed.add(o);
779
+ const template = own.find(templatePrefix);
780
+ const release = { tag: template ? `${template}{version}` : "{member}/v{version}" };
781
+ const legacy = own.filter((o) => o !== template);
782
+ if (legacy.length > 0)
783
+ release.legacyTags = legacy;
784
+ release.green = green;
785
+ const internal = p.deps.some((d) => names.has(d) && d !== p.name);
786
+ release.version = internal ? { packages: ["."], ranges: "train" } : { packages: ["."] };
787
+ const target = { type: "npm", packages: ["."] };
788
+ if (p.name.startsWith("@") && p.access === null)
789
+ target.access = "public";
790
+ release.publish = [target];
791
+ return { name, dir: p.dir, package: p.name, release };
792
+ });
793
+ const shared = [h.prefix, ...h.others.map((o) => o.prefix)].filter((p) => p !== null && p !== "" && !claimed.has(p));
794
+ const release = { train: shared.length > 0 ? { env, first: "together" } : { env } };
795
+ reasons.push(`release.train: ${packages.length} packages, each a workspace member released at its own version; chant workspace train cut ${env} cuts every member that changed since its last release, and the train publishes them in dependency order${shared.length > 0 ? `. first "together": the packages have shared ${shared.map((p) => `${p}<version>`).join(" and ")} releases, so the first train gives every package one label past the highest version any has, and each later train labels each on its own` : ""}`);
796
+ if (shared.length > 0) {
797
+ release.legacyTags = shared;
798
+ reasons.push(`release.legacyTags ${JSON.stringify(shared)}: chant release changed reads the newest ${shared.map((p) => `${p}<version>`).join(" or ")} tag as every package's last release until the train has cut one`);
799
+ }
800
+ release.green = green;
801
+ reasons.push(...greenReasons);
802
+ const workflow = { trigger: "dispatch" };
803
+ if (adopted)
804
+ workflow.file = workflowFile;
805
+ nodeWorkflow(node, opts, workflow, reasons);
806
+ release.workflow = workflow;
807
+ reasons.push(`release.workflow: ${workflowFile}, started by hand with the levels, cuts the train from a green commit and publishes it`);
808
+ if (adopted)
809
+ reasons.push(`release.workflow.file ${workflowFile}: it runs npm publish today, so the npm trusted publishers that name it keep working; the train workflow replaces it rather than publishing from a second file`);
810
+ for (const m of members) {
811
+ const tag = m.release.tag;
812
+ const ranges = m.release.version.ranges;
813
+ const access = m.release.publish[0].access;
814
+ reasons.push(`${m.dir}/chant.config.ts, member ${m.name}: ${m.package} stamped with its label and published to npm${access ? ' with access "public"' : ""}, tagged ${tag}${ranges ? `; ranges "train", so its range on a sibling names the version the train gives it` : ""}${m.release.legacyTags ? `; its ${m.release.legacyTags.map((p) => `${p}<version>`).join(" and ")} tags read as earlier releases` : ""}`);
815
+ }
816
+ if (skipped.length > 0)
817
+ notes.push(`Not published, being private: ${skipped.map((p) => p.name).join(", ")}. The train's publish job builds ${skipped.length === 1 ? "it" : "them"} when a member needs ${skipped.length === 1 ? "it" : "them"}.`);
818
+ const packed = packages.filter((p) => !p.packList);
819
+ if (packed.length > 0)
820
+ notes.push(`npm packs a package's chant.config.ts with it unless package.json files or an .npmignore leaves it out: ${packed.map((p) => p.name).join(", ")} ${packed.length === 1 ? "has" : "have"} neither.`);
821
+ const repo = facts.origin?.repo ?? "this repository";
822
+ for (const m of members) {
823
+ registry.push(adopted
824
+ ? `npm ${m.package}: keep the trusted publisher on npmjs.com that names ${repo} and the workflow file ${workflowName}, or add one naming them if the package has none, and allow npm dist-tag on it, since the reveal moves latest. If ${m.package} is not on npm yet, publish its first version by hand from ${m.dir} (npm publish) so it has settings; the train labels the next past it.`
825
+ : `npm ${m.package}: on npmjs.com, add a trusted publisher for ${forge === "github" ? "GitHub Actions" : "this forge"} naming ${repo} and the workflow file ${workflowName}, and allow npm dist-tag, since the reveal moves latest. Every package names the same file. If ${m.package} is not on npm yet, publish its first version by hand from ${m.dir} (npm publish) so it has settings; the train labels the next past it.`);
826
+ }
827
+ const workspaceName = memberNameOf({ name: facts.origin?.repo.split("/").pop() ?? node.root.name ?? null, dir: facts.path ?? "workspace" }) || "workspace";
828
+ return { release, members, workspaceName, reasons, notes, registry, workflowFile, env };
829
+ }
830
+ const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
831
+ /** A value as TypeScript source, objects and arrays on one line when short. */
832
+ export function toSource(value, indent, step = " ") {
833
+ if (value === null || typeof value !== "object")
834
+ return JSON.stringify(value);
835
+ const inner = indent + step;
836
+ if (Array.isArray(value)) {
837
+ const items = value.map((v) => toSource(v, inner, step));
838
+ const flat = `[${items.join(", ")}]`;
839
+ return flat.length + indent.length <= 100 && !flat.includes("\n") ? flat : `[\n${items.map((i) => `${inner}${i},`).join("\n")}\n${indent}]`;
840
+ }
841
+ const entries = Object.entries(value).map(([k, v]) => `${IDENT.test(k) ? k : JSON.stringify(k)}: ${toSource(v, inner, step)}`);
842
+ if (entries.length === 0)
843
+ return "{}";
844
+ const flat = `{ ${entries.join(", ")} }`;
845
+ return flat.length + indent.length <= 100 && !flat.includes("\n") ? flat : `{\n${entries.map((e) => `${inner}${e},`).join("\n")}\n${indent}}`;
846
+ }
847
+ /** The `release:` property as source, at `indent`, expanded one level so each field is on its own line. */
848
+ export function releaseBlockSource(release, indent, step = " ") {
849
+ const inner = indent + step;
850
+ return `release: {\n${Object.entries(release).map(([k, v]) => `${inner}${k}: ${toSource(v, inner, step)},`).join("\n")}\n${indent}}`;
851
+ }
852
+ /** A config made of the release block alone. */
853
+ export function newConfigSource(release) {
854
+ return `// chant.config.ts: what chant release cuts and publishes. See https://intentius.io/chant/cli/release/\nexport default {\n ${releaseBlockSource(release, " ")},\n};\n`;
855
+ }
856
+ /**
857
+ * Walk TypeScript source from `from`, skipping strings, template literals and
858
+ * comments, and call `visit` at each other character with the brace depth
859
+ * relative to `from`. Stops when `visit` returns true.
860
+ */
861
+ function scan(src, from, visit) {
862
+ let depth = 0;
863
+ for (let i = from; i < src.length; i++) {
864
+ const c = src[i];
865
+ const n = src[i + 1];
866
+ if (c === "/" && n === "/") {
867
+ i = src.indexOf("\n", i);
868
+ if (i < 0)
869
+ return;
870
+ continue;
871
+ }
872
+ if (c === "/" && n === "*") {
873
+ i = src.indexOf("*/", i + 2);
874
+ if (i < 0)
875
+ return;
876
+ i++;
877
+ continue;
878
+ }
879
+ if (c === '"' || c === "'" || c === "`") {
880
+ for (i++; i < src.length && src[i] !== c; i++)
881
+ if (src[i] === "\\")
882
+ i++;
883
+ // The closing quote is visited, so a caller sees where the string ends.
884
+ if (i < src.length && visit(i, depth))
885
+ return;
886
+ continue;
887
+ }
888
+ if (c === "{" || c === "[" || c === "(")
889
+ depth++;
890
+ if (visit(i, depth))
891
+ return;
892
+ if (c === "}" || c === "]" || c === ")")
893
+ depth--;
894
+ }
895
+ }
896
+ /** Where the object a config's default export is opens, or -1. */
897
+ function defaultObjectStart(src) {
898
+ let at = -1;
899
+ scan(src, 0, (i, depth) => {
900
+ if (depth === 0 && src.startsWith("export default", i)) {
901
+ at = i + "export default".length;
902
+ return true;
903
+ }
904
+ return false;
905
+ });
906
+ if (at < 0)
907
+ return -1;
908
+ const rest = src.slice(at);
909
+ const direct = /^\s*(?:(?:[A-Za-z_$][\w$.]*\s*(?:<[^>]*>)?\s*)?\(\s*)?\{/.exec(rest);
910
+ if (direct)
911
+ return at + direct[0].length - 1;
912
+ const ident = /^\s*([A-Za-z_$][\w$]*)\s*(?:;|$|\n|satisfies|as)/.exec(rest);
913
+ if (!ident)
914
+ return -1;
915
+ const decl = new RegExp(`(?:const|let|var)\\s+${ident[1]}\\s*(?::[^=]+)?=\\s*(?:[A-Za-z_$][\\w$.]*\\s*\\(\\s*)?\\{`).exec(src);
916
+ return decl ? decl.index + decl[0].length - 1 : -1;
917
+ }
918
+ /** The end (exclusive) of the bracketed value that opens at `open`. */
919
+ function closeOf(src, open) {
920
+ let end = -1;
921
+ scan(src, open, (i, depth) => {
922
+ if (depth === 1 && i > open && "}])".includes(src[i])) {
923
+ end = i + 1;
924
+ return true;
925
+ }
926
+ return false;
927
+ });
928
+ return end;
929
+ }
930
+ /**
931
+ * Write `release` into a chant.config.ts's default export: before the
932
+ * object's closing brace, or in place of an existing `release` property
933
+ * when `force`. Throws {@link ReleaseInitError}: `release-init-release-exists`
934
+ * for a `release` property without `force`, `release-init-config-unreadable`
935
+ * when the default export is not an object literal this can find.
936
+ */
937
+ export function insertReleaseBlock(src, release, force) {
938
+ const open = defaultObjectStart(src);
939
+ const close = open < 0 ? -1 : closeOf(src, open);
940
+ if (open < 0 || close < 0) {
941
+ throw new ReleaseInitError("release-init-config-unreadable", "chant.config.ts has no default export of an object literal to add release to", "Add the release block shown here to the config by hand.");
942
+ }
943
+ // The indentation of the object's properties.
944
+ const firstProp = /\n([ \t]+)\S/.exec(src.slice(open, close));
945
+ const lineStart = src.lastIndexOf("\n", open) + 1;
946
+ const outer = /^[ \t]*/.exec(src.slice(lineStart))[0];
947
+ const indent = firstProp ? firstProp[1] : `${outer} `;
948
+ const step = indent.length > outer.length ? indent.slice(outer.length) : " ";
949
+ const block = releaseBlockSource(release, indent, step);
950
+ let keyAt = -1;
951
+ scan(src, open, (i, depth) => {
952
+ if (i >= close)
953
+ return true;
954
+ if (depth === 1 && /[\s{,]/.test(src[i - 1] ?? "") && /^(?:release|"release"|'release')\s*:/.test(src.slice(i))) {
955
+ keyAt = i;
956
+ return true;
957
+ }
958
+ return false;
959
+ });
960
+ if (keyAt >= 0) {
961
+ if (!force)
962
+ throw new ReleaseInitError("release-init-release-exists", "chant.config.ts already has a release block", "Run again with --force to replace it, or add the fields shown here to it by hand.");
963
+ const valueAt = keyAt + /^[^:]*:\s*/.exec(src.slice(keyAt))[0].length;
964
+ if (src[valueAt] !== "{")
965
+ throw new ReleaseInitError("release-init-config-unreadable", "the release property in chant.config.ts is not an object literal", "Replace it with the release block shown here by hand.");
966
+ const end = closeOf(src, valueAt);
967
+ return src.slice(0, keyAt) + block + src.slice(end);
968
+ }
969
+ // Before the closing brace, after the last property, its comma, and a comment on its line.
970
+ const brace = close - 1;
971
+ let last = open;
972
+ scan(src, open, (i) => {
973
+ if (i >= brace)
974
+ return true;
975
+ if (!/\s/.test(src[i]))
976
+ last = i;
977
+ return false;
978
+ });
979
+ const needsComma = last !== open && src[last] !== ",";
980
+ const lineEnd = src.indexOf("\n", last);
981
+ const tail = lineEnd >= 0 && lineEnd < brace ? lineEnd : last + 1;
982
+ const head = src.slice(0, last + 1) + (needsComma ? "," : "") + src.slice(last + 1, tail).replace(/\s+$/, "");
983
+ return `${head}\n${indent}${block},\n${outer}${src.slice(brace)}`;
984
+ }