@reelout/core 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/HookDispatcher-Di79rwtu.js +236 -0
  2. package/dist/HookDispatcher-Di79rwtu.js.map +1 -0
  3. package/dist/analyzer.js +12 -3
  4. package/dist/analyzer.js.map +1 -1
  5. package/dist/buildChangelog-Cxm9_lq2.js +187 -0
  6. package/dist/buildChangelog-Cxm9_lq2.js.map +1 -0
  7. package/dist/buildReleaseNotes-S6HcEQnE.js +141 -0
  8. package/dist/buildReleaseNotes-S6HcEQnE.js.map +1 -0
  9. package/dist/builder.js +14 -6
  10. package/dist/builder.js.map +1 -1
  11. package/dist/changelog.js +17 -6
  12. package/dist/changelog.js.map +1 -1
  13. package/dist/index.js +1201 -8
  14. package/dist/index.js.map +1 -1
  15. package/dist/package-Bczytil1.js +884 -0
  16. package/dist/package-Bczytil1.js.map +1 -0
  17. package/dist/propagateDependencyUpdates-QWn0H1qa.js +306 -0
  18. package/dist/propagateDependencyUpdates-QWn0H1qa.js.map +1 -0
  19. package/dist/readPackageHistory-CN5nqMcE.js +133 -0
  20. package/dist/readPackageHistory-CN5nqMcE.js.map +1 -0
  21. package/dist/resolvePackageTag-cwqG1GGt.js +30 -0
  22. package/dist/resolvePackageTag-cwqG1GGt.js.map +1 -0
  23. package/dist/types.js +0 -1
  24. package/package.json +15 -3
  25. package/src/analyzer.ts +7 -2
  26. package/src/builder.ts +12 -3
  27. package/src/changelog.ts +17 -6
  28. package/src/config/resolvePlugin.ts +1 -1
  29. package/src/git/commit/getParsedGitCommit.ts +4 -1
  30. package/src/git/commit/parseGitCommit.ts +27 -2
  31. package/src/git/commit/parseGitPrettyFormat.ts +4 -1
  32. package/src/git/history/expandGitHistory.ts +17 -3
  33. package/src/git/history/readParsedGitHistory.ts +8 -2
  34. package/src/git/repository/isGitShallowRepository.ts +2 -1
  35. package/src/git/tag/ensureGitTag.ts +35 -3
  36. package/src/plugin/createHostReleasePlugin.ts +255 -0
  37. package/src/plugin/index.ts +1 -0
  38. package/src/util/execCommand.ts +9 -0
  39. package/src/util/formatFile.ts +12 -3
  40. package/src/util/interpolate.ts +5 -3
  41. package/src/workflow/analysis/propagateDependencyUpdates.ts +1 -0
  42. package/src/workflow/changelog/buildChangelog.ts +27 -4
  43. package/src/workflow/changelog/buildReleaseNotes.ts +1 -1
  44. package/src/workflow/changelog/index.ts +0 -1
  45. package/src/workflow/changelog/prependChangelog.ts +5 -2
  46. package/src/workflow/changelog/writeChangelog.ts +5 -2
  47. package/src/workflow/commit/generateReleaseCommitMessage.ts +1 -1
  48. package/src/workflow/discovery/discoverPackageTag.ts +5 -2
  49. package/src/workflow/discovery/resolvePackageStableTag.ts +12 -7
  50. package/src/workflow/discovery/resolvePackageTag.ts +5 -2
  51. package/src/workflow/discovery/sortPackages.ts +5 -4
  52. package/src/workflow/discovery/verifyPackageTag.ts +6 -3
  53. package/src/workflow/report/printReleaseReport.ts +6 -1
  54. package/src/workflow/version/bumpVersion.ts +0 -1
  55. package/src/workflow/version/index.ts +0 -1
  56. package/dist/formatError-BMsun8Wi.js +0 -22
  57. package/dist/formatError-BMsun8Wi.js.map +0 -1
  58. package/dist/types-la_KkjCS.js +0 -1
  59. package/dist/workflow-Cqg6rLVB.js +0 -2936
  60. package/dist/workflow-Cqg6rLVB.js.map +0 -1
  61. package/src/workflow/changelog/extractPreviousVersion.ts +0 -77
  62. package/src/workflow/version/promotePrereleaseVersions.ts +0 -51
package/dist/index.js CHANGED
@@ -1,8 +1,155 @@
1
- import { $ as isGitShallowRepository, A as getGitTagMessage, At as execGit, B as getGitRemote, Bt as SEMVER_REGEX, C as iterateChangelogVersions, Ct as readJson, D as isGitTagExact, Dt as isTruthyString, E as buildDependencyGraph, Et as isClass, F as deleteGitTag, Ft as ALL_FILES, G as readGitHistory, Gt as pickPriorityReleaseType, H as getGitConfigValue, Ht as isStableVersion, I as createGitTag, It as DEFAULT_CHANGELOG_FILE, J as detectGitRelationship, Jt as extractVersionQualifier, K as mergeGitHistory, Kt as deriveCommitReleaseType, L as readGitFile, Lt as DEV_NULL, M as generateGitTagName, Mt as compact, N as ensureGitTag, Nt as isDefined, O as isGitTagConnected, Ot as interpolate, P as isGitTagPresent, Pt as buildTrailerPattern, Q as withShallowLock, R as resolveGitRepository, Rt as GIT_TRAILER_RELEASE_AGENT, S as extractLatestVersion, St as unique, T as extractPlainText, Tt as isGitHubActions, U as restoreFullGitHistory, Ut as isSameReleaseCycle, V as ensureGitUserConfig, Vt as promotePrereleaseVersions, W as readParsedGitHistory, Wt as deriveReleaseType, X as resolveGitRevision, Y as expandGitHistory, Z as isGitAncestor, _ as resolvePackageTag, _t as isSemVerGitTag, a as appendReleaseReportSummary, at as parseGitPrettyFormat, b as discoverPackageTag, bt as createPlugin, c as generateReleaseCommitMessage, ct as extractMentions, d as prependChangelog, dt as deriveTransitionReleases, et as countGitHistory, f as extractPreviousVersion, ft as deriveChangeReleases, g as propagateDependencyUpdates, gt as sanitizePrereleaseLabel, h as readPackageHistory, ht as resolveReleaseChannel, i as generateReleaseReport, it as GIT_PRETTY_FORMAT, j as getCurrentGitTag, jt as execCommand, k as getLatestGitTag, kt as formatFile, lt as createGitCommit, m as buildChangelog, mt as resolveVersionQualifier, n as printReleaseReportAnnotation, nt as getParsedGitCommit, o as HookDispatcher, ot as parseGitCommit, p as buildReleaseNotes, pt as packageContainsCommit, q as GIT_REL_FLAGS, qt as bumpVersion, r as printReleaseReport, rt as GIT_PRETTY_FIELD_SEPARATOR, s as Priority, st as TTLCache, t as executeReleaseWorkflow, tt as getCurrentGitCommit, u as writeChangelog, ut as getCurrentGitBranch, v as resolvePackageStableTag, vt as isSemVer, w as extractSemVer, wt as isMatch, x as verifyPackageTag, xt as writeJson, y as filterPackages, yt as findReleaseRule, z as pushGitChanges, zt as RELEASE_HOOK_NAMES } from "./workflow-Cqg6rLVB.js";
2
- import { t as formatError } from "./formatError-BMsun8Wi.js";
1
+ import { a as extractVersionQualifier, i as unique, n as readParsedGitHistory, r as readGitHistory, t as readPackageHistory } from "./readPackageHistory-CN5nqMcE.js";
2
+ import { i as bumpVersion, n as resolvePackageStableTag, r as isSameReleaseCycle, t as buildReleaseNotes } from "./buildReleaseNotes-S6HcEQnE.js";
3
+ import { a as formatFile, i as extractPlainText, n as iterateChangelogVersions, o as compact, r as extractSemVer, s as isDefined, t as buildChangelog } from "./buildChangelog-Cxm9_lq2.js";
4
+ import { A as DEV_NULL, C as isMatch, D as buildTrailerPattern, E as execCommand, M as RELEASE_HOOK_NAMES, N as SEMVER_REGEX, O as ALL_FILES, S as packageContainsCommit, T as execGit, _ as GIT_PRETTY_FORMAT, a as generateGitTagName, b as TTLCache, c as deleteGitTag, d as isGitAncestor, f as withShallowLock, g as GIT_PRETTY_FIELD_SEPARATOR, h as getParsedGitCommit, i as getGitTagMessage, j as GIT_TRAILER_RELEASE_AGENT, k as DEFAULT_CHANGELOG_FILE, l as expandGitHistory, m as countGitHistory, n as verifyPackageTag, o as ensureGitTag, p as isGitShallowRepository, r as isGitTagConnected, s as isGitTagPresent, t as version, u as resolveGitRevision, v as parseGitPrettyFormat, w as formatError, x as extractMentions, y as parseGitCommit } from "./package-Bczytil1.js";
5
+ import { a as detectGitRelationship, c as deriveReleaseType, i as GIT_REL_FLAGS, l as pickPriorityReleaseType, n as buildDependencyGraph, o as deriveTransitionReleases, r as mergeGitHistory, s as deriveChangeReleases, t as propagateDependencyUpdates, u as deriveCommitReleaseType } from "./propagateDependencyUpdates-QWn0H1qa.js";
6
+ import { a as discoverPackageTag, i as prependChangelog, n as Priority, o as extractLatestVersion, r as writeChangelog, s as readGitFile, t as HookDispatcher } from "./HookDispatcher-Di79rwtu.js";
7
+ import { t as resolvePackageTag } from "./resolvePackageTag-cwqG1GGt.js";
8
+ import "./types.js";
3
9
  import { createRequire } from "node:module";
10
+ import semver from "semver";
11
+ import { colors } from "consola/utils";
12
+ import fs from "node:fs/promises";
4
13
  import path from "node:path";
5
14
  import { pathToFileURL } from "node:url";
15
+ import GitHost from "hosted-git-info";
16
+ import { appendFileSync } from "node:fs";
17
+ // src/workflow/version/isStableVersion.ts
18
+ /**
19
+ * Determine whether a version string represents a stable SemVer release.
20
+ *
21
+ * A version is considered stable when:
22
+ * - It is a valid SemVer string.
23
+ * - Its major version is greater than 0 (not 0.x.x).
24
+ * - It contains no prerelease identifiers (no `-alpha`, `-beta`, `-rc`, etc.).
25
+ *
26
+ * Build metadata (the `+` suffix) does not affect stability.
27
+ *
28
+ * @param version Semantic version string to check
29
+ * @returns `true` if `version` is a stable SemVer; otherwise `false`
30
+ * @throws If `version` is not a valid SemVer string
31
+ */
32
+ function isStableVersion(version) {
33
+ const parsed = semver.parse(version);
34
+ if (!parsed) throw new Error(`The version "${colors.bold(version)}" is not a valid SemVer.`);
35
+ return parsed.major > 0 && parsed.prerelease.length === 0;
36
+ }
37
+ // src/util/interpolate.ts
38
+ var BACKSLASH = "\\";
39
+ var LEFT_BRACE = "{";
40
+ var RIGHT_BRACE = "}";
41
+ var DOT = ".";
42
+ var ESCAPE_CHARS = [
43
+ BACKSLASH,
44
+ LEFT_BRACE,
45
+ RIGHT_BRACE
46
+ ];
47
+ var BANNED_KEYS = [
48
+ "__proto__",
49
+ "constructor",
50
+ "prototype"
51
+ ];
52
+ /**
53
+ * Interpolate placeholders in `template` using values from `data`.
54
+ *
55
+ * - Placeholders use `{path.to.value}` (dot notation).
56
+ * - Backslash escapes are supported for `{`, `}`, `\`, and `.` inside tokens.
57
+ * - Tokens that reference banned keys (`__proto__`, `constructor`, `prototype`)
58
+ * are left unexpanded to avoid prototype pollution.
59
+ * - Only own properties are followed when resolving paths; when any step is
60
+ * missing, the token is preserved with its escape sequences already
61
+ * resolved, so an unresolved `{a\.b}` renders as `{a.b}`.
62
+ * - Resolved non-object, non-null values are stringified and inserted.
63
+ * - Unclosed tokens keep their opening brace and resolved body; a trailing
64
+ * backslash is emitted as-is.
65
+ *
66
+ * @param template Template string containing placeholders like `{user.name}`
67
+ * @param data Object used to resolve placeholder paths
68
+ * @returns The template with placeholders replaced by corresponding values
69
+ */
70
+ function interpolate(template, data) {
71
+ let result = "";
72
+ let i = 0;
73
+ let char;
74
+ let nextChar;
75
+ while (char = template[i]) if (char === BACKSLASH) {
76
+ nextChar = template[i + 1];
77
+ if (nextChar !== void 0 && ESCAPE_CHARS.includes(nextChar)) {
78
+ result += nextChar;
79
+ i += 2;
80
+ } else {
81
+ result += char;
82
+ i += 1;
83
+ }
84
+ } else if (char === LEFT_BRACE) {
85
+ const keys = [];
86
+ let key = "";
87
+ let token = "";
88
+ let closed = false;
89
+ i += 1;
90
+ while (char = template[i]) {
91
+ if (char === RIGHT_BRACE) {
92
+ closed = true;
93
+ keys.push(key);
94
+ i += 1;
95
+ break;
96
+ }
97
+ if (char === BACKSLASH) {
98
+ nextChar = template[i + 1];
99
+ if (nextChar !== void 0 && [...ESCAPE_CHARS, DOT].includes(nextChar)) {
100
+ key += nextChar;
101
+ token += nextChar;
102
+ i += 2;
103
+ } else {
104
+ key += char;
105
+ token += char;
106
+ i += 1;
107
+ }
108
+ } else if (char === DOT) {
109
+ keys.push(key);
110
+ key = "";
111
+ token += char;
112
+ i += 1;
113
+ } else {
114
+ key += char;
115
+ token += char;
116
+ i += 1;
117
+ }
118
+ }
119
+ if (closed) {
120
+ let value = data;
121
+ for (const key of keys) {
122
+ const isSafeKey = !BANNED_KEYS.includes(key);
123
+ if (value !== null && typeof value === "object" && Object.hasOwn(value, key) && isSafeKey) value = value[key];
124
+ else {
125
+ value = void 0;
126
+ break;
127
+ }
128
+ }
129
+ if (value == null || typeof value === "object") result += LEFT_BRACE + token + RIGHT_BRACE;
130
+ else result += String(value);
131
+ } else result += LEFT_BRACE + token;
132
+ } else {
133
+ result += char;
134
+ i += 1;
135
+ }
136
+ return result;
137
+ }
138
+ // src/util/isTruthyString.ts
139
+ /**
140
+ * Determine whether a string value represents a truthy boolean.
141
+ *
142
+ * Trims leading and trailing whitespace and coerces the target string to
143
+ * lowercase. Evaluates the string as truthy if it equals `'true'` or `'1'`.
144
+ *
145
+ * @param value The raw string to evaluate
146
+ * @returns `true` if `value` normalizes to `'true'` or `'1'`, otherwise `false`
147
+ */
148
+ function isTruthyString(value) {
149
+ if (!value) return false;
150
+ const normalized = value.toLowerCase().trim();
151
+ return normalized === "true" || normalized === "1";
152
+ }
6
153
  // src/util/isCI.ts
7
154
  /**
8
155
  * Determine whether the current process is running in a CI environment.
@@ -17,6 +164,42 @@ import { pathToFileURL } from "node:url";
17
164
  function isCI(env) {
18
165
  return isTruthyString(env.CI);
19
166
  }
167
+ // src/util/isClass.ts
168
+ /**
169
+ * Determine whether a given value is a constructible class.
170
+ *
171
+ * Verifies that the input is a function with a non-writable prototype, can
172
+ * be successfully invoked via `Reflect.construct`, and matches ES6 class
173
+ * syntax.
174
+ *
175
+ * @param func The unknown value to inspect
176
+ * @returns True if the value is a class, false otherwise
177
+ */
178
+ function isClass(func) {
179
+ if (typeof func !== "function") return false;
180
+ try {
181
+ Reflect.construct(Object, [], func);
182
+ } catch {
183
+ return false;
184
+ }
185
+ const descriptor = Object.getOwnPropertyDescriptor(func, "prototype");
186
+ if (!descriptor || descriptor.writable) return false;
187
+ return /^class\s/.test(Function.prototype.toString.call(func));
188
+ }
189
+ // src/util/isGitHubActions.ts
190
+ /**
191
+ * Determine whether the current process runs on a GitHub Actions runner.
192
+ *
193
+ * Checks if the `GITHUB_ACTIONS` environment variable is set to a truthy
194
+ * value. Gates GitHub Actions-specific reporting such as job summaries and
195
+ * annotations.
196
+ *
197
+ * @param env Readonly process environment variables object
198
+ * @returns `true` if `env.GITHUB_ACTIONS` normalizes to a truthy string, otherwise `false`
199
+ */
200
+ function isGitHubActions(env) {
201
+ return isTruthyString(env.GITHUB_ACTIONS);
202
+ }
20
203
  // src/util/isQuietEnvironment.ts
21
204
  /**
22
205
  * Determine whether the current run should stay quiet about verbose output.
@@ -42,6 +225,116 @@ function isQuietEnvironment(context) {
42
225
  if (isCI(context.env)) return false;
43
226
  return context.stdout?.isTTY !== true;
44
227
  }
228
+ // src/util/readJson.ts
229
+ /**
230
+ * Read and parse a JSON file.
231
+ *
232
+ * Throws a descriptive error when the file cannot be read or parsed, or when
233
+ * the parsed value is not an object.
234
+ *
235
+ * @param filePath Path to the JSON file
236
+ * @returns Parsed JSON object
237
+ * @throws If the file cannot be read, parsed, or is not an object
238
+ */
239
+ async function readJson(filePath) {
240
+ let content;
241
+ try {
242
+ content = await fs.readFile(filePath, "utf-8");
243
+ } catch (err) {
244
+ throw new Error(`JSON file at "${colors.bold(filePath)}" could not be read.`, { cause: err });
245
+ }
246
+ let json;
247
+ try {
248
+ json = JSON.parse(content);
249
+ } catch (err) {
250
+ throw new Error(`JSON file at "${colors.bold(filePath)}" could not be parsed.`, { cause: err });
251
+ }
252
+ if (typeof json !== "object" || json === null) throw new Error(`JSON file at "${colors.bold(filePath)}" does not contain a valid object.`);
253
+ return json;
254
+ }
255
+ // src/util/writeJson.ts
256
+ /**
257
+ * Write a JSON `payload` to `filePath`, formatting the content first.
258
+ *
259
+ * Ensures the directory exists and writes the formatted JSON.
260
+ *
261
+ * @param filePath Path to write the JSON file
262
+ * @param payload JSON-serializable object to write
263
+ * @returns Promise that resolves when the file is written
264
+ */
265
+ async function writeJson(filePath, payload) {
266
+ let content = JSON.stringify(payload, null, 2);
267
+ content = await formatFile(filePath, content);
268
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
269
+ await fs.writeFile(filePath, content);
270
+ }
271
+ // src/config/createPlugin.ts
272
+ /**
273
+ * Instantiate or invoke a plugin factory to produce a release plugin instance.
274
+ *
275
+ * Accepts class constructors, factory functions, tuple configurations, or
276
+ * existing plugin objects. Instantiates classes using `new` or invokes factory
277
+ * functions with options, validating that the resulting object satisfies the
278
+ * plugin structure.
279
+ *
280
+ * @param plugin A plugin constructor, factory function, tuple, or object
281
+ * @returns A validated release plugin instance or null
282
+ */
283
+ async function createPlugin(plugin) {
284
+ let options;
285
+ if (Array.isArray(plugin)) [plugin, options] = plugin;
286
+ if (typeof plugin === "function") plugin = isClass(plugin) ? new plugin(options) : await plugin(options);
287
+ if (plugin != null && typeof plugin === "object" && Object.hasOwn(plugin, "name") && typeof plugin.name === "string") return plugin;
288
+ return null;
289
+ }
290
+ // src/config/findReleaseRule.ts
291
+ /**
292
+ * Find the first release rule matching a release reference.
293
+ *
294
+ * Matches rules sequentially against the reference type and pattern.
295
+ *
296
+ * @param ref Release reference object
297
+ * @param rules Array of release rules to match against
298
+ * @returns The first matching release rule or `undefined`
299
+ */
300
+ function findReleaseRule(ref, rules) {
301
+ return rules.find((rule) => {
302
+ return (rule.type == null || rule.type === ref.type) && isMatch(ref.name, rule.pattern);
303
+ });
304
+ }
305
+ // src/config/isSemVer.ts
306
+ /**
307
+ * Determine whether a value is a valid Semantic Versioning string.
308
+ *
309
+ * Rejects non-string values, leading or trailing whitespace, and leading `v`
310
+ * prefixes. Validates the candidate string using `semver.parse`.
311
+ *
312
+ * @param version Candidate value to evaluate for SemVer compliance
313
+ * @returns `true` if `version` is a valid SemVer string, or `false` otherwise
314
+ */
315
+ function isSemVer(version) {
316
+ if (typeof version !== "string") return false;
317
+ if (version !== version.trim()) return false;
318
+ if (version.startsWith("v")) return false;
319
+ return semver.parse(version) != null;
320
+ }
321
+ // src/config/isSemVerGitTag.ts
322
+ /**
323
+ * Determine whether a tag string is a valid SemVer-style Git tag.
324
+ *
325
+ * Anchors `SEMVER_REGEX.source` for full-string matching and applies the
326
+ * repository's Git-tag acceptance rules.
327
+ *
328
+ * @param tag Tag string to validate
329
+ * @returns `true` if `tag` is accepted as a SemVer-style Git tag; otherwise `false`
330
+ */
331
+ function isSemVerGitTag(tag) {
332
+ const match = new RegExp(`^${SEMVER_REGEX.source}$`).exec(tag);
333
+ if (!match) return false;
334
+ const isScopedPackage = Boolean(match[1]);
335
+ const hasVersionPrefix = tag.startsWith("v");
336
+ return isScopedPackage || hasVersionPrefix;
337
+ }
45
338
  // src/config/normalizeCommitFilter.ts
46
339
  /**
47
340
  * Normalize a commit classifier into a consistent function.
@@ -61,6 +354,19 @@ function normalizeCommitFilter(classifier) {
61
354
  }));
62
355
  return (commit) => commit.type ? map.get(commit.type) : null;
63
356
  }
357
+ // src/config/sanitizePrereleaseLabel.ts
358
+ /**
359
+ * Sanitize a string into a safe, SemVer-compliant prerelease label.
360
+ *
361
+ * Replaces sequences of non-alphanumeric characters with a single hyphen and
362
+ * removes leading or trailing hyphens.
363
+ *
364
+ * @param label Raw string to sanitize
365
+ * @returns Safe SemVer prerelease label
366
+ */
367
+ function sanitizePrereleaseLabel(label) {
368
+ return label.replace(/[^a-zA-Z0-9]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
369
+ }
64
370
  // src/config/normalizeReleaseRule.ts
65
371
  /**
66
372
  * Normalize a release rule input into a resolved release rule object.
@@ -135,22 +441,360 @@ function normalizeWorkspace(cwd, workspace) {
135
441
  async function resolvePlugin(cwd, plugin) {
136
442
  let options;
137
443
  if (Array.isArray(plugin)) [plugin, options] = plugin;
138
- if (typeof plugin === "string") plugin = await import(createRequire(pathToFileURL(cwd)).resolve(plugin));
444
+ if (typeof plugin === "string") plugin = await import(createRequire(pathToFileURL(`${cwd}/`)).resolve(plugin));
139
445
  if (plugin != null && typeof plugin === "object" && "default" in plugin) plugin = plugin.default;
140
446
  if (typeof plugin === "function") return [plugin, options];
141
447
  if (plugin != null && typeof plugin === "object" && Object.hasOwn(plugin, "name") && typeof plugin.name === "string") return plugin;
142
448
  return null;
143
449
  }
450
+ // src/config/resolveReleaseChannel.ts
451
+ /**
452
+ * Resolve the release channel for a release context.
453
+ *
454
+ * Uses the release rule when `channel` is `boolean` or omitted. Sanitizes the
455
+ * reference name when enabling default channel resolution and interpolates
456
+ * `templateParams` into the result.
457
+ *
458
+ * @param options Options for resolving the release channel
459
+ * @returns Resolved release channel string or `undefined`
460
+ */
461
+ function resolveReleaseChannel(options) {
462
+ const { ref, rule, templateParams } = options;
463
+ let { channel } = options;
464
+ let resolved;
465
+ if (channel === true || channel == null) channel = rule?.releaseChannel ?? channel;
466
+ if (typeof channel === "string") resolved = channel;
467
+ else if (channel) resolved = sanitizePrereleaseLabel(ref.name);
468
+ if (typeof resolved === "string") resolved = interpolate(resolved, templateParams);
469
+ return resolved;
470
+ }
471
+ // src/config/resolveVersionQualifier.ts
472
+ /**
473
+ * Resolve the version qualifier for a release context.
474
+ *
475
+ * Uses the release rule when `qualifier` is `boolean` or omitted. Interpolates
476
+ * `templateParams` into `qualifier` and validates that the result forms a
477
+ * valid SemVer prerelease identifier.
478
+ *
479
+ * @param options Options for resolving the version qualifier
480
+ * @returns Resolved version qualifier string or `undefined`
481
+ * @throws If the resolved string is not a valid SemVer prerelease identifier
482
+ */
483
+ function resolveVersionQualifier(options) {
484
+ const { rule, templateParams } = options;
485
+ let { qualifier } = options;
486
+ let resolved;
487
+ if (qualifier === true || qualifier == null) qualifier = rule?.versionQualifier ?? qualifier;
488
+ if (typeof qualifier === "string") resolved = qualifier;
489
+ else if (qualifier) resolved = "";
490
+ if (typeof resolved === "string") resolved = interpolate(resolved, templateParams);
491
+ if (resolved && !isSemVer(`1.0.0-${resolved}.1`)) throw new Error(`The resolved version qualifier "${resolved}" is not a valid SemVer prerelease identifier.`);
492
+ return resolved;
493
+ }
494
+ // src/git/branch/getCurrentGitBranch.ts
495
+ /**
496
+ * Get the current Git branch name.
497
+ *
498
+ * Uses `execGit` to run `git symbolic-ref -q --short HEAD` in the provided
499
+ * working directory and trims the result. Returns an empty string when the
500
+ * repository is in a detached HEAD state.
501
+ *
502
+ * @param cwd The working directory to run the Git command in
503
+ * @returns The current branch name as a string
504
+ */
505
+ async function getCurrentGitBranch(cwd) {
506
+ return (await execGit(cwd, [
507
+ "symbolic-ref",
508
+ "-q",
509
+ "--short",
510
+ "HEAD"
511
+ ])).trim();
512
+ }
513
+ // src/git/commit/createGitCommit.ts
514
+ /**
515
+ * Stage all changes and create a git commit with the specified message.
516
+ *
517
+ * Validates the commit message and working directory status before staging
518
+ * all changes and executing the commit command.
519
+ *
520
+ * @param cwd The target directory path for executing git commands
521
+ * @param message The message to associate with the commit
522
+ * @returns A promise that resolves when the operation completes
523
+ */
524
+ async function createGitCommit(cwd, message) {
525
+ if (!message) return;
526
+ await execGit(cwd, ["add", "."]);
527
+ if (!(await execGit(cwd, ["status", "--porcelain"])).trim()) return;
528
+ await execGit(cwd, [
529
+ "commit",
530
+ "--message",
531
+ message
532
+ ]);
533
+ }
534
+ // src/git/commit/getCurrentGitCommit.ts
535
+ /**
536
+ * Resolve the current `HEAD` commit in the repository.
537
+ *
538
+ * @param cwd Repository working directory path
539
+ * @param markers Optional array of custom trailer marker strings
540
+ * @returns Parsed commit object for the current `HEAD` commit
541
+ */
542
+ function getCurrentGitCommit(cwd, markers = []) {
543
+ return getParsedGitCommit(cwd, "HEAD", markers);
544
+ }
545
+ // src/git/history/restoreFullGitHistory.ts
546
+ /**
547
+ * Convert a shallow clone into a full clone by fetching additional history.
548
+ *
549
+ * Runs `git fetch --unshallow`. Returns `true` when the operation succeeds
550
+ * and `false` on error.
551
+ *
552
+ * @param cwd Repository working directory
553
+ * @returns `true` when the operation succeeded, otherwise `false`
554
+ */
555
+ function restoreFullGitHistory(cwd) {
556
+ return execGit(cwd, ["fetch", "--unshallow"]).then(() => true).catch(() => false);
557
+ }
558
+ // src/git/repository/getGitConfigValue.ts
559
+ /**
560
+ * Get a local git configuration value for `key` in the repository at `cwd`.
561
+ *
562
+ * Returns the config value when present; otherwise `undefined`.
563
+ *
564
+ * @param cwd Repository working directory
565
+ * @param key Git config key to read
566
+ * @returns The config value or `undefined` if not set
567
+ */
568
+ async function getGitConfigValue(cwd, key) {
569
+ try {
570
+ const value = (await execGit(cwd, [
571
+ "config",
572
+ "--local",
573
+ "--get",
574
+ key
575
+ ])).trim();
576
+ return value ? value : void 0;
577
+ } catch {
578
+ return;
579
+ }
580
+ }
581
+ // src/git/repository/ensureGitUserConfig.ts
582
+ /**
583
+ * Ensure Git user configuration is set and return a cleanup handle.
584
+ *
585
+ * Checks the existing `user.name` and `user.email` configuration for the given
586
+ * working directory. Updates the configuration if either value is missing and
587
+ * returns an `AsyncDisposable` resource that restores the original state upon
588
+ * disposal.
589
+ *
590
+ * @param cwd Working directory path in which to check and set Git configuration
591
+ * @param user Git author details containing name and email
592
+ * @returns Async disposable cleanup object if updated, or undefined if already set
593
+ */
594
+ async function ensureGitUserConfig(cwd, user) {
595
+ const initialName = await getGitConfigValue(cwd, "user.name");
596
+ const initialEmail = await getGitConfigValue(cwd, "user.email");
597
+ if (initialName && initialEmail) return;
598
+ await execGit(cwd, [
599
+ "config",
600
+ "user.name",
601
+ user.name
602
+ ]);
603
+ await execGit(cwd, [
604
+ "config",
605
+ "user.email",
606
+ user.email
607
+ ]);
608
+ return { async [Symbol.asyncDispose]() {
609
+ if (initialName) await execGit(cwd, [
610
+ "config",
611
+ "user.name",
612
+ initialName
613
+ ]);
614
+ else await execGit(cwd, [
615
+ "config",
616
+ "--unset",
617
+ "user.name"
618
+ ]);
619
+ if (initialEmail) await execGit(cwd, [
620
+ "config",
621
+ "user.email",
622
+ initialEmail
623
+ ]);
624
+ else await execGit(cwd, [
625
+ "config",
626
+ "--unset",
627
+ "user.email"
628
+ ]);
629
+ } };
630
+ }
631
+ // src/git/repository/getGitRemote.ts
632
+ /**
633
+ * Get the URL for the named remote (defaults to `origin`).
634
+ *
635
+ * @param cwd Repository working directory
636
+ * @param remoteName Remote name (defaults to `'origin'`)
637
+ * @returns Remote URL string or `null` when unavailable
638
+ */
639
+ function getGitRemote(cwd, remoteName = "origin") {
640
+ return execGit(cwd, [
641
+ "remote",
642
+ "get-url",
643
+ remoteName
644
+ ]).then((stdout) => stdout.trim()).catch(() => null);
645
+ }
646
+ // src/git/repository/pushGitChanges.ts
647
+ /**
648
+ * Push a branch and optional tags to the `origin` remote using an atomic push.
649
+ *
650
+ * @param cwd Repository working directory
651
+ * @param branch Branch name to push
652
+ * @param additionalTags Optional list of tag names to push alongside the branch
653
+ * @returns Promise that resolves when the push completes
654
+ */
655
+ async function pushGitChanges(cwd, branch, ...additionalTags) {
656
+ await execGit(cwd, [
657
+ "push",
658
+ "origin",
659
+ ...compact([branch, ...additionalTags]),
660
+ "--atomic",
661
+ "--no-verify"
662
+ ]);
663
+ }
664
+ // src/git/repository/resolveGitRepository.ts
665
+ /**
666
+ * Resolve Git repository host, owner, and project metadata from the `origin` remote URL.
667
+ *
668
+ * @param cwd Repository working directory
669
+ * @returns Promise that resolves to a `GitRepository` object, or `null` when unavailable
670
+ */
671
+ async function resolveGitRepository(cwd) {
672
+ const origin = await getGitRemote(cwd);
673
+ if (!origin) return null;
674
+ const info = GitHost.fromUrl(origin);
675
+ if (info && typeof info.type === "string" && typeof info.user === "string" && typeof info.project === "string") return {
676
+ host: info.type,
677
+ owner: info.user,
678
+ repo: info.project,
679
+ url: info.browse()
680
+ };
681
+ return null;
682
+ }
683
+ // src/git/tag/createGitTag.ts
684
+ /**
685
+ * Create a git tag in the repository at `cwd`.
686
+ *
687
+ * Creates an annotated tag when `message` is provided.
688
+ *
689
+ * @param cwd Repository working directory
690
+ * @param tag Tag name to create
691
+ * @param message Optional tag message (creates an annotated tag when present)
692
+ * @returns Promise that resolves when the tag is created
693
+ */
694
+ async function createGitTag(cwd, tag, message) {
695
+ await execGit(cwd, ["tag", ...message ? [
696
+ "-a",
697
+ tag,
698
+ "-m",
699
+ message,
700
+ "--cleanup=whitespace"
701
+ ] : [tag]]);
702
+ }
703
+ // src/git/tag/getCurrentGitTag.ts
704
+ /**
705
+ * Get the tag name that exactly matches the current `HEAD`, if any.
706
+ *
707
+ * @param cwd Repository working directory
708
+ * @returns Tag name or `null` when no exact tag matches HEAD
709
+ */
710
+ async function getCurrentGitTag(cwd) {
711
+ try {
712
+ const tag = (await execGit(cwd, [
713
+ "describe",
714
+ "--tags",
715
+ "--exact-match"
716
+ ])).trim();
717
+ /* istanbul ignore next */
718
+ return tag ? tag : null;
719
+ } catch {
720
+ return null;
721
+ }
722
+ }
723
+ // src/git/tag/getLatestGitTag.ts
724
+ /**
725
+ * Get the most recent tag reachable from `HEAD`.
726
+ *
727
+ * @param cwd Repository working directory
728
+ * @returns Latest tag string or `null` when none is found
729
+ */
730
+ async function getLatestGitTag(cwd) {
731
+ try {
732
+ const tag = (await execGit(cwd, [
733
+ "describe",
734
+ "--tags",
735
+ "--abbrev=0"
736
+ ])).trim();
737
+ /* istanbul ignore next */
738
+ return tag ? tag : null;
739
+ } catch {
740
+ return null;
741
+ }
742
+ }
743
+ // src/git/tag/isGitTagExact.ts
744
+ /**
745
+ * Check whether a given tag points to the provided commit.
746
+ *
747
+ * @param cwd Repository working directory
748
+ * @param tag Tag name to resolve
749
+ * @param commit Commit hash to compare against
750
+ * @returns `true` when the tag points at `commit`, otherwise `false`
751
+ */
752
+ async function isGitTagExact(cwd, tag, commit) {
753
+ try {
754
+ await execGit(cwd, [
755
+ "merge-base",
756
+ "--is-ancestor",
757
+ `refs/tags/${tag}^{commit}`,
758
+ commit
759
+ ]);
760
+ await execGit(cwd, [
761
+ "merge-base",
762
+ "--is-ancestor",
763
+ commit,
764
+ `refs/tags/${tag}^{commit}`
765
+ ]);
766
+ return true;
767
+ } catch {
768
+ return false;
769
+ }
770
+ }
771
+ // src/workflow/discovery/filterPackages.ts
772
+ /**
773
+ * Filter packages by name patterns.
774
+ *
775
+ * Keeps the packages whose names match `patterns`, scoping a release run to
776
+ * a subset of the discovered workspace. Returns a copy of every package when
777
+ * `patterns` is empty.
778
+ *
779
+ * @param packages Workspace packages to filter
780
+ * @param patterns Minimatch patterns to match package names against
781
+ * @returns Packages whose names match the patterns
782
+ */
783
+ function filterPackages(packages, patterns) {
784
+ if (patterns.length === 0) return [...packages];
785
+ return packages.filter((pkg) => isMatch(pkg.name ?? "", patterns));
786
+ }
144
787
  // src/workflow/discovery/sortPackages.ts
145
788
  /**
146
789
  * Sort workspace packages topologically based on their dependency graphs.
147
790
  *
148
- * Deepest dependents are placed first in the resulting array, ensuring that
149
- * a package always precedes its own dependencies. Ties and circular dependencies
150
- * are resolved deterministically using an alphabetical sort on the package directory (`dir`).
791
+ * Deepest dependencies are placed first in the resulting array, ensuring that
792
+ * a package always follows its own dependencies. Ties and circular dependencies
793
+ * are resolved deterministically using an alphabetical sort on the package
794
+ * location (`location`).
151
795
  *
152
796
  * @param packages The workspace packages to sort.
153
- * @returns A new array of packages sorted by dependency depth and directory path.
797
+ * @returns A new array of packages sorted by dependency depth and location.
154
798
  */
155
799
  function sortPackages(packages) {
156
800
  const packageNodes = [];
@@ -176,6 +820,555 @@ function sortPackages(packages) {
176
820
  }
177
821
  return packageNodes.toSorted((a, b) => b.level - a.level).map((node) => node.package);
178
822
  }
179
- export { ALL_FILES, DEFAULT_CHANGELOG_FILE, DEV_NULL, GIT_PRETTY_FIELD_SEPARATOR, GIT_PRETTY_FORMAT, GIT_REL_FLAGS, GIT_TRAILER_RELEASE_AGENT, HookDispatcher, Priority, RELEASE_HOOK_NAMES, SEMVER_REGEX, TTLCache, appendReleaseReportSummary, buildChangelog, buildDependencyGraph, buildReleaseNotes, buildTrailerPattern, bumpVersion, compact, countGitHistory, createGitCommit, createGitTag, createPlugin, deleteGitTag, deriveChangeReleases, deriveCommitReleaseType, deriveReleaseType, deriveTransitionReleases, detectGitRelationship, discoverPackageTag, ensureGitTag, ensureGitUserConfig, execCommand, execGit, executeReleaseWorkflow, expandGitHistory, extractLatestVersion, extractMentions, extractPlainText, extractPreviousVersion, extractSemVer, extractVersionQualifier, filterPackages, findReleaseRule, formatError, formatFile, generateGitTagName, generateReleaseCommitMessage, generateReleaseReport, getCurrentGitBranch, getCurrentGitCommit, getCurrentGitTag, getGitConfigValue, getGitRemote, getGitTagMessage, getLatestGitTag, getParsedGitCommit, interpolate, isCI, isClass, isDefined, isGitAncestor, isGitHubActions, isGitShallowRepository, isGitTagConnected, isGitTagExact, isGitTagPresent, isMatch, isQuietEnvironment, isSameReleaseCycle, isSemVer, isSemVerGitTag, isStableVersion, isTruthyString, iterateChangelogVersions, mergeGitHistory, normalizeCommitFilter, normalizeReleaseRule, normalizeWorkspace, packageContainsCommit, parseGitCommit, parseGitPrettyFormat, pickPriorityReleaseType, prependChangelog, printReleaseReport, printReleaseReportAnnotation, promotePrereleaseVersions, propagateDependencyUpdates, pushGitChanges, readGitFile, readGitHistory, readJson, readPackageHistory, readParsedGitHistory, resolveGitRepository, resolveGitRevision, resolvePackageStableTag, resolvePackageTag, resolvePlugin, resolveReleaseChannel, resolveVersionQualifier, restoreFullGitHistory, sanitizePrereleaseLabel, sortPackages, unique, verifyPackageTag, withShallowLock, writeChangelog, writeJson };
823
+ // src/workflow/commit/generateReleaseCommitMessage.ts
824
+ var NOTABLE_TYPES = [
825
+ "feat",
826
+ "fix",
827
+ "perf",
828
+ "refactor",
829
+ "revert"
830
+ ];
831
+ /**
832
+ * Generate a formatted release commit message based on release plans and
833
+ * custom trailers.
834
+ *
835
+ * Compiles package version updates and included commit logs into a standardized
836
+ * conventional commit message body, appending configured release agent and
837
+ * custom trailers. Returns `null` if no valid release subject can be derived.
838
+ *
839
+ * @param cwd The working directory path
840
+ * @param plans Readonly array of release plans containing package changes and commit history
841
+ * @param trailers Optional record of custom git trailers to append to the commit
842
+ * @returns The formatted release commit message string or `null` if the subject is empty
843
+ * @example
844
+ * ```
845
+ * chore: release pkg-a@2.1.0, pkg-b@1.0.4
846
+ *
847
+ * Version Updates:
848
+ * - pkg-a: 2.0.0 → 2.1.0
849
+ * - pkg-b: 1.0.3 → 1.0.4
850
+ *
851
+ * Notable Changes:
852
+ * - feat(pkg-a): support custom plugin entrypoints (#210)
853
+ * - fix(pkg-b): correct minor typography bug in help text (#212)
854
+ *
855
+ * Release-Mode: Deferred
856
+ * ```
857
+ */
858
+ async function generateReleaseCommitMessage(cwd, plans, trailers = {}) {
859
+ const standalone = plans.length === 1;
860
+ trailers = {
861
+ [GIT_TRAILER_RELEASE_AGENT]: `ReelOut/${/* istanbul ignore next */ version}`,
862
+ ...trailers
863
+ };
864
+ plans = plans.filter((plan) => plan.release?.tag?.name).toSorted((a, b) => {
865
+ if (a.package.entry) return -1;
866
+ if (b.package.entry) return 1;
867
+ /* istanbul ignore next */
868
+ return (a.package.name ?? "").localeCompare(b.package.name ?? "");
869
+ });
870
+ let subject;
871
+ if (plans.length === 1) subject = standalone ? plans[0]?.release?.version : plans[0]?.release?.tag?.name;
872
+ else if (plans.length >= 2 && plans.length <= 3) subject = plans.map((plan) => plan.release?.tag?.name).join(", ");
873
+ else if (plans.length > 3) subject = `${plans.length} packages (${plans.slice(0, 2).map((plan) => plan.release?.tag?.name).join(", ")}, +${plans.length - 2} more)`;
874
+ if (!subject) return null;
875
+ const packages = plans.map((plan) => {
876
+ return `- ${plan.package.name || plan.package.location}: ${plan.package.version} → ${plan.release?.version}`;
877
+ });
878
+ const commits = (await plans.reduce(async (acc, plan) => mergeGitHistory(cwd, await acc, plan.history), Promise.resolve([]))).filter((commit) => {
879
+ const isNotableType = commit.type && NOTABLE_TYPES.includes(commit.type);
880
+ const isBreaking = commit.notes.length > 0;
881
+ return isNotableType || isBreaking;
882
+ }).toReversed().map(({ header }) => `- ${header}`);
883
+ return [
884
+ `chore: release ${subject}`,
885
+ packages.length >= 2 ? ["Version Updates:", ...packages].join("\n") : void 0,
886
+ commits.length > 0 ? ["Notable Changes:", ...commits].join("\n") : void 0,
887
+ Object.entries(trailers).map(([key, value]) => key && value != null ? `${key}: ${value}` : "").filter(Boolean).join("\n")
888
+ ].filter(Boolean).join("\n\n");
889
+ }
890
+ // src/plugin/createHostReleasePlugin.ts
891
+ /**
892
+ * Read the release token from the release environment.
893
+ *
894
+ * Treats unset and whitespace-only values as missing.
895
+ *
896
+ * @param env Release environment variables
897
+ * @param tokenEnvKey Environment variable holding the release token
898
+ * @returns The trimmed token, or undefined when it is not set
899
+ */
900
+ var readToken = (env, tokenEnvKey) => {
901
+ const token = env[tokenEnvKey]?.trim();
902
+ return token ? token : void 0;
903
+ };
904
+ /**
905
+ * Run the collected release rollbacks, logging individual rollback failures
906
+ * without aborting the remaining rollbacks.
907
+ *
908
+ * @param logger Logger used to report rollback failures
909
+ * @param displayName Human-readable host name used in log messages
910
+ * @param rollbacks Rollbacks collected during publishing
911
+ */
912
+ var rollbackReleases = async (logger, displayName, rollbacks) => {
913
+ const results = await Promise.allSettled(rollbacks.map(({ rollback }) => rollback()));
914
+ for (const [index, entry] of rollbacks.entries()) {
915
+ const result = results[index];
916
+ if (result?.status === "rejected") logger.error(`A ${displayName} release for tag "${entry.tag}" could not be rolled back: ${formatError(result.reason)}`);
917
+ }
918
+ };
919
+ /**
920
+ * Create a built-in plugin that publishes releases to a git host.
921
+ *
922
+ * Produces the shared skeleton behind the host release plugins. The plugin
923
+ * stays inactive unless the release repository is hosted on the given host,
924
+ * and verifies the token during the `configure` stage: a missing token
925
+ * skips the plugin's `publish` step with a debug message — or fails the run in
926
+ * strict mode — and a provided token is verified against the release
927
+ * repository before any mutation. During `publish`, host releases are
928
+ * created in reverse alphabetical package order (ensuring the root package
929
+ * release is created last) and rolled back when subsequent publishing
930
+ * stages fail.
931
+ *
932
+ * @param options Host release plugin options
933
+ * @returns A release plugin configured for the given host
934
+ */
935
+ function createHostReleasePlugin(options) {
936
+ return {
937
+ name: options.name,
938
+ version: options.version,
939
+ configure: async (context, next) => {
940
+ const repository = context.repository;
941
+ if (repository?.host !== options.host) {
942
+ context.logger.debug(`${options.displayName} releases will not be created: no ${options.displayName}-hosted repository was detected.`);
943
+ return next(context);
944
+ }
945
+ const token = readToken(context.env, options.tokenEnvKey);
946
+ if (!token) {
947
+ if (context.strict) throw new Error(`The ${options.tokenEnvKey} environment variable is required in strict mode.`);
948
+ context.logger.debug(`${options.displayName} releases will not be created: ${options.tokenEnvKey} is not set.`);
949
+ return next(context);
950
+ }
951
+ await options.verifyToken(token, repository);
952
+ return next(context);
953
+ },
954
+ publish: async (context, next) => {
955
+ if (context.repository?.host !== options.host) {
956
+ context.logger.debug(`${options.displayName} publishing was skipped: no ${options.displayName}-hosted repository was detected.`);
957
+ return next(context);
958
+ }
959
+ const token = readToken(context.env, options.tokenEnvKey);
960
+ if (!token) return next(context);
961
+ if (context.dryRun) {
962
+ context.logger.debug(`[DRY RUN] ${options.displayName} releases will not be created.`);
963
+ return next(context);
964
+ }
965
+ const plans = context.plans.toSorted((a, b) => (a.package.name || "").localeCompare(b.package.name || ""));
966
+ const repository = context.repository;
967
+ const rollbacks = [];
968
+ try {
969
+ for (const plan of plans.toReversed()) {
970
+ const rollback = await options.createRelease(context, plan, token, repository);
971
+ if (rollback) rollbacks.push({
972
+ tag: plan.release?.tag?.name ?? "unknown",
973
+ rollback
974
+ });
975
+ }
976
+ } catch (err) {
977
+ await rollbackReleases(context.logger, options.displayName, rollbacks);
978
+ throw err;
979
+ }
980
+ try {
981
+ return await next(context);
982
+ } catch (err) {
983
+ await rollbackReleases(context.logger, options.displayName, rollbacks);
984
+ throw err;
985
+ }
986
+ }
987
+ };
988
+ }
989
+ // src/workflow/report/resolveErrorMessage.ts
990
+ /**
991
+ * Resolve a displayable message from an unknown error value.
992
+ *
993
+ * Normalizes `Error` instances to their `message` and passes string values
994
+ * through unchanged. Returns `null` for any other shape so callers can fall
995
+ * back to a generic message.
996
+ *
997
+ * @param error Unknown error value carried on a release outcome
998
+ * @returns The resolved error message, or `null` when none can be resolved
999
+ */
1000
+ function resolveErrorMessage(error) {
1001
+ if (Error.isError(error)) return error.message;
1002
+ return typeof error === "string" ? error : null;
1003
+ }
1004
+ var FALLBACK_ERROR_MESSAGE = "An unexpected error occurred during the release process.";
1005
+ /**
1006
+ * Resolve a displayable failure message from a release outcome.
1007
+ *
1008
+ * Normalizes the outcome error to its message and falls back to a generic
1009
+ * message when the error carries no displayable content.
1010
+ *
1011
+ * @param outcome Failure outcome whose error is rendered
1012
+ * @returns The resolved error message, or the fallback message
1013
+ */
1014
+ function resolveOutcomeErrorMessage(outcome) {
1015
+ return resolveErrorMessage(outcome.error) || FALLBACK_ERROR_MESSAGE;
1016
+ }
1017
+ // src/workflow/report/appendReleaseReportSummary.ts
1018
+ var STATUS_LABELS = {
1019
+ success: "Success",
1020
+ failure: "Failure"
1021
+ };
1022
+ /**
1023
+ * Append a Markdown release report to the GitHub Actions job summary.
1024
+ *
1025
+ * Detects a GitHub Actions runner through the `GITHUB_ACTIONS` environment
1026
+ * variable and appends the rendered `report` to the file referenced by
1027
+ * `GITHUB_STEP_SUMMARY`, so GitHub displays it on the run summary page. Dry
1028
+ * runs append a `(dry run)` marker to the status line; real releases render
1029
+ * the status unmarked. Does nothing outside GitHub Actions or when no summary
1030
+ * file is configured, and logs a warning instead of throwing when the summary
1031
+ * file cannot be written.
1032
+ *
1033
+ * @param logger Logger instance for reporting summary write failures
1034
+ * @param env Readonly process environment variables object
1035
+ * @param report Release report containing outcome and package details
1036
+ */
1037
+ function appendReleaseReportSummary(logger, env, report) {
1038
+ if (!isGitHubActions(env)) return;
1039
+ const filePath = env.GITHUB_STEP_SUMMARY;
1040
+ if (!filePath) return;
1041
+ try {
1042
+ appendFileSync(filePath, `\n${formatReleaseReportSummary(report)}`);
1043
+ } catch (error) {
1044
+ logger.warn(`GitHub Actions job summary could not be written to "${filePath}": ${error instanceof Error ? error.message : error}`);
1045
+ }
1046
+ }
1047
+ var formatPackageLabel = (plan) => {
1048
+ if (plan.package.name) return `\`${plan.package.name}\``;
1049
+ return `\`${plan.package.location}\``;
1050
+ };
1051
+ var formatReleaseReportSummary = (report) => {
1052
+ const lines = ["## ReelOut Release Report", ""];
1053
+ if (report.outcome) {
1054
+ const status = STATUS_LABELS[report.outcome.status];
1055
+ const label = report.dryRun ? `${status} (dry run)` : status;
1056
+ lines.push(`**Status:** ${label}`, "");
1057
+ }
1058
+ if (report.outcome?.status === "failure") {
1059
+ const message = resolveOutcomeErrorMessage(report.outcome);
1060
+ lines.push(...message.split("\n").map((line) => `> ${line}`), "");
1061
+ return lines.join("\n");
1062
+ }
1063
+ if (report.plans.length === 0) {
1064
+ lines.push("No packages are scheduled for release.", "");
1065
+ return lines.join("\n");
1066
+ }
1067
+ const plans = report.plans.toSorted((a, b) => (a.package.name || "").localeCompare(b.package.name || ""));
1068
+ lines.push("| Package | Version | Type | Tag |", "| --- | --- | --- | --- |");
1069
+ for (const plan of plans) {
1070
+ const version = `\`${plan.release.version}\` ← \`${plan.package.version}\``;
1071
+ lines.push([
1072
+ `| ${formatPackageLabel(plan)}`,
1073
+ version,
1074
+ plan.release.type,
1075
+ plan.release.tag ? `\`${plan.release.tag}\`` : ""
1076
+ ].join(" | ") + " |");
1077
+ }
1078
+ lines.push("");
1079
+ for (const plan of plans) {
1080
+ const changelog = plan.release.changelog?.trim();
1081
+ if (!changelog) continue;
1082
+ lines.push("<details>", `<summary>${formatPackageLabel(plan)} ${plan.release.version}</summary>`, "", changelog, "", "</details>", "");
1083
+ }
1084
+ return lines.join("\n");
1085
+ };
1086
+ // src/workflow/report/generateReleaseReport.ts
1087
+ /**
1088
+ * Generate a structured release report from the current workflow state.
1089
+ *
1090
+ * Extracts state information from `context` and organizes it into a report
1091
+ * containing the `dryRun` flag, the terminal release outcome, release plans,
1092
+ * and package metadata. Omits unversioned release plans from the finalized
1093
+ * output.
1094
+ *
1095
+ * @param context Release execution context containing workflow state and plans
1096
+ * @returns Structured release report object containing workflow results
1097
+ */
1098
+ function generateReleaseReport(context) {
1099
+ return {
1100
+ dryRun: context.dryRun,
1101
+ outcome: context.outcome,
1102
+ packages: context.packages.map((pkg) => ({
1103
+ location: pkg.location,
1104
+ name: pkg.name,
1105
+ version: pkg.version
1106
+ })),
1107
+ plans: compact(context.plans.map((plan) => {
1108
+ if (!plan.release?.version) return null;
1109
+ return {
1110
+ package: {
1111
+ provider: plan.package.provider,
1112
+ entry: plan.package.entry,
1113
+ location: plan.package.location,
1114
+ name: plan.package.name,
1115
+ version: plan.package.version,
1116
+ private: !!plan.package.private
1117
+ },
1118
+ release: {
1119
+ type: plan.release.type,
1120
+ version: plan.release.version,
1121
+ tag: plan.release.tag?.name,
1122
+ changelog: plan.release.changelog
1123
+ }
1124
+ };
1125
+ }))
1126
+ };
1127
+ }
1128
+ // src/workflow/report/printReleaseReport.ts
1129
+ /**
1130
+ * Print a formatted release report to the logger.
1131
+ *
1132
+ * Logs the terminal outcome status and details for planned package releases.
1133
+ * Displays package names, directories, and version changes on success, or
1134
+ * outputs the error message on failure. Dry runs append a `(dry run)` marker
1135
+ * to the status line; real releases print the status unmarked.
1136
+ *
1137
+ * @param logger Logger instance for outputting messages
1138
+ * @param report Release report containing outcome and package details
1139
+ */
1140
+ function printReleaseReport(logger, report) {
1141
+ if (report.outcome) {
1142
+ const statusLabel = {
1143
+ success: colors.green("SUCCESS"),
1144
+ failure: colors.red("FAILURE")
1145
+ }[report.outcome.status];
1146
+ logger.info(`Status: ${[statusLabel, report.dryRun && colors.yellow("(dry run)")].filter(Boolean).join(" ")}`);
1147
+ }
1148
+ if (report.outcome?.status === "failure") return logger.error(["Release complete:", colors.red(resolveOutcomeErrorMessage(report.outcome))].join(" "));
1149
+ if (report.plans.length === 0) return logger.info(["Release complete:", colors.yellow("No packages are scheduled for release.")].join(" "));
1150
+ const header = [
1151
+ "Release complete:",
1152
+ colors.bold(colors.green(`${report.plans.length} released`)),
1153
+ colors.gray(`(${report.packages.length})`)
1154
+ ].join(" ");
1155
+ const list = report.plans.toSorted((a, b) => (a.package.name || "").localeCompare(b.package.name || "")).map((plan) => {
1156
+ let dir = path.normalize(path.join(plan.package.location, "."));
1157
+ dir = dir === "." ? dir : `./${dir}`;
1158
+ const name = plan.package.name ? colors.bgBlue(` ${plan.package.name} `) : !plan.package.entry && colors.gray(` ${dir} `);
1159
+ let version = [plan.release.version, plan.package.version].join(" ← ");
1160
+ version = ` ${version} `;
1161
+ const type = plan.release.type ? colors.gray(` ${plan.release.type} `) : void 0;
1162
+ return [[
1163
+ name,
1164
+ plan.release.type === "major" ? colors.bgRed(version) : colors.bgGreen(version),
1165
+ type
1166
+ ].filter(Boolean).join(""), plan.release.changelog?.replace(/^(#+ .+)$/gm, (_, header) => colors.cyan(header)).trim()].filter(Boolean).join("\n\n");
1167
+ }).join("\n\n");
1168
+ logger.info(`${header}\n\n${list}\n`);
1169
+ }
1170
+ // src/workflow/report/printReleaseReportAnnotation.ts
1171
+ /**
1172
+ * Print a GitHub Actions error annotation for a failed release.
1173
+ *
1174
+ * Detects a GitHub Actions runner through the `GITHUB_ACTIONS` environment
1175
+ * variable and writes a `::error` workflow command carrying the failure
1176
+ * reason to `stdout`, so GitHub surfaces the failure as an annotation on the
1177
+ * run page. Does nothing outside GitHub Actions or when the release did not
1178
+ * fail.
1179
+ *
1180
+ * @param env Readonly process environment variables object
1181
+ * @param stdout Writable stream receiving the annotation command
1182
+ * @param report Release report containing outcome and failure details
1183
+ */
1184
+ function printReleaseReportAnnotation(env, stdout, report) {
1185
+ if (!isGitHubActions(env) || report.outcome?.status !== "failure") return;
1186
+ const message = formatAnnotationMessage(resolveOutcomeErrorMessage(report.outcome));
1187
+ stdout.write(`::error title=Release failed::${message}\n`);
1188
+ }
1189
+ var formatAnnotationMessage = (message) => message.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
1190
+ // src/workflow/executeReleaseWorkflow.ts
1191
+ /**
1192
+ * Resolve a plugin's hook entry into a normalized hook definition.
1193
+ *
1194
+ * Accepts a bare middleware function or a `{ priority, middleware }`
1195
+ * definition and extracts its middleware and priority.
1196
+ *
1197
+ * @param hookName Name of the hook to resolve
1198
+ * @param plugin Plugin owning the hook entry
1199
+ * @returns Normalized hook definition, or `undefined` when unimplemented
1200
+ */
1201
+ function resolvePluginHook(hookName, plugin) {
1202
+ let hook = plugin[hookName];
1203
+ if (typeof hook === "function") hook = { middleware: hook };
1204
+ const middleware = hook?.middleware;
1205
+ const priority = hook?.priority;
1206
+ if (!middleware) return;
1207
+ return {
1208
+ priority,
1209
+ middleware
1210
+ };
1211
+ }
1212
+ /**
1213
+ * Throw a cancellation error when the context abort signal has fired.
1214
+ *
1215
+ * Wraps the underlying `AbortError` so the workflow reports a readable
1216
+ * cancellation instead of a bare DOM exception.
1217
+ *
1218
+ * @param context Release execution context carrying the optional abort signal
1219
+ * @throws If the context abort signal has already fired
1220
+ */
1221
+ function throwIfCancelled(context) {
1222
+ const signal = context.signal;
1223
+ if (!signal?.aborted) return;
1224
+ try {
1225
+ signal.throwIfAborted();
1226
+ } catch (err) {
1227
+ throw new Error("Release cancelled.", { cause: err });
1228
+ }
1229
+ }
1230
+ /**
1231
+ * Format a duration in milliseconds as a seconds string.
1232
+ *
1233
+ * @param duration Duration in milliseconds
1234
+ * @returns Duration formatted as seconds with two decimal places
1235
+ */
1236
+ function formatDuration(duration) {
1237
+ return `${(duration / 1e3).toFixed(2)}s`;
1238
+ }
1239
+ /**
1240
+ * Pick the console color for a duration, highlighting slow middleware.
1241
+ *
1242
+ * @param duration Duration in milliseconds
1243
+ * @returns Color function that highlights durations of five seconds or more
1244
+ */
1245
+ function durationColor(duration) {
1246
+ return duration >= 5e3 ? colors.yellow : colors.cyan;
1247
+ }
1248
+ /**
1249
+ * Format a hook and its owning plugin as a display label.
1250
+ *
1251
+ * @param hook Name of the hook
1252
+ * @param plugin Name of the plugin owning the hook
1253
+ * @returns Gray hook name followed by the plugin name
1254
+ */
1255
+ function hookLabel(hook, plugin) {
1256
+ return `${colors.gray(`[${hook}]`)} ${plugin}`;
1257
+ }
1258
+ /**
1259
+ * Execute the complete release workflow across all configured plugins.
1260
+ *
1261
+ * Runs each lifecycle phase sequentially, dispatching plugin hooks in onion
1262
+ * order based on declared priority, and checks the abort signal before each
1263
+ * phase. Each dispatched middleware runs through a single constructor
1264
+ * interceptor that also attributes failures to the owning hook and plugin,
1265
+ * collects middleware failures, and rescues `finalize` errors so the
1266
+ * remaining `finalize` middleware still runs. Outside `test` mode the
1267
+ * interceptor logs every middleware's exclusive duration — its wall-clock
1268
+ * time minus the time consumed by downstream middleware — on completion.
1269
+ * When a phase hook throws, plugin rollbacks run while the error unwinds,
1270
+ * then every `finalize` middleware runs with the failure recorded on
1271
+ * `context.outcome`. Each `finalize` failure is logged as a warning after
1272
+ * the report. A failing `finalize` middleware never changes the workflow
1273
+ * outcome and never masks the original workflow error.
1274
+ *
1275
+ * @param context Release execution context containing runtime options and logger
1276
+ * @param plugins List of release plugins to execute
1277
+ * @returns Promise that resolves when all phases and `finalize` middleware
1278
+ * complete
1279
+ * @throws If a lifecycle hook fails or the workflow is cancelled
1280
+ */
1281
+ async function executeReleaseWorkflow(context, plugins) {
1282
+ context.outcome = null;
1283
+ const middlewareFailures = [];
1284
+ const dispatcher = new HookDispatcher(async (context, registration, next) => {
1285
+ const plugin = registration.meta;
1286
+ /* istanbul ignore next */
1287
+ if (!plugin) throw new Error(`Registration for hook "${registration.hook}" is missing plugin metadata.`);
1288
+ const hook = registration.hook;
1289
+ const label = hookLabel(hook, plugin.name);
1290
+ context.logger.start(label);
1291
+ const startedAt = performance.now();
1292
+ let downstreamDuration = 0;
1293
+ const runNext = async () => {
1294
+ const downstreamStart = performance.now();
1295
+ try {
1296
+ return await next(context);
1297
+ } finally {
1298
+ downstreamDuration += performance.now() - downstreamStart;
1299
+ }
1300
+ };
1301
+ const finish = (hasError) => {
1302
+ const duration = performance.now() - startedAt - downstreamDuration;
1303
+ const color = durationColor(duration);
1304
+ const message = [label, color(formatDuration(duration))].join(" ");
1305
+ if (hasError) context.logger.error(message);
1306
+ else context.logger.success(message);
1307
+ };
1308
+ try {
1309
+ const result = await registration.middleware.call(plugin, context, runNext);
1310
+ finish(false);
1311
+ return result;
1312
+ } catch (error) {
1313
+ const phase = {
1314
+ hook,
1315
+ plugin: plugin.name
1316
+ };
1317
+ middlewareFailures.push({
1318
+ ...phase,
1319
+ error
1320
+ });
1321
+ context.outcome ??= {
1322
+ status: "failure",
1323
+ error,
1324
+ phase
1325
+ };
1326
+ finish(true);
1327
+ if (hook === "finalize") return next(context);
1328
+ throw error;
1329
+ }
1330
+ });
1331
+ for (const hookName of RELEASE_HOOK_NAMES) for (const plugin of plugins) {
1332
+ const definition = resolvePluginHook(hookName, plugin);
1333
+ if (!definition) continue;
1334
+ dispatcher.on(hookName, definition.middleware, {
1335
+ priority: definition.priority,
1336
+ meta: plugin
1337
+ });
1338
+ }
1339
+ const dispatch = async (index, context) => {
1340
+ const hook = RELEASE_HOOK_NAMES[index];
1341
+ if (!hook) return;
1342
+ if (hook === "finalize") return await dispatch(index + 1, context);
1343
+ throwIfCancelled(context);
1344
+ return await dispatcher.dispatch(hook, context, (context) => dispatch(index + 1, context));
1345
+ };
1346
+ try {
1347
+ await dispatch(0, context);
1348
+ context.outcome = {
1349
+ status: "success",
1350
+ error: null,
1351
+ phase: null
1352
+ };
1353
+ } catch (err) {
1354
+ context.outcome ??= {
1355
+ status: "failure",
1356
+ error: err,
1357
+ phase: null
1358
+ };
1359
+ }
1360
+ await dispatcher.dispatch("finalize", context);
1361
+ const report = generateReleaseReport(context);
1362
+ printReleaseReport(context.logger, report);
1363
+ appendReleaseReportSummary(context.logger, context.env, report);
1364
+ printReleaseReportAnnotation(context.env, context.stdout, report);
1365
+ for (const failure of middlewareFailures) {
1366
+ if (failure.hook !== "finalize") continue;
1367
+ if (failure.error === context.outcome.error) continue;
1368
+ context.logger.warn(`Plugin "${failure.plugin}" could not finalize: ${failure.error instanceof Error ? failure.error.message : String(failure.error)}`);
1369
+ }
1370
+ if (context.outcome.status === "failure") throw context.outcome.error;
1371
+ }
1372
+ export { ALL_FILES, DEFAULT_CHANGELOG_FILE, DEV_NULL, GIT_PRETTY_FIELD_SEPARATOR, GIT_PRETTY_FORMAT, GIT_REL_FLAGS, GIT_TRAILER_RELEASE_AGENT, HookDispatcher, Priority, RELEASE_HOOK_NAMES, SEMVER_REGEX, TTLCache, appendReleaseReportSummary, buildChangelog, buildDependencyGraph, buildReleaseNotes, buildTrailerPattern, bumpVersion, compact, countGitHistory, createGitCommit, createGitTag, createHostReleasePlugin, createPlugin, deleteGitTag, deriveChangeReleases, deriveCommitReleaseType, deriveReleaseType, deriveTransitionReleases, detectGitRelationship, discoverPackageTag, ensureGitTag, ensureGitUserConfig, execCommand, execGit, executeReleaseWorkflow, expandGitHistory, extractLatestVersion, extractMentions, extractPlainText, extractSemVer, extractVersionQualifier, filterPackages, findReleaseRule, formatError, formatFile, generateGitTagName, generateReleaseCommitMessage, generateReleaseReport, getCurrentGitBranch, getCurrentGitCommit, getCurrentGitTag, getGitConfigValue, getGitRemote, getGitTagMessage, getLatestGitTag, getParsedGitCommit, interpolate, isCI, isClass, isDefined, isGitAncestor, isGitHubActions, isGitShallowRepository, isGitTagConnected, isGitTagExact, isGitTagPresent, isMatch, isQuietEnvironment, isSameReleaseCycle, isSemVer, isSemVerGitTag, isStableVersion, isTruthyString, iterateChangelogVersions, mergeGitHistory, normalizeCommitFilter, normalizeReleaseRule, normalizeWorkspace, packageContainsCommit, parseGitCommit, parseGitPrettyFormat, pickPriorityReleaseType, prependChangelog, printReleaseReport, printReleaseReportAnnotation, propagateDependencyUpdates, pushGitChanges, readGitFile, readGitHistory, readJson, readPackageHistory, readParsedGitHistory, resolveGitRepository, resolveGitRevision, resolvePackageStableTag, resolvePackageTag, resolvePlugin, resolveReleaseChannel, resolveVersionQualifier, restoreFullGitHistory, sanitizePrereleaseLabel, sortPackages, unique, verifyPackageTag, withShallowLock, writeChangelog, writeJson };
180
1373
 
181
1374
  //# sourceMappingURL=index.js.map