@reelout/core 0.1.1 → 0.5.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 (138) hide show
  1. package/LICENSE +21 -0
  2. package/dist/analyzer.js +33 -0
  3. package/dist/analyzer.js.map +1 -0
  4. package/dist/builder.js +64 -0
  5. package/dist/builder.js.map +1 -0
  6. package/dist/changelog.js +63 -0
  7. package/dist/changelog.js.map +1 -0
  8. package/dist/formatError-BXNdyRfu.js +23 -0
  9. package/dist/formatError-BXNdyRfu.js.map +1 -0
  10. package/dist/index.js +225 -1
  11. package/dist/index.js.map +1 -0
  12. package/dist/types-la_KkjCS.js +1 -0
  13. package/dist/types.js +2 -0
  14. package/dist/workflow-CroJ6v4g.js +2736 -0
  15. package/dist/workflow-CroJ6v4g.js.map +1 -0
  16. package/package.json +35 -6
  17. package/src/analyzer.ts +59 -0
  18. package/src/builder.ts +116 -0
  19. package/src/cache/TTLCache.ts +100 -0
  20. package/src/cache/index.ts +4 -0
  21. package/src/changelog.ts +107 -0
  22. package/src/config/const.ts +104 -0
  23. package/src/config/createPlugin.ts +41 -0
  24. package/src/config/findReleaseRule.ts +26 -0
  25. package/src/config/index.ts +15 -0
  26. package/src/config/isSemVer.ts +31 -0
  27. package/src/config/isSemVerGitTag.ts +25 -0
  28. package/src/config/normalizeCommitFilter.ts +37 -0
  29. package/src/config/normalizeReleaseRule.ts +66 -0
  30. package/src/config/normalizeWorkspace.ts +34 -0
  31. package/src/config/resolvePlugin.ts +57 -0
  32. package/src/config/resolveReleaseChannel.ts +47 -0
  33. package/src/config/resolveVersionQualifier.ts +53 -0
  34. package/src/config/sanitizePrereleaseLabel.ts +18 -0
  35. package/src/git/branch/getCurrentGitBranch.ts +18 -0
  36. package/src/git/branch/index.ts +4 -0
  37. package/src/git/commit/createGitCommit.ts +29 -0
  38. package/src/git/commit/extractMentions.ts +34 -0
  39. package/src/git/commit/getCurrentGitCommit.ts +19 -0
  40. package/src/git/commit/getParsedGitCommit.ts +49 -0
  41. package/src/git/commit/index.ts +9 -0
  42. package/src/git/commit/parseGitCommit.ts +114 -0
  43. package/src/git/commit/parseGitPrettyFormat.ts +76 -0
  44. package/src/git/history/countGitHistory.ts +28 -0
  45. package/src/git/history/expandGitHistory.ts +112 -0
  46. package/src/git/history/index.ts +9 -0
  47. package/src/git/history/mergeGitHistory.ts +76 -0
  48. package/src/git/history/restoreFullGitHistory.ts +19 -0
  49. package/src/git/history/showGitHistory.ts +80 -0
  50. package/src/git/history/showParsedGitHistory.ts +28 -0
  51. package/src/git/index.ts +9 -0
  52. package/src/git/repository/ensureGitUserConfig.ts +50 -0
  53. package/src/git/repository/getGitConfigValue.ts +27 -0
  54. package/src/git/repository/getGitRemote.ts +20 -0
  55. package/src/git/repository/index.ts +10 -0
  56. package/src/git/repository/isGitShallowRepository.ts +21 -0
  57. package/src/git/repository/pushGitChanges.ts +26 -0
  58. package/src/git/repository/resolveGitRepository.ts +40 -0
  59. package/src/git/repository/withShallowLock.ts +62 -0
  60. package/src/git/revision/detectGitRelationship.ts +43 -0
  61. package/src/git/revision/index.ts +7 -0
  62. package/src/git/revision/isGitAncestor.ts +33 -0
  63. package/src/git/revision/readGitFile.ts +29 -0
  64. package/src/git/revision/resolveGitRevision.ts +23 -0
  65. package/src/git/tag/createGitTag.ts +25 -0
  66. package/src/git/tag/deleteGitTag.ts +17 -0
  67. package/src/git/tag/ensureGitTag.ts +63 -0
  68. package/src/git/tag/generateGitTagName.ts +43 -0
  69. package/src/git/tag/getCurrentGitTag.ts +23 -0
  70. package/src/git/tag/getGitTagMessage.ts +35 -0
  71. package/src/git/tag/getLatestGitTag.ts +22 -0
  72. package/src/git/tag/index.ts +13 -0
  73. package/src/git/tag/isGitTagConnected.ts +33 -0
  74. package/src/git/tag/isGitTagPointed.ts +38 -0
  75. package/src/git/tag/isGitTagPresent.ts +17 -0
  76. package/src/index.ts +9 -2
  77. package/src/plugin/HookManager.ts +128 -0
  78. package/src/plugin/index.ts +4 -0
  79. package/src/types.ts +259 -0
  80. package/src/util/buildTrailerPattern.ts +20 -0
  81. package/src/util/compact.ts +14 -0
  82. package/src/util/execCommand.ts +196 -0
  83. package/src/util/execGit.ts +27 -0
  84. package/src/util/formatError.ts +21 -0
  85. package/src/util/formatFile.ts +41 -0
  86. package/src/util/index.ts +19 -0
  87. package/src/util/interpolate.ts +141 -0
  88. package/src/util/isCI.ts +18 -0
  89. package/src/util/isClass.ts +34 -0
  90. package/src/util/isDefined.ts +12 -0
  91. package/src/util/isMatch.ts +43 -0
  92. package/src/util/isQuietEnvironment.ts +35 -0
  93. package/src/util/isTruthyString.ts +19 -0
  94. package/src/util/readJson.ts +47 -0
  95. package/src/util/unique.ts +26 -0
  96. package/src/util/writeJson.ts +28 -0
  97. package/src/workflow/analysis/deriveChangeReleases.ts +76 -0
  98. package/src/workflow/analysis/deriveTransitionReleases.ts +134 -0
  99. package/src/workflow/analysis/index.ts +10 -0
  100. package/src/workflow/analysis/isCommitForPackage.ts +23 -0
  101. package/src/workflow/analysis/promotePrereleaseVersions.ts +51 -0
  102. package/src/workflow/analysis/propagateDependencyUpdates.ts +71 -0
  103. package/src/workflow/analysis/sliceUnreleased.ts +36 -0
  104. package/src/workflow/analysis/streamPackageCommits.ts +34 -0
  105. package/src/workflow/changelog/buildChangelog.ts +79 -0
  106. package/src/workflow/changelog/buildReleaseNotes.ts +50 -0
  107. package/src/workflow/changelog/conventional-changelog-conventionalcommits.d.ts +7 -0
  108. package/src/workflow/changelog/extractLatestVersion.ts +22 -0
  109. package/src/workflow/changelog/extractPlainText.ts +38 -0
  110. package/src/workflow/changelog/extractPreviousVersion.ts +77 -0
  111. package/src/workflow/changelog/extractSemVer.ts +33 -0
  112. package/src/workflow/changelog/index.ts +12 -0
  113. package/src/workflow/changelog/iterateChangelogVersions.ts +70 -0
  114. package/src/workflow/changelog/prependChangelog.ts +59 -0
  115. package/src/workflow/changelog/writeChangelog.ts +27 -0
  116. package/src/workflow/committing/generateReleaseCommitMessage.ts +121 -0
  117. package/src/workflow/committing/index.ts +5 -0
  118. package/src/workflow/committing/isReleaseCommit.ts +56 -0
  119. package/src/workflow/discovery/buildDependencyGraph.ts +43 -0
  120. package/src/workflow/discovery/discoverPackageTag.ts +98 -0
  121. package/src/workflow/discovery/index.ts +9 -0
  122. package/src/workflow/discovery/resolvePackageStableTag.ts +88 -0
  123. package/src/workflow/discovery/resolvePackageTag.ts +45 -0
  124. package/src/workflow/discovery/sortPackages.ts +75 -0
  125. package/src/workflow/discovery/verifyPackageTag.ts +49 -0
  126. package/src/workflow/executeReleaseWorkflow.ts +130 -0
  127. package/src/workflow/index.ts +10 -0
  128. package/src/workflow/report/generateReleaseReport.ts +54 -0
  129. package/src/workflow/report/index.ts +5 -0
  130. package/src/workflow/report/printReleaseReport.ts +97 -0
  131. package/src/workflow/versioning/bumpVersion.ts +76 -0
  132. package/src/workflow/versioning/deriveReleaseType.ts +33 -0
  133. package/src/workflow/versioning/determineReleaseType.ts +35 -0
  134. package/src/workflow/versioning/extractVersionQualifier.ts +29 -0
  135. package/src/workflow/versioning/index.ts +10 -0
  136. package/src/workflow/versioning/isSameReleaseCycle.ts +36 -0
  137. package/src/workflow/versioning/isStableVersion.ts +31 -0
  138. package/src/workflow/versioning/pickPriorityReleaseType.ts +27 -0
@@ -0,0 +1,2736 @@
1
+ import semver from "semver";
2
+ import { colors } from "consola/utils";
3
+ import { Writable } from "node:stream";
4
+ import { spawn } from "node:child_process";
5
+ import prettier from "prettier";
6
+ import { minimatch } from "minimatch";
7
+ import fs, { readFile } from "node:fs/promises";
8
+ import path from "node:path";
9
+ import { CommitParser } from "conventional-commits-parser";
10
+ import { AsyncLocalStorage } from "node:async_hooks";
11
+ import GitHost from "hosted-git-info";
12
+ import { fromMarkdown } from "mdast-util-from-markdown";
13
+ import assert from "node:assert";
14
+ import createPreset from "conventional-changelog-conventionalcommits";
15
+ import { writeChangelogString } from "conventional-changelog-writer";
16
+ import { toMarkdown } from "mdast-util-to-markdown";
17
+ //#region src/workflow/versioning/extractVersionQualifier.ts
18
+ /**
19
+ * Extract the version qualifier string from a parsed `SemVer` instance.
20
+ *
21
+ * Strips the trailing numeric counter from the `prerelease` components if
22
+ * present. Joins any remaining prerelease identifiers with a dot separator.
23
+ *
24
+ * @param version Parsed `SemVer` instance or nullish value to inspect
25
+ * @returns The extracted qualifier string or `undefined` if no prerelease exists
26
+ */
27
+ function extractVersionQualifier(version) {
28
+ if (version != null && version.prerelease.length > 0) {
29
+ const prerelease = [...version.prerelease];
30
+ if (typeof prerelease.at(-1) === "number") prerelease.pop();
31
+ return prerelease.join(".");
32
+ } else return;
33
+ }
34
+ //#endregion
35
+ //#region src/workflow/versioning/bumpVersion.ts
36
+ /**
37
+ * Bump a semantic version string based on release and transition rules.
38
+ *
39
+ * Parses the target version and determines the next version string using the
40
+ * specified release type, prerelease identifier, and transition mode. Adjusts
41
+ * prerelease types when continuing an existing qualifier and returns `null` when
42
+ * `options.release` is omitted or if transition conditions fail.
43
+ *
44
+ * @param options Version bump configuration including release type, identifier, and transition rules
45
+ * @returns The bumped semantic version string, or `null` if no bump occurs
46
+ * @throws If `options.version` is not a valid semantic version
47
+ */
48
+ function bumpVersion(options) {
49
+ const { version } = options;
50
+ const parsed = semver.parse(version);
51
+ if (!parsed) throw new Error(`Version "${version}" is not a valid semantic version.`);
52
+ if (!options.release) return null;
53
+ if (parsed.prerelease.length > 0) {
54
+ if (options.transition === "advance" && options.identifier == null) return null;
55
+ } else if (options.transition === "continue") return null;
56
+ let release = options.release;
57
+ let identifier;
58
+ if (typeof options.identifier === "string") {
59
+ release = `pre${options.release}`;
60
+ identifier = options.identifier;
61
+ const parsedIdentifier = extractVersionQualifier(parsed);
62
+ const transition = options.transition ?? (parsedIdentifier && identifier === "" ? "advance" : "continue");
63
+ if (typeof parsedIdentifier === "string" && transition === "continue") {
64
+ if (release === "premajor" && parsed.minor === 0 && parsed.patch === 0 || release === "preminor" && parsed.patch === 0 || release === "prepatch") release = "prerelease";
65
+ }
66
+ }
67
+ return semver.inc(parsed, release, { loose: false }, identifier, "0");
68
+ }
69
+ //#endregion
70
+ //#region src/workflow/versioning/determineReleaseType.ts
71
+ /**
72
+ * Determine the release type for a single commit.
73
+ *
74
+ * Automatically returns `'major'` if the commit is marked as a breaking change.
75
+ * Otherwise, routes the commit through the custom `classifier` and ensures the
76
+ * resolved value is a valid semantic versioning release type.
77
+ *
78
+ * @param classifier Function mapping commits to release types
79
+ * @param commit Parsed commit to evaluate
80
+ * @returns `ReleaseType` string, or `null` when no matching rule applies
81
+ */
82
+ function determineReleaseType(classifier, commit) {
83
+ if (commit.notes.length > 0) return "major";
84
+ const type = classifier(commit);
85
+ switch (type) {
86
+ case "major":
87
+ case "minor":
88
+ case "patch": return type;
89
+ }
90
+ return null;
91
+ }
92
+ //#endregion
93
+ //#region src/workflow/versioning/pickPriorityReleaseType.ts
94
+ /**
95
+ * Determine the highest-priority release type between two candidates.
96
+ *
97
+ * Compares release types by precedence order: `major` > `minor` > `patch`.
98
+ * Returns the higher-precedence type, or `null` if neither applies.
99
+ *
100
+ * @param curr Current accumulated release type
101
+ * @param next Candidate release type to consider
102
+ * @returns Highest-precedence `ReleaseType`, or `null` if neither applies
103
+ */
104
+ function pickPriorityReleaseType(curr, next) {
105
+ for (const type of [
106
+ "major",
107
+ "minor",
108
+ "patch"
109
+ ]) if (curr === type || next === type) return type;
110
+ return null;
111
+ }
112
+ //#endregion
113
+ //#region src/workflow/versioning/deriveReleaseType.ts
114
+ /**
115
+ * Derive the combined release type from a commit history collection.
116
+ *
117
+ * Processes commits sequentially, accumulating the highest-precedence release
118
+ * type found by evaluating each individual commit and comparing it against the
119
+ * current maximum via `pickPriorityReleaseType`.
120
+ *
121
+ * @param classifier Function mapping commits to release types
122
+ * @param history Array of parsed commits to evaluate
123
+ * @returns `ReleaseType` string, or `null` when no matching rule applies
124
+ */
125
+ function deriveReleaseType(classifier, history) {
126
+ let releaseType = null;
127
+ for (const commit of history) releaseType = pickPriorityReleaseType(releaseType, determineReleaseType(classifier, commit));
128
+ return releaseType;
129
+ }
130
+ //#endregion
131
+ //#region src/workflow/versioning/isSameReleaseCycle.ts
132
+ /**
133
+ * Determine whether two semantic version strings or objects belong to the same release cycle.
134
+ *
135
+ * Compares the main version components of `currentVersion` and `nextVersion` to
136
+ * determine equality. Treats a transition from a non-zero `0.x` version to
137
+ * `1.0.0` as part of the same release cycle. Returns `false` if either input
138
+ * cannot be parsed.
139
+ *
140
+ * @param currentVersion Starting version string, `semver.SemVer` instance, or nullish value
141
+ * @param nextVersion Target version string, `semver.SemVer` instance, or nullish value
142
+ * @returns `true` if both versions belong to the same release cycle, `false` otherwise
143
+ */
144
+ function isSameReleaseCycle(currentVersion, nextVersion) {
145
+ const current = semver.parse(currentVersion);
146
+ const next = semver.parse(nextVersion);
147
+ if (!current || !next) return false;
148
+ if (current.compareMain(next) === 0) return true;
149
+ return current.major === 0 && (current.minor > 0 || current.patch > 0) && next.major === 1 && next.minor === 0 && next.patch === 0;
150
+ }
151
+ //#endregion
152
+ //#region src/workflow/versioning/isStableVersion.ts
153
+ /**
154
+ * Determine whether a version string represents a stable SemVer release.
155
+ *
156
+ * A version is considered stable when:
157
+ * - It is a valid SemVer string.
158
+ * - Its major version is greater than 0 (not 0.x.x).
159
+ * - It contains no prerelease identifiers (no `-alpha`, `-beta`, `-rc`, etc.).
160
+ *
161
+ * Build metadata (the `+` suffix) does not affect stability.
162
+ *
163
+ * @param version Semantic version string to check
164
+ * @returns `true` if `version` is a stable SemVer; otherwise `false`
165
+ * @throws If `version` is not a valid SemVer string
166
+ */
167
+ function isStableVersion(version) {
168
+ const parsed = semver.parse(version);
169
+ if (!parsed) throw new Error(`The version "${colors.bold(version)}" is not a valid SemVer.`);
170
+ return parsed.major > 0 && parsed.prerelease.length === 0;
171
+ }
172
+ //#endregion
173
+ //#region src/config/const.ts
174
+ var ALL_FILES = "**/*";
175
+ var DEFAULT_CHANGELOG_FILE = "CHANGELOG.md";
176
+ var GIT_TRAILER_RELEASE_AGENT = "Release-Agent";
177
+ /**
178
+ * 1. Primitive Building Blocks
179
+ *
180
+ * Base regular expression patterns for wildcards, alphanumeric strings with hyphens,
181
+ * and standard non-negative integers.
182
+ */
183
+ var WILDCARD = "\\*";
184
+ var ALPHANUM_DASH = "[0-9a-zA-Z-]+";
185
+ var NUMERIC_IDENTIFIER = "0|[1-9]\\d*";
186
+ /**
187
+ * 2. Package Name & Prefix Constructs
188
+ *
189
+ * Matches package name prefixes (unscoped or scoped) or a simple `v` prefix.
190
+ *
191
+ * Capture Groups:
192
+ * - Group 1: Package name (e.g., `my-package` or `@scope/my-package`)
193
+ */
194
+ var PKG_NAME_PART = `(?:${WILDCARD}|${ALPHANUM_DASH})`;
195
+ var OPTIONAL_VERSION_PREFIX = `(?:v|${`(${PKG_NAME_PART}|@${PKG_NAME_PART}\\/${PKG_NAME_PART})`}@)`;
196
+ /**
197
+ * 3. Core SemVer Components
198
+ *
199
+ * Matches standard `MAJOR.MINOR.PATCH` versions or wildcard variants (e.g., `1.0.0`, `*.*.*`).
200
+ *
201
+ * Capture Groups:
202
+ * - Group 3: Major version
203
+ * - Group 4: Minor version
204
+ * - Group 5: Patch version
205
+ */
206
+ var CAPTURED_VERSION_DIGIT = `(${WILDCARD}|${NUMERIC_IDENTIFIER})`;
207
+ var SEMVER_CORE = `${CAPTURED_VERSION_DIGIT}\\.${CAPTURED_VERSION_DIGIT}\\.${CAPTURED_VERSION_DIGIT}`;
208
+ var PRERELEASE_IDENTIFIER = `(?:${WILDCARD}|${NUMERIC_IDENTIFIER}|(\\d*[a-zA-Z-][0-9a-zA-Z-]*))`;
209
+ var FULL_SEMVER_PATTERN = `${OPTIONAL_VERSION_PREFIX}?${`(${SEMVER_CORE}${`(?:-(${PRERELEASE_IDENTIFIER}(?:\\.${PRERELEASE_IDENTIFIER})*))`}?${`(?:\\+(${ALPHANUM_DASH}(?:\\.${ALPHANUM_DASH})*))`}?)`}`;
210
+ /**
211
+ * Regular expression to match and capture Semantic Versioning (SemVer) strings,
212
+ * including optional package prefixes (e.g., `@scope/pkg@`) and `v` prefixes.
213
+ *
214
+ * @example
215
+ * ```ts
216
+ * SEMVER_REGEX.test('1.0.0') // true
217
+ * SEMVER_REGEX.test('v1.2.3-beta.1+sha.1234') // true
218
+ * SEMVER_REGEX.test('@scope/package@1.0.0') // true
219
+ * ```
220
+ *
221
+ * @see {@link https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string SemVer Specification}
222
+ */
223
+ var SEMVER_REGEX = new RegExp(FULL_SEMVER_PATTERN);
224
+ var DEV_NULL = new Writable({
225
+ /* istanbul ignore next */
226
+ write(_chunk, _encoding, callback) {
227
+ callback();
228
+ } });
229
+ var RELEASE_HOOK_NAMES = [
230
+ "configure",
231
+ "discover",
232
+ "analyze",
233
+ "build",
234
+ "write",
235
+ "publish",
236
+ "finalize"
237
+ ];
238
+ //#endregion
239
+ //#region src/util/buildTrailerPattern.ts
240
+ /**
241
+ * Build a regular expression to match trailer lines using custom markers.
242
+ *
243
+ * Combines the provided marker strings with a standard alphanumeric pattern
244
+ * to construct a regular expression that matches trailer definitions.
245
+ *
246
+ * @param markers Optional array of custom trailer marker strings
247
+ * @returns A regular expression matching trailer lines
248
+ */
249
+ function buildTrailerPattern(markers = []) {
250
+ return new RegExp(`^(${markers.map(RegExp.escape).concat("[A-Za-z0-9_-]+").join("|")})[ \\t]*:[ \\t]*(.*)$`);
251
+ }
252
+ //#endregion
253
+ //#region src/util/isDefined.ts
254
+ /**
255
+ * Type guard that asserts a value is neither `null` nor `undefined`.
256
+ *
257
+ * @param value Value to test
258
+ * @returns `true` when `value` is not `null` or `undefined`
259
+ */
260
+ function isDefined(value) {
261
+ return value != null;
262
+ }
263
+ //#endregion
264
+ //#region src/util/compact.ts
265
+ /**
266
+ * Remove `null` and `undefined` values from an array.
267
+ *
268
+ * @param array The array to compact
269
+ * @returns A new array that does not contain `null` or `undefined` values
270
+ */
271
+ function compact(array) {
272
+ return array.filter(isDefined);
273
+ }
274
+ //#endregion
275
+ //#region src/util/execCommand.ts
276
+ /**
277
+ * Execute a system command with arguments as a child process.
278
+ *
279
+ * Spawns the target process, collects output streams, and intercepts mutating
280
+ * `git` operations in test mode to inject deterministic commit timestamps.
281
+ *
282
+ * @param command Executable command name or path to spawn
283
+ * @param args Array of string arguments passed to the command
284
+ * @param options Execution environment, streaming, and signal options
285
+ * @returns Promise attached to the child process resolving to standard output
286
+ * @throws If process execution fails or exits with a non-zero status
287
+ */
288
+ function execCommand(command, args, options) {
289
+ const { cwd, signal } = options;
290
+ const env = {
291
+ HOME: process.env.HOME,
292
+ PATH: process.env.PATH,
293
+ ...options.env
294
+ };
295
+ const child = spawn(command, args, {
296
+ cwd,
297
+ env,
298
+ signal,
299
+ stdio: [
300
+ "ignore",
301
+ "pipe",
302
+ "pipe"
303
+ ]
304
+ });
305
+ const promise = new Promise((resolve, reject) => {
306
+ const stdout = [];
307
+ const stderr = [];
308
+ let settled = false;
309
+ function safeResolve(value) {
310
+ /* istanbul ignore next */
311
+ if (settled) return;
312
+ settled = true;
313
+ cleanup();
314
+ resolve(value);
315
+ }
316
+ function safeReject(err) {
317
+ /* istanbul ignore next */
318
+ if (settled) return;
319
+ settled = true;
320
+ cleanup();
321
+ reject(err);
322
+ }
323
+ function cleanup() {
324
+ child.off("error", onError);
325
+ child.off("close", onClose);
326
+ child.stdout.removeAllListeners("data");
327
+ child.stderr.removeAllListeners("data");
328
+ if (options.stdout) {
329
+ child.stdout.unpipe(options.stdout);
330
+ options.stdout.off("error", onError);
331
+ }
332
+ if (options.stderr) {
333
+ child.stderr.unpipe(options.stderr);
334
+ options.stderr.off("error", onError);
335
+ }
336
+ }
337
+ function onError(err) {
338
+ safeReject(err);
339
+ }
340
+ function onClose(code, signal) {
341
+ /* istanbul ignore next */
342
+ if (settled) return;
343
+ if (code === 0) return safeResolve(bufferArrayToString(stdout));
344
+ const quotedCommand = quoteCommandForMessage([command, ...args].join(" "));
345
+ /* istanbul ignore next */
346
+ const exitStatus = code !== null ? `exit code ${code}` : signal ? `signal ${signal}` : "unknown status";
347
+ const errorDiagnostics = bufferArrayToString(stderr).trim() || bufferArrayToString(stdout).trim();
348
+ const errorMessage = [`Command ${quotedCommand} failed (${exitStatus})`, errorDiagnostics].filter(Boolean).join("\n");
349
+ const err = new Error(errorMessage, { cause: {
350
+ code,
351
+ signal,
352
+ diagnostics: errorDiagnostics
353
+ } });
354
+ /* istanbul ignore else */
355
+ if (code != null) Object.defineProperty(err, "code", { value: code });
356
+ safeReject(err);
357
+ }
358
+ child.on("error", onError);
359
+ child.on("close", onClose);
360
+ if (options.stdout) {
361
+ options.stdout.on("error", onError);
362
+ child.stdout.pipe(options.stdout);
363
+ } else child.stdout.on("data", (chunk) => stdout.push(chunk));
364
+ if (options.stderr) {
365
+ options.stderr.on("error", onError);
366
+ child.stderr.pipe(options.stderr);
367
+ } else child.stderr.on("data", (chunk) => stderr.push(chunk));
368
+ });
369
+ promise.child = child;
370
+ return promise;
371
+ }
372
+ function bufferArrayToString(chunks) {
373
+ return Buffer.concat(chunks).toString("utf-8");
374
+ }
375
+ function quoteCommandForMessage(command) {
376
+ if (!command.includes("'")) return `'${command}'`;
377
+ if (!command.includes("\"")) return `"${command}"`;
378
+ return JSON.stringify(command);
379
+ }
380
+ //#endregion
381
+ //#region src/util/execGit.ts
382
+ /**
383
+ * Execute a Git command inside a target directory.
384
+ *
385
+ * Wraps `execCommand` to invoke the `git` executable using the provided
386
+ * arguments and execution options.
387
+ *
388
+ * @param cwd Working directory path where the Git command runs
389
+ * @param args Command-line arguments passed to Git
390
+ * @param options Additional execution, environment, and stream options
391
+ * @returns Promise attached to the child process resolving to stdout
392
+ */
393
+ function execGit(cwd, args, options) {
394
+ return execCommand("git", args, {
395
+ ...options,
396
+ cwd
397
+ });
398
+ }
399
+ //#endregion
400
+ //#region src/util/formatFile.ts
401
+ /**
402
+ * Format `content` for `filePath` using Prettier when possible.
403
+ *
404
+ * Resolves project/editorconfig settings and formats the provided content.
405
+ * Returns the original content on error or when no parser is inferred.
406
+ *
407
+ * @param filePath Path used to infer parser and config
408
+ * @param content Source content to format
409
+ * @returns Formatted content or original content on failure
410
+ */
411
+ async function formatFile(filePath, content) {
412
+ try {
413
+ const info = await prettier.getFileInfo(filePath, { resolveConfig: true });
414
+ const config = await prettier.resolveConfig(filePath, { editorconfig: true });
415
+ if (info.inferredParser == null) return content;
416
+ return await prettier.format(content, {
417
+ ...config,
418
+ parser: info.inferredParser,
419
+ filepath: filePath
420
+ });
421
+ } catch {
422
+ return content;
423
+ }
424
+ }
425
+ //#endregion
426
+ //#region src/util/interpolate.ts
427
+ var BACKSLASH = "\\";
428
+ var LEFT_BRACE = "{";
429
+ var RIGHT_BRACE = "}";
430
+ var DOT = ".";
431
+ var ESCAPE_CHARS = [
432
+ BACKSLASH,
433
+ LEFT_BRACE,
434
+ RIGHT_BRACE
435
+ ];
436
+ var BANNED_KEYS = [
437
+ "__proto__",
438
+ "constructor",
439
+ "prototype"
440
+ ];
441
+ /**
442
+ * Interpolate placeholders in `template` using values from `data`.
443
+ *
444
+ * - Placeholders use `{path.to.value}` (dot notation).
445
+ * - Backslash escapes are supported for `{`, `}`, `\`, and `.` inside tokens.
446
+ * - Tokens that reference banned keys (`__proto__`, `constructor`, `prototype`)
447
+ * are left unexpanded to avoid prototype pollution.
448
+ * - Only own properties are followed when resolving paths; if any step is
449
+ * missing, the original token text is preserved.
450
+ * - Resolved non-object, non-null values are stringified and inserted.
451
+ * - Unclosed tokens and a trailing backslash are preserved verbatim.
452
+ *
453
+ * @param template Template string containing placeholders like `{user.name}`
454
+ * @param data Object used to resolve placeholder paths
455
+ * @returns The template with placeholders replaced by corresponding values
456
+ */
457
+ function interpolate(template, data) {
458
+ let result = "";
459
+ let i = 0;
460
+ let char;
461
+ let nextChar;
462
+ while (char = template[i]) if (char === BACKSLASH) {
463
+ nextChar = template[i + 1];
464
+ if (nextChar !== void 0 && ESCAPE_CHARS.includes(nextChar)) {
465
+ result += nextChar;
466
+ i += 2;
467
+ } else {
468
+ result += char;
469
+ i += 1;
470
+ }
471
+ } else if (char === LEFT_BRACE) {
472
+ const keys = [];
473
+ let key = "";
474
+ let token = "";
475
+ let closed = false;
476
+ i += 1;
477
+ while (char = template[i]) {
478
+ if (char === RIGHT_BRACE) {
479
+ closed = true;
480
+ keys.push(key);
481
+ i += 1;
482
+ break;
483
+ }
484
+ if (char === BACKSLASH) {
485
+ nextChar = template[i + 1];
486
+ if (nextChar !== void 0 && [...ESCAPE_CHARS, DOT].includes(nextChar)) {
487
+ key += nextChar;
488
+ token += nextChar;
489
+ i += 2;
490
+ } else {
491
+ key += char;
492
+ token += char;
493
+ i += 1;
494
+ }
495
+ } else if (char === DOT) {
496
+ keys.push(key);
497
+ key = "";
498
+ token += char;
499
+ i += 1;
500
+ } else {
501
+ key += char;
502
+ token += char;
503
+ i += 1;
504
+ }
505
+ }
506
+ if (closed) {
507
+ let value = data;
508
+ for (const key of keys) {
509
+ const isSafeKey = !BANNED_KEYS.includes(key);
510
+ if (value !== null && typeof value === "object" && Object.hasOwn(value, key) && isSafeKey) value = value[key];
511
+ else {
512
+ value = void 0;
513
+ break;
514
+ }
515
+ }
516
+ if (value == null || typeof value === "object") result += LEFT_BRACE + token + RIGHT_BRACE;
517
+ else result += String(value);
518
+ } else result += LEFT_BRACE + token;
519
+ } else {
520
+ result += char;
521
+ i += 1;
522
+ }
523
+ return result;
524
+ }
525
+ //#endregion
526
+ //#region src/util/isClass.ts
527
+ /**
528
+ * Determine whether a given value is a constructible class.
529
+ *
530
+ * Verifies that the input is a function with a non-writable prototype, can
531
+ * be successfully invoked via `Reflect.construct`, and matches ES6 class
532
+ * syntax.
533
+ *
534
+ * @param func The unknown value to inspect
535
+ * @returns True if the value is a class, false otherwise
536
+ */
537
+ function isClass(func) {
538
+ if (typeof func !== "function") return false;
539
+ try {
540
+ Reflect.construct(Object, [], func);
541
+ } catch {
542
+ return false;
543
+ }
544
+ const descriptor = Object.getOwnPropertyDescriptor(func, "prototype");
545
+ if (!descriptor || descriptor.writable) return false;
546
+ return /^class\s/.test(Function.prototype.toString.call(func));
547
+ }
548
+ //#endregion
549
+ //#region src/util/isMatch.ts
550
+ /**
551
+ * Determine whether a target string matches glob patterns.
552
+ *
553
+ * Matches positive and negative glob patterns using dotfile support. Automatically
554
+ * expands a single negative pattern by prepending a global wildcard match.
555
+ *
556
+ * @param target Target string to evaluate against glob patterns
557
+ * @param patterns Single glob pattern or list of patterns to evaluate
558
+ * @returns True if target matches positive patterns and satisfies negative patterns
559
+ */
560
+ function isMatch(target, patterns) {
561
+ if (typeof patterns === "string") {
562
+ if (patterns.startsWith("!")) patterns = ["**/*", patterns];
563
+ else patterns = [patterns];
564
+ }
565
+ const positives = [];
566
+ const negatives = [];
567
+ for (const pattern of patterns) if (pattern.startsWith("!")) negatives.push(pattern);
568
+ else positives.push(pattern);
569
+ return positives.some((pattern) => minimatch(target, pattern, { dot: true })) && negatives.every((pattern) => minimatch(target, pattern, { dot: true }));
570
+ }
571
+ //#endregion
572
+ //#region src/util/readJson.ts
573
+ /**
574
+ * Read and parse a JSON file.
575
+ *
576
+ * Throws a descriptive error when the file cannot be read or parsed, or when
577
+ * the parsed value is not an object.
578
+ *
579
+ * @param filePath Path to the JSON file
580
+ * @returns Parsed JSON object
581
+ * @throws If the file cannot be read, parsed, or is not an object
582
+ */
583
+ async function readJson(filePath) {
584
+ let content;
585
+ try {
586
+ content = await fs.readFile(filePath, "utf-8");
587
+ } catch (err) {
588
+ throw new Error(`JSON file at "${colors.bold(filePath)}" could not be read.`, { cause: err });
589
+ }
590
+ let json;
591
+ try {
592
+ json = JSON.parse(content);
593
+ } catch (err) {
594
+ throw new Error(`JSON file at "${colors.bold(filePath)}" could not be parsed.`, { cause: err });
595
+ }
596
+ if (typeof json !== "object" || json === null) throw new Error(`JSON file at "${colors.bold(filePath)}" does not contain a valid object.`);
597
+ return json;
598
+ }
599
+ //#endregion
600
+ //#region src/util/writeJson.ts
601
+ /**
602
+ * Write a JSON `payload` to `filePath`, formatting the content first.
603
+ *
604
+ * Ensures the directory exists and writes the formatted JSON.
605
+ *
606
+ * @param filePath Path to write the JSON file
607
+ * @param payload JSON-serializable object to write
608
+ * @returns Promise that resolves when the file is written
609
+ */
610
+ async function writeJson(filePath, payload) {
611
+ let content = JSON.stringify(payload, null, 2);
612
+ content = await formatFile(filePath, content);
613
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
614
+ await fs.writeFile(filePath, content);
615
+ }
616
+ //#endregion
617
+ //#region src/config/createPlugin.ts
618
+ /**
619
+ * Instantiate or invoke a plugin factory to produce a release plugin instance.
620
+ *
621
+ * Accepts class constructors, factory functions, tuple configurations, or
622
+ * existing plugin objects. Instantiates classes using `new` or invokes factory
623
+ * functions with options, validating that the resulting object satisfies the
624
+ * plugin structure.
625
+ *
626
+ * @param plugin A plugin constructor, factory function, tuple, or object
627
+ * @returns A validated release plugin instance or null
628
+ */
629
+ async function createPlugin(plugin) {
630
+ let options;
631
+ if (Array.isArray(plugin)) [plugin, options] = plugin;
632
+ if (typeof plugin === "function") plugin = isClass(plugin) ? new plugin(options) : await plugin(options);
633
+ if (plugin != null && typeof plugin === "object" && Object.hasOwn(plugin, "name") && typeof plugin.name === "string") return plugin;
634
+ return null;
635
+ }
636
+ //#endregion
637
+ //#region src/config/findReleaseRule.ts
638
+ /**
639
+ * Find the first release rule matching a release reference.
640
+ *
641
+ * Matches rules sequentially against the reference type and pattern.
642
+ *
643
+ * @param ref Release reference object
644
+ * @param rules Array of release rules to match against
645
+ * @returns The first matching release rule or `undefined`
646
+ */
647
+ function findReleaseRule(ref, rules) {
648
+ return rules.find((rule) => {
649
+ return (rule.type == null || rule.type === ref.type) && isMatch(ref.name, rule.pattern);
650
+ });
651
+ }
652
+ //#endregion
653
+ //#region src/config/isSemVer.ts
654
+ /**
655
+ * Determine whether a value is a valid Semantic Versioning string.
656
+ *
657
+ * Rejects non-string values, leading or trailing whitespace, and leading `v`
658
+ * prefixes. Validates the candidate string using `semver.parse`.
659
+ *
660
+ * @param version Candidate value to evaluate for SemVer compliance
661
+ * @returns `true` if `version` is a valid SemVer string, or `false` otherwise
662
+ */
663
+ function isSemVer(version) {
664
+ if (typeof version !== "string") return false;
665
+ if (version !== version.trim()) return false;
666
+ if (version.startsWith("v")) return false;
667
+ return semver.parse(version) != null;
668
+ }
669
+ //#endregion
670
+ //#region src/config/isSemVerGitTag.ts
671
+ /**
672
+ * Determine whether a tag string is a valid SemVer-style Git tag.
673
+ *
674
+ * Anchors `SEMVER_REGEX.source` for full-string matching and applies the
675
+ * repository's Git-tag acceptance rules.
676
+ *
677
+ * @param tag Tag string to validate
678
+ * @returns `true` if `tag` is accepted as a SemVer-style Git tag; otherwise `false`
679
+ */
680
+ function isSemVerGitTag(tag) {
681
+ const match = new RegExp(`^${SEMVER_REGEX.source}$`).exec(tag);
682
+ if (!match) return false;
683
+ const isScopedPackage = Boolean(match[1]);
684
+ const hasVersionPrefix = tag.startsWith("v");
685
+ return isScopedPackage || hasVersionPrefix;
686
+ }
687
+ //#endregion
688
+ //#region src/config/sanitizePrereleaseLabel.ts
689
+ /**
690
+ * Sanitize a string into a safe, SemVer-compliant prerelease label.
691
+ *
692
+ * Replaces sequences of non-alphanumeric characters with a single hyphen and
693
+ * removes leading or trailing hyphens.
694
+ *
695
+ * @param label Raw string to sanitize
696
+ * @returns Safe SemVer prerelease label
697
+ */
698
+ function sanitizePrereleaseLabel(label) {
699
+ return label.replace(/[^a-zA-Z0-9]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
700
+ }
701
+ //#endregion
702
+ //#region src/config/resolveReleaseChannel.ts
703
+ /**
704
+ * Resolve the release channel for a release context.
705
+ *
706
+ * Uses the release rule when `channel` is `boolean` or omitted. Sanitizes the
707
+ * reference name when enabling default channel resolution and interpolates
708
+ * `templateParams` into the result.
709
+ *
710
+ * @param options Options for resolving the release channel
711
+ * @returns Resolved release channel string or `undefined`
712
+ */
713
+ function resolveReleaseChannel(options) {
714
+ const { ref, rule, templateParams } = options;
715
+ let { channel } = options;
716
+ let resolved;
717
+ if (channel === true || channel == null) channel = rule?.releaseChannel ?? channel;
718
+ if (typeof channel === "string") resolved = channel;
719
+ else if (channel) resolved = sanitizePrereleaseLabel(ref.name);
720
+ if (typeof resolved === "string") resolved = interpolate(resolved, templateParams);
721
+ return resolved;
722
+ }
723
+ //#endregion
724
+ //#region src/config/resolveVersionQualifier.ts
725
+ /**
726
+ * Resolve the version qualifier for a release context.
727
+ *
728
+ * Uses the release rule when `qualifier` is `boolean` or omitted. Interpolates
729
+ * `templateParams` into `qualifier` and validates that the result forms a
730
+ * valid SemVer prerelease identifier.
731
+ *
732
+ * @param options Options for resolving the version qualifier
733
+ * @returns Resolved version qualifier string or `undefined`
734
+ * @throws If the resolved string is not a valid SemVer prerelease identifier
735
+ */
736
+ function resolveVersionQualifier(options) {
737
+ const { rule, templateParams } = options;
738
+ let { qualifier } = options;
739
+ let resolved;
740
+ if (qualifier === true || qualifier == null) qualifier = rule?.versionQualifier ?? qualifier;
741
+ if (typeof qualifier === "string") resolved = qualifier;
742
+ else if (qualifier) resolved = "";
743
+ if (typeof resolved === "string") resolved = interpolate(resolved, templateParams);
744
+ if (resolved && !isSemVer(`1.0.0-${resolved}.1`)) throw new Error(`The resolved version qualifier "${resolved}" is not a valid SemVer prerelease identifier.`);
745
+ return resolved;
746
+ }
747
+ //#endregion
748
+ //#region src/workflow/analysis/isCommitForPackage.ts
749
+ /**
750
+ * Test whether a commit modifies files in a package.
751
+ *
752
+ * @param pkg Package with an explicit file pattern or base directory
753
+ * @param commit Parsed commit containing changed file paths
754
+ * @returns `true` if any changed file matches the package pattern
755
+ */
756
+ function isCommitForPackage(pkg, commit) {
757
+ return commit.files.some((file) => {
758
+ const { location } = pkg;
759
+ return isMatch(file, pkg.files || path.join(location, "**/*"));
760
+ });
761
+ }
762
+ //#endregion
763
+ //#region src/workflow/analysis/deriveChangeReleases.ts
764
+ /**
765
+ * Analyze commit history to update release plans for packages.
766
+ *
767
+ * Maps commit `history` across package release `plans` to associate matching
768
+ * commits with their target packages. Calculates the release type for each
769
+ * plan based on classified `history` and applies overrides according to the
770
+ * provided `hint` or existing release priority.
771
+ *
772
+ * @param hint Release type override hint or default preference
773
+ * @param classifier Classifier function to determine commit release types
774
+ * @param plans List of release plans to analyze and update
775
+ * @param history Stream or iterable of git commits to process
776
+ * @returns Updated release plans with updated commit histories and release types
777
+ */
778
+ async function deriveChangeReleases(hint, classifier, plans, history) {
779
+ for await (const commit of history) plans = plans.map((plan) => {
780
+ if (!isCommitForPackage(plan.package, commit)) return plan;
781
+ return {
782
+ ...plan,
783
+ history: plan.history.concat(commit)
784
+ };
785
+ });
786
+ return plans.map((plan) => {
787
+ let { release } = plan;
788
+ let releaseType = deriveReleaseType(classifier, plan.history);
789
+ if (releaseType) switch (hint) {
790
+ case "major":
791
+ case "minor":
792
+ case "patch":
793
+ releaseType = hint;
794
+ break;
795
+ default: releaseType = pickPriorityReleaseType(release?.type, releaseType);
796
+ }
797
+ if (releaseType) release = {
798
+ ...release,
799
+ type: releaseType
800
+ };
801
+ return {
802
+ ...plan,
803
+ release
804
+ };
805
+ });
806
+ }
807
+ //#endregion
808
+ //#region src/workflow/analysis/deriveTransitionReleases.ts
809
+ /**
810
+ * Derive transition release types for release plans based on version qualifiers.
811
+ *
812
+ * Evaluates unreleased `plans` by parsing package `semver` strings and checking
813
+ * prerelease tags. Compares parsed version qualifiers against
814
+ * `versionQualifier` and assigns `major`, `minor`, or `patch` release types
815
+ * according to `hint`.
816
+ *
817
+ * @param hint Release type override hint to guide release classification
818
+ * @param versionQualifier Optional qualifier string to compare against prerelease tags
819
+ * @param plans List of release plans to analyze and update
820
+ * @returns Updated release plans with derived transition release types
821
+ */
822
+ function deriveTransitionReleases(hint, versionQualifier, plans) {
823
+ return plans.map((plan) => {
824
+ if (plan.release) return plan;
825
+ const parsed = semver.parse(plan.package.version);
826
+ if (!parsed) return plan;
827
+ const { major, minor, patch } = parsed;
828
+ const parsedVersionQualifier = extractVersionQualifier(parsed);
829
+ let releaseType;
830
+ let versionTransition;
831
+ switch (hint) {
832
+ case "major":
833
+ if (parsed.prerelease.length === 0) {
834
+ if (typeof versionQualifier === "string") releaseType = "major";
835
+ else if (major === 0 && (minor > 0 || patch > 0)) releaseType = "major";
836
+ } else if (minor === 0 && patch === 0 && parsedVersionQualifier !== versionQualifier) releaseType = "major";
837
+ break;
838
+ case "minor":
839
+ if (parsed.prerelease.length === 0) {
840
+ if (typeof versionQualifier === "string") releaseType = "minor";
841
+ } else if (minor > 0 && patch === 0 && parsedVersionQualifier !== versionQualifier) releaseType = "minor";
842
+ break;
843
+ case "patch":
844
+ if (parsed.prerelease.length === 0) {
845
+ if (typeof versionQualifier === "string") releaseType = "patch";
846
+ } else if (patch > 0 && parsedVersionQualifier !== versionQualifier) releaseType = "patch";
847
+ break;
848
+ default: if (parsed.prerelease.length === 0) {
849
+ if (major === 0 && (minor > 0 || patch > 0)) releaseType = "major";
850
+ } else if (minor === 0 && patch === 0 && parsedVersionQualifier !== versionQualifier) releaseType = "major";
851
+ else if (minor > 0 && patch === 0 && parsedVersionQualifier !== versionQualifier) releaseType = "minor";
852
+ else if (patch > 0 && parsedVersionQualifier !== versionQualifier) releaseType = "patch";
853
+ }
854
+ if (parsedVersionQualifier == null || parsedVersionQualifier !== "" && versionQualifier === "") versionTransition = "advance";
855
+ else versionTransition = "continue";
856
+ if (!releaseType) return plan;
857
+ return {
858
+ ...plan,
859
+ release: {
860
+ type: releaseType,
861
+ transition: versionTransition
862
+ }
863
+ };
864
+ });
865
+ }
866
+ //#endregion
867
+ //#region src/workflow/analysis/promotePrereleaseVersions.ts
868
+ /**
869
+ * Promote prerelease versions when they have no explicit release type.
870
+ *
871
+ * Analyzes prerelease and zero-major versions to determine an appropriate
872
+ * release type for graduation:
873
+ * - Prerelease versions are promoted based on their highest incremented component
874
+ * (patch, minor, or major)
875
+ * - Zero-major versions (0.y.z) are promoted to major
876
+ * - Stable versions (1.0.0+) remain unchanged
877
+ * - Plans with explicit releases are preserved as-is
878
+ *
879
+ * @param plans Release plans to analyze
880
+ * @returns Plans with inferred release types for prerelease versions
881
+ */
882
+ async function promotePrereleaseVersions(plans) {
883
+ return plans.map((plan) => {
884
+ if (plan.release) return plan;
885
+ if (!plan.package.tag) return plan;
886
+ const parsed = semver.parse(plan.package.version);
887
+ if (!parsed) return plan;
888
+ let type;
889
+ if (parsed.prerelease.length) {
890
+ if (parsed.patch !== 0) type = "patch";
891
+ else if (parsed.minor !== 0) type = "minor";
892
+ else if (parsed.major !== 0) type = "major";
893
+ else type = "major";
894
+ } else if (parsed.major === 0) type = "major";
895
+ if (type) return {
896
+ ...plan,
897
+ release: { type }
898
+ };
899
+ return plan;
900
+ });
901
+ }
902
+ //#endregion
903
+ //#region src/git/branch/getCurrentGitBranch.ts
904
+ /**
905
+ * Get the current Git branch name.
906
+ *
907
+ * Uses `execGit` to run `git symbolic-ref -q --short HEAD` in the provided
908
+ * working directory and trims the result. Returns an empty string when the
909
+ * repository is in a detached HEAD state.
910
+ *
911
+ * @param cwd The working directory to run the Git command in
912
+ * @returns The current branch name as a string
913
+ */
914
+ async function getCurrentGitBranch(cwd) {
915
+ return (await execGit(cwd, [
916
+ "symbolic-ref",
917
+ "-q",
918
+ "--short",
919
+ "HEAD"
920
+ ])).trim();
921
+ }
922
+ //#endregion
923
+ //#region src/git/commit/createGitCommit.ts
924
+ /**
925
+ * Stage all changes and create a git commit with the specified message.
926
+ *
927
+ * Validates the commit message and working directory status before staging
928
+ * all changes and executing the commit command.
929
+ *
930
+ * @param cwd The target directory path for executing git commands
931
+ * @param message The message to associate with the commit
932
+ * @returns A promise that resolves when the operation completes
933
+ */
934
+ async function createGitCommit(cwd, message) {
935
+ if (!message) return;
936
+ await execGit(cwd, ["add", "."]);
937
+ if (!(await execGit(cwd, ["status", "--porcelain"])).trim()) return;
938
+ await execGit(cwd, [
939
+ "commit",
940
+ "--message",
941
+ message
942
+ ]);
943
+ }
944
+ //#endregion
945
+ //#region src/git/commit/extractMentions.ts
946
+ var ALPHANUMERIC = "[a-zA-Z0-9]";
947
+ var SEPARATOR = "[-_]";
948
+ var USERNAME = `${ALPHANUMERIC}+(?:${SEPARATOR}+${ALPHANUMERIC}+)*`;
949
+ var EMAIL_LOCAL = "[a-zA-Z0-9._%+-]";
950
+ var DOMAIN_SUFFIX = "[a-zA-Z0-9.-]*\\.[a-zA-Z]{2,}";
951
+ var SCOPED_PACKAGE_SPEC_SUFFIX = `/${USERNAME}@[0-9]+\\.[0-9]+\\.[0-9]+`;
952
+ /**
953
+ * Extract unique mention handles from the input text string.
954
+ *
955
+ * Evaluates `text` against boundary rules to isolate valid handles while
956
+ * excluding email addresses, domain names, and scoped package specs, then
957
+ * de-duplicates the resulting handles.
958
+ *
959
+ * @param text The input string to parse for mentions
960
+ * @returns An array of unique mention handles
961
+ */
962
+ function extractMentions(text) {
963
+ if (!text) return [];
964
+ const regex = new RegExp(`(?<!${EMAIL_LOCAL})@(${USERNAME})\\b(?!${SEPARATOR}|${DOMAIN_SUFFIX}|${SCOPED_PACKAGE_SPEC_SUFFIX})`, "g");
965
+ const matches = text.matchAll(regex);
966
+ const mentions = new Set(matches.map((match) => match[1]));
967
+ return Array.from(mentions);
968
+ }
969
+ //#endregion
970
+ //#region src/cache/TTLCache.ts
971
+ /**
972
+ * A simple time-to-live cache that automatically evicts entries after a TTL.
973
+ *
974
+ * - Entries are removed automatically when their TTL expires.
975
+ * - Reading an entry resets its TTL to the original value.
976
+ * - Setting an existing key clears its previous timer and resets the TTL.
977
+ *
978
+ * @template K Type of cache keys
979
+ * @template V Type of cache values
980
+ */
981
+ var TTLCache = class {
982
+ constructor() {
983
+ this.cache = /* @__PURE__ */ new Map();
984
+ }
985
+ /**
986
+ * Store a value under `key` for `ttl` milliseconds.
987
+ *
988
+ * If the key already exists its previous timer is cleared and the TTL is reset.
989
+ *
990
+ * @param key Cache key
991
+ * @param value Value to store
992
+ * @param ttl Time to live in milliseconds (default: 60_000)
993
+ */
994
+ set(key, value, ttl = 6e4) {
995
+ const ref = this.cache.get(key);
996
+ if (ref) clearTimeout(ref.timer);
997
+ const timer = setTimeout(() => {
998
+ this.cache.delete(key);
999
+ }, ttl).unref();
1000
+ this.cache.set(key, {
1001
+ value,
1002
+ timer,
1003
+ ttl
1004
+ });
1005
+ }
1006
+ /**
1007
+ * Retrieve the value for `key`, or `undefined` if not present.
1008
+ *
1009
+ * Reading an entry resets its TTL to the original `ttl` provided when it was set.
1010
+ *
1011
+ * @param key Cache key
1012
+ * @returns The stored value or `undefined` if not present
1013
+ */
1014
+ get(key) {
1015
+ const ref = this.cache.get(key);
1016
+ if (!ref) return void 0;
1017
+ this.set(key, ref.value, ref.ttl);
1018
+ return ref.value;
1019
+ }
1020
+ /**
1021
+ * Check whether `key` exists in the cache.
1022
+ *
1023
+ * @param key Cache key
1024
+ * @returns `true` if present; otherwise `false`
1025
+ */
1026
+ has(key) {
1027
+ return this.cache.has(key);
1028
+ }
1029
+ /**
1030
+ * Remove `key` from the cache and clear its eviction timer.
1031
+ *
1032
+ * @param key Cache key
1033
+ * @returns `true` if the key was present and removed; otherwise `false`
1034
+ */
1035
+ delete(key) {
1036
+ const ref = this.cache.get(key);
1037
+ if (!ref) return false;
1038
+ clearTimeout(ref.timer);
1039
+ return this.cache.delete(key);
1040
+ }
1041
+ /**
1042
+ * Clear all entries and their timers.
1043
+ */
1044
+ clear() {
1045
+ for (const { timer } of this.cache.values()) clearTimeout(timer);
1046
+ this.cache.clear();
1047
+ }
1048
+ };
1049
+ //#endregion
1050
+ //#region src/git/commit/parseGitCommit.ts
1051
+ var BREAKING_HEADER_REGEX = /^([\w-]+)(?:\(([^)]+)\))?!: (.*)$/;
1052
+ var BREAKING_MARKERS = ["BREAKING CHANGE", "BREAKING-CHANGE"];
1053
+ /**
1054
+ * Parse a git log entry into a structured commit object.
1055
+ *
1056
+ * Combines the commit subject and body, extracts conventional commit metadata
1057
+ * using custom trailer markers and breaking header patterns, and normalizes
1058
+ * dates to ISO format strings.
1059
+ *
1060
+ * @param entry The raw git log entry to parse
1061
+ * @param markers Optional array of custom trailer marker strings
1062
+ * @returns A structured commit object containing parsed details, notes, and mentions
1063
+ */
1064
+ async function parseGitCommit(entry, markers = []) {
1065
+ const message = [entry.subject, entry.body].filter(Boolean).join("\n\n");
1066
+ const commit = new CommitParser({
1067
+ breakingHeaderPattern: BREAKING_HEADER_REGEX,
1068
+ noteKeywords: [],
1069
+ notesPattern: () => buildTrailerPattern(BREAKING_MARKERS.concat(markers))
1070
+ }).parse(message);
1071
+ const notes = [];
1072
+ const trailers = [];
1073
+ for (const note of commit.notes) {
1074
+ if (BREAKING_MARKERS.includes(note.title.toUpperCase())) notes.push(note);
1075
+ trailers.push({
1076
+ key: note.title,
1077
+ value: note.text
1078
+ });
1079
+ }
1080
+ if (notes.length === 0 && BREAKING_HEADER_REGEX.test(commit.header)) {
1081
+ const note = {
1082
+ title: "BREAKING CHANGE",
1083
+ text: commit.subject
1084
+ };
1085
+ notes.push(note);
1086
+ trailers.push({
1087
+ key: note.title,
1088
+ value: note.text
1089
+ });
1090
+ }
1091
+ const mentions = extractMentions(message);
1092
+ return {
1093
+ ...commit,
1094
+ hash: entry.hash,
1095
+ parent: entry.parent,
1096
+ authorDate: new Date(entry.authorDate).toISOString(),
1097
+ committerDate: new Date(entry.committerDate).toISOString(),
1098
+ type: commit.type?.toLowerCase() || null,
1099
+ scope: commit.scope || null,
1100
+ subject: commit.subject || null,
1101
+ header: commit.header,
1102
+ body: commit.body,
1103
+ footer: commit.footer,
1104
+ notes,
1105
+ mentions,
1106
+ trailers,
1107
+ files: entry.files
1108
+ };
1109
+ }
1110
+ //#endregion
1111
+ //#region src/git/commit/parseGitPrettyFormat.ts
1112
+ /**
1113
+ * Field separator used in the git pretty format to produce a single-line
1114
+ *, machine-parseable record.
1115
+ */
1116
+ var GIT_PRETTY_FIELD_SEPARATOR = "";
1117
+ /**
1118
+ * Pretty format string passed to `git log --pretty=format:`. Produces seven
1119
+ * fields separated by `GIT_PRETTY_FIELD_SEPARATOR`:
1120
+ * hash, parents, author date, committer date, subject, body, files.
1121
+ */
1122
+ var GIT_PRETTY_FORMAT = [
1123
+ "%H",
1124
+ "%P",
1125
+ "%aI",
1126
+ "%cI",
1127
+ "%s",
1128
+ "%b",
1129
+ ""
1130
+ ].join("");
1131
+ /**
1132
+ * Parse a single line produced by `git log --pretty=format:${GIT_PRETTY_FORMAT}`.
1133
+ *
1134
+ * The input is expected to contain seven fields separated by
1135
+ * `GIT_PRETTY_FIELD_SEPARATOR`:
1136
+ * 1. `hash` (commit hash)
1137
+ * 2. `parent` (space-separated parent hashes)
1138
+ * 3. `authorDate` (ISO 8601)
1139
+ * 4. `committerDate` (ISO 8601)
1140
+ * 5. `subject`
1141
+ * 6. `body`
1142
+ * 7. `files` (newline-separated list)
1143
+ *
1144
+ * The function trims fields, converts parent hashes into an array, normalizes
1145
+ * dates to ISO strings, and splits `files` into an array. Missing optional
1146
+ * fields are normalized to sensible defaults.
1147
+ *
1148
+ * @param raw Raw pretty-format string produced by git
1149
+ * @returns Parsed `GitLogEntry` with `hash`, `parent`, `authorDate`, `committerDate`, `subject`, `body`, and `files`
1150
+ * @throws If required fields (hash, authorDate, committerDate, subject) are missing or malformed
1151
+ */
1152
+ function parseGitPrettyFormat(raw) {
1153
+ let [hash, parentHashes, authorDate, committerDate, subject, body, files] = raw.split("");
1154
+ hash = hash?.trim();
1155
+ parentHashes = parentHashes?.trim();
1156
+ authorDate = authorDate?.trim();
1157
+ committerDate = committerDate?.trim();
1158
+ subject = subject?.trim();
1159
+ body = body?.trim();
1160
+ files = files?.trim();
1161
+ if (!hash || !authorDate || !committerDate || typeof subject !== "string") throw new Error(`The input "${colors.bold(raw)}" is not in the expected pretty format.`);
1162
+ return {
1163
+ hash,
1164
+ parent: parentHashes ? parentHashes.split(/\s+/) : [],
1165
+ authorDate: new Date(authorDate).toISOString(),
1166
+ committerDate: new Date(committerDate).toISOString(),
1167
+ subject,
1168
+ body: body ?? "",
1169
+ files: files ? files.split("\n") : []
1170
+ };
1171
+ }
1172
+ //#endregion
1173
+ //#region src/git/commit/getParsedGitCommit.ts
1174
+ var cache = new TTLCache();
1175
+ /**
1176
+ * Retrieve and parse a git commit by its reference.
1177
+ *
1178
+ * Fetches the raw git log entry for the specified `ref`, checking the local cache
1179
+ * prior to parsing missing entries.
1180
+ *
1181
+ * @param cwd Current working directory path
1182
+ * @param ref Git reference to fetch
1183
+ * @param markers Optional array of custom trailer marker strings
1184
+ * @returns Structured commit object
1185
+ */
1186
+ async function getParsedGitCommit(cwd, ref, markers = []) {
1187
+ const entry = parseGitPrettyFormat(await execGit(cwd, [
1188
+ "log",
1189
+ "-1",
1190
+ ref,
1191
+ "--name-only",
1192
+ `--pretty=format:${GIT_PRETTY_FORMAT}`
1193
+ ]));
1194
+ const key = `${entry.hash}:${entry.parent}:${markers}`;
1195
+ const cached = cache.get(key);
1196
+ if (cached) return cached;
1197
+ const parsed = await parseGitCommit(entry, markers);
1198
+ cache.set(key, parsed);
1199
+ return parsed;
1200
+ }
1201
+ //#endregion
1202
+ //#region src/git/commit/getCurrentGitCommit.ts
1203
+ /**
1204
+ * Resolve the current `HEAD` commit in the repository.
1205
+ *
1206
+ * @param cwd Repository working directory path
1207
+ * @param markers Optional array of custom trailer marker strings
1208
+ * @returns Parsed commit object for the current `HEAD` commit
1209
+ */
1210
+ function getCurrentGitCommit(cwd, markers = []) {
1211
+ return getParsedGitCommit(cwd, "HEAD", markers);
1212
+ }
1213
+ //#endregion
1214
+ //#region src/git/history/countGitHistory.ts
1215
+ /**
1216
+ * Count mainline commits reachable from a given reference.
1217
+ *
1218
+ * Uses `git rev-list --count --first-parent` to calculate the length of the
1219
+ * primary history trunk, excluding commits introduced by side-branch merges.
1220
+ *
1221
+ * @param cwd Repository working directory
1222
+ * @param ref Commit reference to count from (defaults to `HEAD`)
1223
+ * @returns Number of commits along the primary branch line up to `ref`
1224
+ */
1225
+ async function countGitHistory(cwd, ref = "HEAD") {
1226
+ const stdout = await execGit(cwd, [
1227
+ "rev-list",
1228
+ "--count",
1229
+ "--first-parent",
1230
+ ref
1231
+ ]);
1232
+ return Number.parseInt(stdout.trim(), 10);
1233
+ }
1234
+ //#endregion
1235
+ //#region src/git/repository/isGitShallowRepository.ts
1236
+ /**
1237
+ * Determine whether the repository at `cwd` is a shallow clone.
1238
+ *
1239
+ * Runs `git rev-parse --is-shallow-repository` to detect shallow clones.
1240
+ * Useful before operations that require full history.
1241
+ *
1242
+ * @param cwd Repository working directory
1243
+ * @returns `true` if shallow, `false` if full clone, or `null` on error
1244
+ */
1245
+ async function isGitShallowRepository(cwd) {
1246
+ return (await execGit(cwd, ["rev-parse", "--is-shallow-repository"])).trim() === "true";
1247
+ }
1248
+ //#endregion
1249
+ //#region src/git/repository/withShallowLock.ts
1250
+ var lockQueue = /* @__PURE__ */ new Map();
1251
+ var context = new AsyncLocalStorage();
1252
+ /**
1253
+ * Serialize access to a shallow Git repository while running a callback.
1254
+ *
1255
+ * If `cwd` is a shallow clone, callers from different async contexts are
1256
+ * executed one at a time; nested calls within the same async context run
1257
+ * immediately without waiting. If the repository becomes non-shallow before
1258
+ * a queued turn runs, downstream waiters are released early.
1259
+ *
1260
+ * @param cwd Repository working directory path string
1261
+ * @param callback Function to execute while the lock is held
1262
+ * @returns Promise resolving to the result of `callback`
1263
+ */
1264
+ async function withShallowLock(cwd, callback) {
1265
+ if (!await isGitShallowRepository(cwd)) return callback();
1266
+ const active = context.getStore();
1267
+ if (active?.has(cwd)) return callback();
1268
+ const { promise, resolve } = Promise.withResolvers();
1269
+ const previous = lockQueue.get(cwd) ?? Promise.resolve();
1270
+ const queued = previous.then(() => promise);
1271
+ lockQueue.set(cwd, queued);
1272
+ await previous;
1273
+ if (!await isGitShallowRepository(cwd)) resolve();
1274
+ try {
1275
+ return await context.run(new Set(active).add(cwd), callback);
1276
+ } finally {
1277
+ resolve();
1278
+ if (lockQueue.get(cwd) === queued) lockQueue.delete(cwd);
1279
+ }
1280
+ }
1281
+ //#endregion
1282
+ //#region src/git/revision/isGitAncestor.ts
1283
+ /**
1284
+ * Determine whether `ancestor` is an ancestor of `descendant`.
1285
+ *
1286
+ * Runs `git merge-base --is-ancestor <ancestor> <descendant>` in the repository at `cwd`.
1287
+ * Resolves to `true` if `ancestor` is an ancestor, `false` if not.
1288
+ * Rethrows errors for invalid refs or other failures.
1289
+ *
1290
+ * @param cwd Repository working directory
1291
+ * @param ancestor Candidate ancestor ref
1292
+ * @param descendant Candidate descendant ref
1293
+ * @returns Resolves to `true` if `ancestor` is an ancestor of `descendant`, `false` otherwise
1294
+ * @throws If a ref is invalid or the Git command fails
1295
+ */
1296
+ function isGitAncestor(cwd, ancestor, descendant) {
1297
+ return execGit(cwd, [
1298
+ "merge-base",
1299
+ "--is-ancestor",
1300
+ ancestor,
1301
+ descendant
1302
+ ]).then(() => true).catch((err) => {
1303
+ if (err?.code === 1) return false;
1304
+ throw err;
1305
+ });
1306
+ }
1307
+ //#endregion
1308
+ //#region src/git/revision/resolveGitRevision.ts
1309
+ /**
1310
+ * Resolve a Git revision or commit-ish expression to its full commit hash.
1311
+ *
1312
+ * Runs `git rev-parse --verify <revision>^{commit}` under the hood. Peels annotated
1313
+ * tags, branches, short SHAs, and relative expressions down to a verified commit object.
1314
+ *
1315
+ * @param cwd The repository working directory
1316
+ * @param revision The Git revision or expression to resolve
1317
+ * @returns A promise that resolves to the full, trimmed commit SHA-1 string
1318
+ */
1319
+ async function resolveGitRevision(cwd, revision) {
1320
+ return (await execGit(cwd, [
1321
+ "rev-parse",
1322
+ "--verify",
1323
+ `${revision}^{commit}`
1324
+ ])).trim();
1325
+ }
1326
+ //#endregion
1327
+ //#region src/git/history/expandGitHistory.ts
1328
+ /**
1329
+ * Deepen a shallow clone so additional commits become available.
1330
+ *
1331
+ * Attempts a single `--shallow-since` fetch to reach `until` (if provided),
1332
+ * otherwise deepens by `pageSize`, accounting for existing depth when `from`
1333
+ * is supplied. Operation is serialized to avoid concurrent deepens.
1334
+ *
1335
+ * @param cwd Repository working directory
1336
+ * @param options Options: { pageSize?, from?, until? }
1337
+ * @returns true if history was deepened or already sufficient, otherwise false
1338
+ */
1339
+ async function expandGitHistory(cwd, options = {}) {
1340
+ if (!await isGitShallowRepository(cwd)) return false;
1341
+ return withShallowLock(cwd, async () => {
1342
+ const { until } = options;
1343
+ let { from } = options;
1344
+ let { pageSize = 50 } = options;
1345
+ if (until) {
1346
+ if (await isGitAncestor(cwd, until, "HEAD")) return true;
1347
+ const commitDate = (await execGit(cwd, [
1348
+ "show",
1349
+ "-s",
1350
+ "--format=%cI",
1351
+ `${until}^{commit}`
1352
+ ])).trim();
1353
+ try {
1354
+ await execGit(cwd, [
1355
+ "-c",
1356
+ "fetch.negotiationAlgorithm=skipping",
1357
+ "fetch",
1358
+ `--shallow-since=${commitDate}`,
1359
+ "--update-shallow",
1360
+ "--filter=blob:none"
1361
+ ]);
1362
+ return true;
1363
+ } catch {}
1364
+ }
1365
+ if (from) {
1366
+ from = await resolveGitRevision(cwd, from);
1367
+ const depth = await countGitHistory(cwd, from);
1368
+ if (depth > pageSize) return true;
1369
+ pageSize -= depth - 1;
1370
+ }
1371
+ try {
1372
+ await execGit(cwd, [
1373
+ "-c",
1374
+ "fetch.negotiationAlgorithm=skipping",
1375
+ "fetch",
1376
+ `--deepen=${pageSize}`,
1377
+ "--update-shallow",
1378
+ "--filter=blob:none",
1379
+ ...from && !await isGitAncestor(cwd, from, "HEAD") ? [
1380
+ "origin",
1381
+ from,
1382
+ "HEAD"
1383
+ ] : []
1384
+ ]);
1385
+ return true;
1386
+ } catch {
1387
+ return false;
1388
+ }
1389
+ });
1390
+ }
1391
+ //#endregion
1392
+ //#region src/git/revision/detectGitRelationship.ts
1393
+ var GIT_REL_FLAGS = {
1394
+ NONE: 0,
1395
+ IS_ANCESTOR: 1,
1396
+ IS_DESCENDANT: 2,
1397
+ IS_EQUAL: 3
1398
+ };
1399
+ /**
1400
+ * Determine the relationship between two git refs.
1401
+ *
1402
+ * Runs `git merge-base --is-ancestor` in both directions and returns a
1403
+ * numeric bitmask using `GIT_REL_FLAGS`. A successful check (exit code 0)
1404
+ * indicates an ancestor relationship; non-zero exit is treated as "not ancestor".
1405
+ *
1406
+ * @param cwd Repository working directory
1407
+ * @param refA First ref (candidate ancestor)
1408
+ * @param refB Second ref (candidate descendant)
1409
+ * @returns Bitmask of type `GitRelFlags`
1410
+ */
1411
+ async function detectGitRelationship(cwd, refA, refB) {
1412
+ let flags = GIT_REL_FLAGS.NONE;
1413
+ const [aIsAncestor, bIsAncestor] = await Promise.all([isGitAncestor(cwd, refA, refB), isGitAncestor(cwd, refB, refA)]);
1414
+ if (aIsAncestor) flags |= GIT_REL_FLAGS.IS_ANCESTOR;
1415
+ if (bIsAncestor) flags |= GIT_REL_FLAGS.IS_DESCENDANT;
1416
+ return flags;
1417
+ }
1418
+ //#endregion
1419
+ //#region src/git/history/mergeGitHistory.ts
1420
+ /**
1421
+ * Merge two newest-first commit lists into a single deduplicated newest-first list.
1422
+ *
1423
+ * Compares commits by hash, uses git relationship (ancestor/descendant) when needed,
1424
+ * and falls back to committerDate for unrelated commits.
1425
+ *
1426
+ * @param cwd Repository working directory used for relationship checks
1427
+ * @param a Commits from the first source (newest-first)
1428
+ * @param b Commits from the second source (newest-first)
1429
+ * @returns Merged commits in newest-first order with duplicates removed
1430
+ */
1431
+ async function mergeGitHistory(cwd, a, b) {
1432
+ const merged = [];
1433
+ const a2 = [...a];
1434
+ const b2 = [...b];
1435
+ let i = a2.shift();
1436
+ let j = b2.shift();
1437
+ while (i && j) switch (i.hash === j.hash ? GIT_REL_FLAGS.IS_EQUAL : await detectGitRelationship(cwd, i.hash, j.hash)) {
1438
+ case GIT_REL_FLAGS.IS_EQUAL:
1439
+ merged.push(i);
1440
+ i = a2.shift();
1441
+ j = b2.shift();
1442
+ break;
1443
+ case GIT_REL_FLAGS.IS_ANCESTOR:
1444
+ merged.push(j);
1445
+ j = b2.shift();
1446
+ break;
1447
+ case GIT_REL_FLAGS.IS_DESCENDANT:
1448
+ merged.push(i);
1449
+ i = a2.shift();
1450
+ break;
1451
+ case GIT_REL_FLAGS.NONE: if (i.committerDate < j.committerDate) {
1452
+ merged.push(j);
1453
+ j = b2.shift();
1454
+ } else {
1455
+ merged.push(i);
1456
+ i = a2.shift();
1457
+ }
1458
+ }
1459
+ if (i) merged.push(i);
1460
+ if (j) merged.push(j);
1461
+ return merged.concat(a2).concat(b2);
1462
+ }
1463
+ //#endregion
1464
+ //#region src/git/history/restoreFullGitHistory.ts
1465
+ /**
1466
+ * Convert a shallow clone into a full clone by fetching additional history.
1467
+ *
1468
+ * Runs `git fetch --unshallow`. Returns `true` when the operation succeeds
1469
+ * and `false` on error.
1470
+ *
1471
+ * @param cwd Repository working directory
1472
+ * @returns `true` when the operation succeeded, otherwise `false`
1473
+ */
1474
+ function restoreFullGitHistory(cwd) {
1475
+ return execGit(cwd, ["fetch", "--unshallow"]).then(() => true).catch(() => false);
1476
+ }
1477
+ //#endregion
1478
+ //#region src/git/history/showGitHistory.ts
1479
+ /**
1480
+ * Yield commit SHAs from repository history in paginated order.
1481
+ *
1482
+ * Ensures commits are available via `expandGitHistory`, resolves `until` to a
1483
+ * commit id, and pages from `from` toward `until`, yielding each commit SHA.
1484
+ * If a git command fails the generator ends silently.
1485
+ *
1486
+ * @param cwd Repository working directory
1487
+ * @param options Supports `from`, `until`, `pageSize`, and `filePath`
1488
+ * @yields Commit SHA strings in paginated order
1489
+ */
1490
+ async function* showGitHistory(cwd, options = {}) {
1491
+ try {
1492
+ const { filePath, pageSize = 50 } = options;
1493
+ let from = options.from || "HEAD";
1494
+ let until = options.until || void 0;
1495
+ if (until) until = await resolveGitRevision(cwd, until);
1496
+ while (true) {
1497
+ await expandGitHistory(cwd, {
1498
+ from,
1499
+ until,
1500
+ pageSize
1501
+ });
1502
+ const args = [
1503
+ "rev-list",
1504
+ `--max-count=${pageSize}`,
1505
+ from
1506
+ ];
1507
+ if (until) args.push(`^${until}`);
1508
+ if (filePath) args.push("--", ...(Array.isArray(filePath) ? filePath : [filePath]).filter(Boolean));
1509
+ const list = (await execGit(cwd, args)).trim().split("\n").filter(Boolean);
1510
+ for (const item of list.slice(0, -1)) yield item;
1511
+ const tail = list.at(-1);
1512
+ if (!tail) return;
1513
+ if (tail === from) {
1514
+ yield tail;
1515
+ from = `${tail}^`;
1516
+ from = await resolveGitRevision(cwd, from);
1517
+ } else from = tail;
1518
+ }
1519
+ } catch {}
1520
+ }
1521
+ //#endregion
1522
+ //#region src/git/history/showParsedGitHistory.ts
1523
+ /**
1524
+ * Yield parsed commits sequentially from repository history.
1525
+ *
1526
+ * Fetches commits using `showGitHistory` and parses each commit with
1527
+ * `getParsedGitCommit`. Yields successfully parsed `GitCommit` objects on demand
1528
+ * and skips unparsable commits.
1529
+ *
1530
+ * @param cwd Repository working directory path
1531
+ * @param options Filter and pagination options passed to `showGitHistory`
1532
+ * @yields Parsed `GitCommit` objects in historical order
1533
+ */
1534
+ async function* showParsedGitHistory(cwd, options) {
1535
+ for await (const commit of showGitHistory(cwd, options)) try {
1536
+ yield await getParsedGitCommit(cwd, commit);
1537
+ } catch {}
1538
+ }
1539
+ //#endregion
1540
+ //#region src/git/repository/getGitConfigValue.ts
1541
+ /**
1542
+ * Get a local git configuration value for `key` in the repository at `cwd`.
1543
+ *
1544
+ * Returns the config value when present; otherwise `undefined`.
1545
+ *
1546
+ * @param cwd Repository working directory
1547
+ * @param key Git config key to read
1548
+ * @returns The config value or `undefined` if not set
1549
+ */
1550
+ async function getGitConfigValue(cwd, key) {
1551
+ try {
1552
+ const value = (await execGit(cwd, [
1553
+ "config",
1554
+ "--local",
1555
+ "--get",
1556
+ key
1557
+ ])).trim();
1558
+ return value ? value : void 0;
1559
+ } catch {
1560
+ return;
1561
+ }
1562
+ }
1563
+ //#endregion
1564
+ //#region src/git/repository/ensureGitUserConfig.ts
1565
+ /**
1566
+ * Ensure Git user configuration is set and return a cleanup handle.
1567
+ *
1568
+ * Checks the existing `user.name` and `user.email` configuration for the given
1569
+ * working directory. Updates the configuration if either value is missing and
1570
+ * returns an `AsyncDisposable` resource that restores the original state upon
1571
+ * disposal.
1572
+ *
1573
+ * @param cwd Working directory path in which to check and set Git configuration
1574
+ * @param user Git author details containing name and email
1575
+ * @returns Async disposable cleanup object if updated, or undefined if already set
1576
+ */
1577
+ async function ensureGitUserConfig(cwd, user) {
1578
+ const initialName = await getGitConfigValue(cwd, "user.name");
1579
+ const initialEmail = await getGitConfigValue(cwd, "user.email");
1580
+ if (initialName && initialEmail) return;
1581
+ await execGit(cwd, [
1582
+ "config",
1583
+ "user.name",
1584
+ user.name
1585
+ ]);
1586
+ await execGit(cwd, [
1587
+ "config",
1588
+ "user.email",
1589
+ user.email
1590
+ ]);
1591
+ return { async [Symbol.asyncDispose]() {
1592
+ if (initialName) await execGit(cwd, [
1593
+ "config",
1594
+ "user.name",
1595
+ initialName
1596
+ ]);
1597
+ else await execGit(cwd, [
1598
+ "config",
1599
+ "--unset",
1600
+ "user.name"
1601
+ ]);
1602
+ if (initialEmail) await execGit(cwd, [
1603
+ "config",
1604
+ "user.email",
1605
+ initialEmail
1606
+ ]);
1607
+ else await execGit(cwd, [
1608
+ "config",
1609
+ "--unset",
1610
+ "user.email"
1611
+ ]);
1612
+ } };
1613
+ }
1614
+ //#endregion
1615
+ //#region src/git/repository/getGitRemote.ts
1616
+ /**
1617
+ * Get the URL for the named remote (defaults to `origin`).
1618
+ *
1619
+ * @param cwd Repository working directory
1620
+ * @param remoteName Remote name (defaults to `'origin'`)
1621
+ * @returns Remote URL string or `null` when unavailable
1622
+ */
1623
+ function getGitRemote(cwd, remoteName = "origin") {
1624
+ return execGit(cwd, [
1625
+ "remote",
1626
+ "get-url",
1627
+ remoteName
1628
+ ]).then((stdout) => stdout.trim()).catch(() => null);
1629
+ }
1630
+ //#endregion
1631
+ //#region src/git/repository/pushGitChanges.ts
1632
+ /**
1633
+ * Push a branch and optional tags to the `origin` remote using an atomic push.
1634
+ *
1635
+ * @param cwd Repository working directory
1636
+ * @param branch Branch name to push
1637
+ * @param additionalTags Optional list of tag names to push alongside the branch
1638
+ * @returns Promise that resolves when the push completes
1639
+ */
1640
+ async function pushGitChanges(cwd, branch, ...additionalTags) {
1641
+ await execGit(cwd, [
1642
+ "push",
1643
+ "origin",
1644
+ ...compact([branch, ...additionalTags]),
1645
+ "--atomic",
1646
+ "--no-verify"
1647
+ ]);
1648
+ }
1649
+ //#endregion
1650
+ //#region src/git/repository/resolveGitRepository.ts
1651
+ /**
1652
+ * Resolve Git repository host, owner, and project metadata from the `origin` remote URL.
1653
+ *
1654
+ * @param cwd Repository working directory
1655
+ * @returns Promise that resolves to a `GitRepository` object, or `null` when unavailable
1656
+ */
1657
+ async function resolveGitRepository(cwd) {
1658
+ const origin = await getGitRemote(cwd);
1659
+ if (!origin) return null;
1660
+ const info = GitHost.fromUrl(origin);
1661
+ if (info && typeof info.type === "string" && typeof info.user === "string" && typeof info.project === "string") return {
1662
+ host: info.type,
1663
+ owner: info.user,
1664
+ repo: info.project,
1665
+ url: info.browse()
1666
+ };
1667
+ return null;
1668
+ }
1669
+ //#endregion
1670
+ //#region src/git/revision/readGitFile.ts
1671
+ /**
1672
+ * Read a file's contents from a specific Git revision.
1673
+ *
1674
+ * Runs `git show <ref>:<filePath>` and returns the command output as a
1675
+ * string. If the file does not exist at the given revision or the Git
1676
+ * command fails for any reason, the function returns `null`.
1677
+ *
1678
+ * The returned string is the raw file contents as emitted by Git; callers
1679
+ * that need binary-safe handling should decode or process the bytes
1680
+ * accordingly. This function intentionally swallows Git errors and signals
1681
+ * absence via a `null` result rather than throwing.
1682
+ *
1683
+ * @param cwd Repository working directory
1684
+ * @param ref Commit-ish reference (commit SHA, tag, or branch) to read from
1685
+ * @param filePath Path to the file relative to the repository root
1686
+ * @returns File contents as a string, or `null` if the file is unavailable at the ref
1687
+ */
1688
+ function readGitFile(cwd, ref, filePath) {
1689
+ return execGit(cwd, ["show", `${ref}:${filePath}`]).catch(() => null);
1690
+ }
1691
+ //#endregion
1692
+ //#region src/git/tag/createGitTag.ts
1693
+ /**
1694
+ * Create a git tag in the repository at `cwd`.
1695
+ *
1696
+ * Creates an annotated tag when `message` is provided.
1697
+ *
1698
+ * @param cwd Repository working directory
1699
+ * @param tag Tag name to create
1700
+ * @param message Optional tag message (creates an annotated tag when present)
1701
+ * @returns Promise that resolves when the tag is created
1702
+ */
1703
+ async function createGitTag(cwd, tag, message) {
1704
+ await execGit(cwd, ["tag", ...message ? [
1705
+ "-a",
1706
+ tag,
1707
+ "-m",
1708
+ message,
1709
+ "--cleanup=whitespace"
1710
+ ] : [tag]]);
1711
+ }
1712
+ //#endregion
1713
+ //#region src/git/tag/deleteGitTag.ts
1714
+ /**
1715
+ * Delete a local git tag in the repository at `cwd`.
1716
+ *
1717
+ * @param cwd Repository working directory
1718
+ * @param tag Tag name to delete
1719
+ * @returns `true` when deletion succeeded, otherwise `false`
1720
+ */
1721
+ function deleteGitTag(cwd, tag) {
1722
+ return execGit(cwd, [
1723
+ "tag",
1724
+ "-d",
1725
+ tag
1726
+ ]).then(() => true).catch(() => false);
1727
+ }
1728
+ //#endregion
1729
+ //#region src/git/tag/isGitTagPresent.ts
1730
+ /**
1731
+ * Determine whether a specific git tag exists locally in the repository.
1732
+ *
1733
+ * @param cwd Working directory for the git command
1734
+ * @param tag Name of the tag to evaluate
1735
+ * @returns True if the tag reference exists locally, false otherwise
1736
+ */
1737
+ function isGitTagPresent(cwd, tag) {
1738
+ return resolveGitRevision(cwd, `refs/tags/${tag}`).then(() => true).catch(() => false);
1739
+ }
1740
+ //#endregion
1741
+ //#region src/git/tag/ensureGitTag.ts
1742
+ var MIN_HISTORY_DEPTH = 2;
1743
+ var ORIGIN_NOT_REPO = `fatal: 'origin' does not appear to be a git repository`;
1744
+ var REMOTE_REF_NOT_FOUND = `fatal: couldn't find remote ref`;
1745
+ /**
1746
+ * Ensure a tag exists locally, fetching it shallowly from `origin` if needed.
1747
+ *
1748
+ * Acquires a shallow-fetch lock, verifies local presence and history depth,
1749
+ * attempts a shallow fetch of `refs/tags/<tag>` when required, and removes a
1750
+ * local tag if the remote reports the tag is missing.
1751
+ *
1752
+ * @param cwd Working directory
1753
+ * @param tag Tag name (for example `v1.2.0`)
1754
+ * @returns `true` if the tag is present or was fetched; otherwise `false`
1755
+ */
1756
+ function ensureGitTag(cwd, tag) {
1757
+ return withShallowLock(cwd, async () => {
1758
+ const tagRef = `refs/tags/${tag}`;
1759
+ if (await isGitTagPresent(cwd, tag) && await countGitHistory(cwd, tagRef) >= MIN_HISTORY_DEPTH) return true;
1760
+ try {
1761
+ await execGit(cwd, [
1762
+ "fetch",
1763
+ "origin",
1764
+ `${tagRef}:${tagRef}`,
1765
+ `--depth=${MIN_HISTORY_DEPTH}`,
1766
+ "--update-shallow",
1767
+ "--force"
1768
+ ]);
1769
+ return true;
1770
+ } catch (err) {
1771
+ const errorMessage = err?.message;
1772
+ if (errorMessage?.includes(ORIGIN_NOT_REPO)) return await isGitTagPresent(cwd, tag);
1773
+ if (errorMessage?.includes(REMOTE_REF_NOT_FOUND)) {
1774
+ if (await isGitTagPresent(cwd, tag)) await deleteGitTag(cwd, tag);
1775
+ }
1776
+ }
1777
+ return false;
1778
+ });
1779
+ }
1780
+ //#endregion
1781
+ //#region src/git/tag/generateGitTagName.ts
1782
+ function generateGitTagName(entry, name, version) {
1783
+ if (!version) return null;
1784
+ if (entry) return `v${version}`;
1785
+ if (!name) throw new Error("Package name is required to build a tag name.");
1786
+ return `${name}@${version}`;
1787
+ }
1788
+ //#endregion
1789
+ //#region src/git/tag/getCurrentGitTag.ts
1790
+ /**
1791
+ * Get the tag name that exactly matches the current `HEAD`, if any.
1792
+ *
1793
+ * @param cwd Repository working directory
1794
+ * @returns Tag name or `null` when no exact tag matches HEAD
1795
+ */
1796
+ async function getCurrentGitTag(cwd) {
1797
+ try {
1798
+ const tag = (await execGit(cwd, [
1799
+ "describe",
1800
+ "--tags",
1801
+ "--exact-match"
1802
+ ])).trim();
1803
+ /* istanbul ignore next */
1804
+ return tag ? tag : null;
1805
+ } catch {
1806
+ return null;
1807
+ }
1808
+ }
1809
+ //#endregion
1810
+ //#region src/git/tag/getGitTagMessage.ts
1811
+ /**
1812
+ * Get the message of an annotated git tag in the repository at `cwd`.
1813
+ *
1814
+ * @param cwd Repository working directory
1815
+ * @param tag Tag name to query
1816
+ * @returns The tag message string when found, otherwise `undefined`
1817
+ */
1818
+ async function getGitTagMessage(cwd, tag) {
1819
+ try {
1820
+ const [objectType, message] = (await execGit(cwd, [
1821
+ "for-each-ref",
1822
+ "--format=%(objecttype)%00%(contents)",
1823
+ `refs/tags/${tag}`
1824
+ ])).split("\0");
1825
+ if (objectType?.trim() !== "tag") return;
1826
+ return message?.trim() || void 0;
1827
+ } catch {
1828
+ /* istanbul ignore next */
1829
+ return;
1830
+ }
1831
+ }
1832
+ //#endregion
1833
+ //#region src/git/tag/getLatestGitTag.ts
1834
+ /**
1835
+ * Get the most recent tag reachable from `HEAD`.
1836
+ *
1837
+ * @param cwd Repository working directory
1838
+ * @returns Latest tag string or `null` when none is found
1839
+ */
1840
+ async function getLatestGitTag(cwd) {
1841
+ try {
1842
+ const tag = (await execGit(cwd, [
1843
+ "describe",
1844
+ "--tags",
1845
+ "--abbrev=0"
1846
+ ])).trim();
1847
+ /* istanbul ignore next */
1848
+ return tag ? tag : null;
1849
+ } catch {
1850
+ return null;
1851
+ }
1852
+ }
1853
+ //#endregion
1854
+ //#region src/git/tag/isGitTagConnected.ts
1855
+ /**
1856
+ * Determine whether a specific git tag commit is reachable from the current HEAD.
1857
+ *
1858
+ * Uses `git merge-base --is-ancestor refs/tags/<tag>^{commit} HEAD` to verify
1859
+ * that the tag's commit is an ancestor of the current reference. Any non-zero
1860
+ * exit status or execution error is treated as "not reachable".
1861
+ *
1862
+ * @param cwd Working directory where the git command will run
1863
+ * @param tag Tag name to evaluate (for example, "v1.2.0")
1864
+ * @returns True if the tag commit is reachable from HEAD, false otherwise
1865
+ */
1866
+ async function isGitTagConnected(cwd, tag) {
1867
+ try {
1868
+ await execGit(cwd, [
1869
+ "merge-base",
1870
+ "--is-ancestor",
1871
+ `refs/tags/${tag}^{commit}`,
1872
+ "HEAD"
1873
+ ]);
1874
+ return true;
1875
+ } catch {
1876
+ return false;
1877
+ }
1878
+ }
1879
+ //#endregion
1880
+ //#region src/git/tag/isGitTagPointed.ts
1881
+ /**
1882
+ * Check whether a given tag points to the provided commit.
1883
+ *
1884
+ * @param cwd Repository working directory
1885
+ * @param tag Tag name to resolve
1886
+ * @param commit Commit hash to compare against
1887
+ * @returns `true` when the tag points at `commit`, otherwise `false`
1888
+ */
1889
+ async function isGitTagPointed(cwd, tag, commit) {
1890
+ try {
1891
+ await execGit(cwd, [
1892
+ "merge-base",
1893
+ "--is-ancestor",
1894
+ `refs/tags/${tag}^{commit}`,
1895
+ commit
1896
+ ]);
1897
+ await execGit(cwd, [
1898
+ "merge-base",
1899
+ "--is-ancestor",
1900
+ commit,
1901
+ `refs/tags/${tag}^{commit}`
1902
+ ]);
1903
+ return true;
1904
+ } catch {
1905
+ return false;
1906
+ }
1907
+ }
1908
+ //#endregion
1909
+ //#region src/workflow/discovery/buildDependencyGraph.ts
1910
+ /**
1911
+ * Build a dependency graph mapping package names to dependent release plans.
1912
+ *
1913
+ * Each key is a package name and the value is a set of `ReleasePlan`s that
1914
+ * list that package as a dependency.
1915
+ *
1916
+ * @param plans Array of release plans to analyze
1917
+ * @returns Dependency graph mapping package name -> set of dependent plans
1918
+ */
1919
+ function buildDependencyGraph(plans) {
1920
+ const graph = /* @__PURE__ */ new Map();
1921
+ const packageNames = new Set(plans.map((plan) => plan.package.name).filter((name) => !!name));
1922
+ for (const plan of plans) for (const depName of plan.package.dependencies) {
1923
+ let set = graph.get(depName);
1924
+ if (!set && packageNames.has(depName)) graph.set(depName, set = /* @__PURE__ */ new Set());
1925
+ if (set) set.add(plan);
1926
+ }
1927
+ return graph;
1928
+ }
1929
+ //#endregion
1930
+ //#region src/workflow/changelog/extractPlainText.ts
1931
+ /**
1932
+ * Extract trimmed plain text from a Heading, Paragraph, or PhrasingContent node.
1933
+ *
1934
+ * Performs a depth-first traversal, concatenating string `value` tokens in
1935
+ * document order. Non-string values are ignored. Returns `null` for empty or
1936
+ * missing input.
1937
+ *
1938
+ * @param node Node to extract text from
1939
+ * @returns The trimmed plain-text string, or null if empty
1940
+ */
1941
+ function extractPlainText(node) {
1942
+ if (!node) return null;
1943
+ const queue = [node];
1944
+ let result = "";
1945
+ while (node = queue.shift()) {
1946
+ if ("value" in node && typeof node.value === "string") result += node.value;
1947
+ /* istanbul ignore else */
1948
+ if ("children" in node && Array.isArray(node.children)) queue.unshift(...node.children);
1949
+ }
1950
+ return result.trim() || null;
1951
+ }
1952
+ //#endregion
1953
+ //#region src/workflow/changelog/extractSemVer.ts
1954
+ var ANCHORED_SEMVER_REGEX = new RegExp(`^${SEMVER_REGEX.source}$`);
1955
+ var BRACKETED_SEMVER_REGEX = new RegExp(`\\[${SEMVER_REGEX.source}\\]`);
1956
+ /**
1957
+ * Extract SemVer core strings from a line.
1958
+ *
1959
+ * Splits the line on runs of spaces or tabs and on `..`/`...`. For each token,
1960
+ * first attempts an anchored SemVer match (must match the whole token), then
1961
+ * a bracketed match that finds a SemVer inside `[...]`. Returns the captured
1962
+ * SemVer core (capture group 2) for each successful match; falsy results are
1963
+ * filtered out.
1964
+ *
1965
+ * @param line Line to scan for SemVer cores
1966
+ * @returns Array of extracted SemVer core strings; empty if none
1967
+ */
1968
+ function extractSemVer(line) {
1969
+ return compact(line.split(/[ \t]+|\.{2,3}/).map((token) => {
1970
+ return (ANCHORED_SEMVER_REGEX.exec(token) ?? BRACKETED_SEMVER_REGEX.exec(token))?.at(2);
1971
+ }));
1972
+ }
1973
+ //#endregion
1974
+ //#region src/workflow/changelog/iterateChangelogVersions.ts
1975
+ var SENTENCE_TERMINAL_REGEX = /\p{Sentence_Terminal}$/u;
1976
+ /**
1977
+ * Iterate over Semantic Version strings extracted from a Markdown changelog.
1978
+ *
1979
+ * Parses `changelogContent` into an AST and evaluates nodes sequentially using
1980
+ * custom extractors. Evaluates heading nodes first before checking short
1981
+ * paragraph nodes. Stops execution after the first strategy yields valid
1982
+ * versions.
1983
+ *
1984
+ * @param changelogContent Raw Markdown text of the changelog
1985
+ * @yields Valid SemVer strings found in headings or candidate paragraphs
1986
+ */
1987
+ function* iterateChangelogVersions(changelogContent) {
1988
+ const root = fromMarkdown(changelogContent);
1989
+ const nodeExtractors = [(node) => {
1990
+ return node.type === "heading" ? extractPlainText(node) : null;
1991
+ }, (node) => {
1992
+ if (node.type !== "paragraph") return null;
1993
+ const paragraphText = extractPlainText(node);
1994
+ if (!paragraphText || paragraphText.length > 48 || SENTENCE_TERMINAL_REGEX.test(paragraphText)) return null;
1995
+ return paragraphText;
1996
+ }];
1997
+ for (const extractText of nodeExtractors) {
1998
+ let isVersionFound = false;
1999
+ for (const node of root.children) {
2000
+ const extractedText = extractText(node);
2001
+ const candidateVersion = extractedText ? semver.sort(extractSemVer(extractedText)).pop() : null;
2002
+ if (candidateVersion && semver.valid(candidateVersion)) {
2003
+ isVersionFound = true;
2004
+ yield candidateVersion;
2005
+ }
2006
+ }
2007
+ if (isVersionFound) return;
2008
+ }
2009
+ }
2010
+ //#endregion
2011
+ //#region src/workflow/changelog/extractLatestVersion.ts
2012
+ /**
2013
+ * Find the highest semantic version from the first version-bearing element.
2014
+ *
2015
+ * Pulls the first available version string from the parsed markdown iterator.
2016
+ * Short-circuits execution immediately upon locating a match to avoid passing
2017
+ * through the remaining document structure.
2018
+ *
2019
+ * @param changelogContent The raw markdown string representing the changelog
2020
+ * @returns The highest valid semantic version string found or null
2021
+ */
2022
+ function extractLatestVersion(changelogContent) {
2023
+ for (const version of iterateChangelogVersions(changelogContent)) return version;
2024
+ return null;
2025
+ }
2026
+ //#endregion
2027
+ //#region src/workflow/discovery/verifyPackageTag.ts
2028
+ /**
2029
+ * Verify a Git tag against package specifications and repository history.
2030
+ *
2031
+ * Ensures the target tag exists locally before parsing its commit data. Rejects
2032
+ * tags that do not target a commit matching the specified `pkg`. Expands the
2033
+ * history graph up to the tag reference before verifying structural connectivity.
2034
+ *
2035
+ * @param cwd Repository working directory path
2036
+ * @param pkg Package descriptor containing version and location context
2037
+ * @param tagName Name of the Git tag to verify
2038
+ * @returns True if the tag is valid and connected; otherwise, false
2039
+ */
2040
+ async function verifyPackageTag(cwd, pkg, tagName) {
2041
+ await ensureGitTag(cwd, tagName);
2042
+ const tagRef = `refs/tags/${tagName}`;
2043
+ let tagCommit;
2044
+ try {
2045
+ tagCommit = await getParsedGitCommit(cwd, tagRef);
2046
+ } catch {
2047
+ return false;
2048
+ }
2049
+ if (!isCommitForPackage(pkg, tagCommit)) return false;
2050
+ await expandGitHistory(cwd, { until: tagRef });
2051
+ return isGitTagConnected(cwd, tagName);
2052
+ }
2053
+ //#endregion
2054
+ //#region src/workflow/discovery/discoverPackageTag.ts
2055
+ /**
2056
+ * Discover and validate the Git tag for a package.
2057
+ *
2058
+ * Returns the existing tag if already present on the `pkg` object. Resolves
2059
+ * the local changelog file path, extracts the current version, and generates
2060
+ * the expected Git tag name. Verifies the tag against the repository and
2061
+ * ensures its historical changelog version matches the current local version.
2062
+ *
2063
+ * @param cwd The current working directory
2064
+ * @param pkg The package configuration object
2065
+ * @returns The validated `Tag` object or null if validation fails
2066
+ */
2067
+ async function discoverPackageTag(cwd, pkg) {
2068
+ if (pkg.tag) return pkg.tag;
2069
+ const changelogFile = pkg.changelogFile || "CHANGELOG.md";
2070
+ const changelogFilePath = path.resolve(cwd, pkg.location, changelogFile);
2071
+ let localChangelogContent;
2072
+ try {
2073
+ localChangelogContent = await readFile(changelogFilePath, "utf-8");
2074
+ } catch {}
2075
+ if (!localChangelogContent) return null;
2076
+ const currentVersion = extractLatestVersion(localChangelogContent);
2077
+ if (!currentVersion) return null;
2078
+ let expectedTagName;
2079
+ try {
2080
+ expectedTagName = generateGitTagName(pkg.entry, pkg.name, currentVersion);
2081
+ } catch {}
2082
+ if (!expectedTagName) return null;
2083
+ if (!await verifyPackageTag(cwd, pkg, expectedTagName)) return null;
2084
+ const historicalChangelogContent = await readGitFile(cwd, await resolveGitRevision(cwd, `refs/tags/${expectedTagName}`), path.relative(cwd, changelogFilePath));
2085
+ if (!historicalChangelogContent) return null;
2086
+ const historicalChangelogVersion = extractLatestVersion(historicalChangelogContent);
2087
+ if (!historicalChangelogVersion || historicalChangelogVersion !== currentVersion) return null;
2088
+ return {
2089
+ name: expectedTagName,
2090
+ message: await getGitTagMessage(cwd, expectedTagName)
2091
+ };
2092
+ }
2093
+ //#endregion
2094
+ //#region src/workflow/discovery/resolvePackageStableTag.ts
2095
+ /**
2096
+ * Resolve the latest stable Git tag for a package.
2097
+ *
2098
+ * Reads changelog release versions for `pkg` and verifies strict descending
2099
+ * semver order. Ignores prerelease versions unless transitioning across major
2100
+ * or prerelease boundaries, and verifies that the matching Git tag exists.
2101
+ *
2102
+ * @param cwd Absolute path to the root working directory
2103
+ * @param pkg Package configuration object
2104
+ * @returns Verified tag metadata object or `null` if no stable tag is resolved
2105
+ * @throws If a version is invalid, versions are not in strict descending
2106
+ * order, or the corresponding Git tag is missing
2107
+ */
2108
+ async function resolvePackageStableTag(cwd, pkg) {
2109
+ const changelogFile = pkg.changelogFile || "CHANGELOG.md";
2110
+ const changelogFilePath = path.resolve(cwd, pkg.location, changelogFile);
2111
+ let changelogContent;
2112
+ try {
2113
+ changelogContent = await readFile(changelogFilePath, "utf-8");
2114
+ } catch (error) {
2115
+ /* istanbul ignore else */
2116
+ if (error?.code === "ENOENT") return null;
2117
+ /* istanbul ignore next */
2118
+ throw error;
2119
+ }
2120
+ let precedingVersion = null;
2121
+ for (const version of iterateChangelogVersions(changelogContent)) {
2122
+ const currentVersion = semver.parse(version);
2123
+ assert(currentVersion, `Version "${version}" is not a valid semantic version.`);
2124
+ if (precedingVersion && semver.gte(currentVersion, precedingVersion)) throw new Error(`Version "${version}" must be strictly lower than preceding version "${precedingVersion.raw}".`);
2125
+ if (!semver.prerelease(currentVersion) && (currentVersion.major >= 1 || precedingVersion && semver.prerelease(precedingVersion))) {
2126
+ const tagName = generateGitTagName(pkg.entry, pkg.name, version);
2127
+ if (!await verifyPackageTag(cwd, pkg, tagName)) throw new Error(`Git tag "${tagName}" is not associated with package "${pkg.name ?? ""}" in directory "${pkg.location}".`);
2128
+ return {
2129
+ name: tagName,
2130
+ message: await getGitTagMessage(cwd, tagName)
2131
+ };
2132
+ }
2133
+ precedingVersion = currentVersion;
2134
+ }
2135
+ return null;
2136
+ }
2137
+ //#endregion
2138
+ //#region src/workflow/discovery/resolvePackageTag.ts
2139
+ /**
2140
+ * Resolve the release tag for a single package version.
2141
+ *
2142
+ * Returns the cached `pkg.tag` immediately if it already exists. Generates an
2143
+ * expected tag name from the package metadata and verifies its integrity using
2144
+ * `verifyPackageTag`.
2145
+ *
2146
+ * @param cwd Repository working directory
2147
+ * @param pkg Package descriptor containing version and location context
2148
+ * @returns A promise resolving to the tag metadata or null when not found
2149
+ */
2150
+ async function resolvePackageTag(cwd, pkg) {
2151
+ if (pkg.tag) return pkg.tag;
2152
+ let expectedTagName;
2153
+ try {
2154
+ expectedTagName = generateGitTagName(pkg.entry, pkg.name, pkg.version);
2155
+ } catch {}
2156
+ if (!expectedTagName) return null;
2157
+ if (await verifyPackageTag(cwd, pkg, expectedTagName)) return {
2158
+ name: expectedTagName,
2159
+ message: await getGitTagMessage(cwd, expectedTagName)
2160
+ };
2161
+ return null;
2162
+ }
2163
+ //#endregion
2164
+ //#region src/workflow/analysis/propagateDependencyUpdates.ts
2165
+ /**
2166
+ * Propagate release updates through package dependencies.
2167
+ *
2168
+ * Marks packages that depend on a releasing package for a `patch` release
2169
+ * when they do not already have a release type.
2170
+ *
2171
+ * @param plans Array of release plans to update
2172
+ * @returns Updated array of release plans
2173
+ */
2174
+ async function propagateDependencyUpdates(cwd, plans) {
2175
+ const graph = buildDependencyGraph(plans);
2176
+ const scheduled = /* @__PURE__ */ new Map();
2177
+ const stack = [];
2178
+ for (const plan of plans) if (plan.release?.type) {
2179
+ const visited = /* @__PURE__ */ new Set([plan]);
2180
+ stack.push(plan);
2181
+ let curr;
2182
+ while (curr = stack.pop()) if (curr.package.name) {
2183
+ for (const dependent of graph.get(curr.package.name) ?? []) if (!visited.has(dependent)) {
2184
+ visited.add(dependent);
2185
+ stack.push(dependent);
2186
+ scheduled.set(dependent, await mergeGitHistory(cwd, scheduled.get(dependent) ?? dependent.history, plan.history));
2187
+ }
2188
+ }
2189
+ }
2190
+ return plans.map((plan) => {
2191
+ const history = scheduled.get(plan);
2192
+ if (history) {
2193
+ plan = {
2194
+ ...plan,
2195
+ history
2196
+ };
2197
+ if (!plan.release?.type) plan.release = { type: "patch" };
2198
+ }
2199
+ return plan;
2200
+ });
2201
+ }
2202
+ //#endregion
2203
+ //#region src/workflow/committing/isReleaseCommit.ts
2204
+ /**
2205
+ * Determine whether a commit represents a release or matches a release marker.
2206
+ *
2207
+ * Resolves string commit identifiers to parsed commit objects, checks if any
2208
+ * associated trailer matches the `marker` predicate, and falls back to
2209
+ * verifying exact tag matches for the `commit` hash.
2210
+ *
2211
+ * @param cwd Working directory path for Git commands
2212
+ * @param commit Commit object, hash string, or nullish value
2213
+ * @param marker Trailer key string or predicate function to evaluate
2214
+ * @returns `true` if the commit is a release commit, otherwise `false`
2215
+ */
2216
+ async function isReleaseCommit(cwd, commit, marker = GIT_TRAILER_RELEASE_AGENT) {
2217
+ if (typeof commit === "string") try {
2218
+ commit = await getParsedGitCommit(cwd, commit, typeof marker === "string" ? [marker] : []);
2219
+ } catch {
2220
+ commit = null;
2221
+ }
2222
+ if (!commit) return false;
2223
+ const predicate = typeof marker === "string" ? (trailer) => trailer.key === marker && !!trailer.value : marker;
2224
+ if (commit.trailers.some(predicate)) return true;
2225
+ return execGit(cwd, [
2226
+ "describe",
2227
+ "--tags",
2228
+ "--exact-match",
2229
+ commit.hash
2230
+ ]).then(() => true).catch(() => false);
2231
+ }
2232
+ //#endregion
2233
+ //#region src/workflow/analysis/sliceUnreleased.ts
2234
+ /**
2235
+ * Yield parsed commits from the workspace until a release commit is found.
2236
+ *
2237
+ * Iterates through parsed commit history and yields unreleased commits in
2238
+ * order. Stops processing upon reaching the first release commit.
2239
+ *
2240
+ * @param cwd Path to the working directory
2241
+ * @param options Options for configuring Git history retrieval
2242
+ * @yields Parsed `Commit` objects up to the most recent release commit
2243
+ */
2244
+ async function* sliceUnreleased(cwd, options) {
2245
+ for await (const commit of showParsedGitHistory(cwd, options)) {
2246
+ if (await isReleaseCommit(cwd, commit, options?.marker)) break;
2247
+ yield commit;
2248
+ }
2249
+ }
2250
+ //#endregion
2251
+ //#region src/workflow/analysis/streamPackageCommits.ts
2252
+ /**
2253
+ * Yield commits from git history associated with a package.
2254
+ *
2255
+ * Filters git commit history to stream only entries relevant to the target
2256
+ * `pkg` directory.
2257
+ *
2258
+ * @param cwd Path to the working directory for git commands
2259
+ * @param pkg Package configuration containing the target directory
2260
+ * @param options Options for parsing and filtering git history
2261
+ * @yields Commits belonging to the specified package
2262
+ */
2263
+ async function* streamPackageCommits(cwd, pkg, options = {}) {
2264
+ options = {
2265
+ ...options,
2266
+ filePath: options.filePath || pkg.location
2267
+ };
2268
+ for await (const commit of showParsedGitHistory(cwd, options)) if (isCommitForPackage(pkg, commit)) yield commit;
2269
+ }
2270
+ //#endregion
2271
+ //#region src/workflow/changelog/buildChangelog.ts
2272
+ var preset = await createPreset();
2273
+ var headerPartial = (context) => {
2274
+ return context.version ? preset.writer.headerPartial?.(context) : void 0;
2275
+ };
2276
+ /**
2277
+ * Build the changelog string for a release.
2278
+ *
2279
+ * Compiles commit history and release context into a formatted changelog using
2280
+ * conventional commits and writer configurations. Resolves file paths and handles
2281
+ * tag comparisons when repository URLs are available.
2282
+ *
2283
+ * @param context The release context containing repository and working directory details
2284
+ * @param history The iterable or async iterable collection of commits to process
2285
+ * @param options The build configuration options for the changelog
2286
+ * @returns The formatted changelog content string
2287
+ */
2288
+ async function buildChangelog(context, history, options = {}) {
2289
+ const repository = context.repository?.url || void 0;
2290
+ const version = options.version || void 0;
2291
+ const previousTag = options.previousTag || void 0;
2292
+ const currentTag = options.currentTag || void 0;
2293
+ return formatFile(path.join(context.cwd, options.packageDir || ".", options.changelogFile || "CHANGELOG.md"), await writeChangelogString(history, {
2294
+ date: context.today,
2295
+ version,
2296
+ previousTag,
2297
+ currentTag,
2298
+ linkCompare: !!repository && !!previousTag && !!currentTag,
2299
+ linkReferences: !!repository,
2300
+ repoUrl: repository,
2301
+ commit: "commit",
2302
+ issue: "issues",
2303
+ headerPartial
2304
+ }, preset.writer));
2305
+ }
2306
+ //#endregion
2307
+ //#region src/workflow/changelog/buildReleaseNotes.ts
2308
+ /**
2309
+ * Build release notes from a release context and commit history.
2310
+ *
2311
+ * Generates changelog content from commits, parses it into an abstract syntax
2312
+ * tree, shifts heading depths, and formats the resulting markdown file.
2313
+ *
2314
+ * @param context The release context containing repository and configuration details
2315
+ * @param history The iterable or async iterable collection of commits to process
2316
+ * @returns The formatted release notes as a markdown string
2317
+ */
2318
+ async function buildReleaseNotes(context, history) {
2319
+ const changelogContent = await buildChangelog(context, history);
2320
+ const root = fromMarkdown(changelogContent);
2321
+ root.children = root.children.flatMap((node) => {
2322
+ if (node.type === "heading") {
2323
+ /* istanbul ignore next */
2324
+ if (node.depth <= 2) return [];
2325
+ node = {
2326
+ ...node,
2327
+ depth: node.depth - 1
2328
+ };
2329
+ }
2330
+ return node;
2331
+ });
2332
+ return formatFile(path.join(context.cwd, DEFAULT_CHANGELOG_FILE), toMarkdown(root));
2333
+ }
2334
+ //#endregion
2335
+ //#region src/workflow/changelog/extractPreviousVersion.ts
2336
+ /**
2337
+ * Find the latest stable version that precedes the current version.
2338
+ *
2339
+ * Parses markdown from top to bottom to extract semantic versions from headings
2340
+ * and paragraphs. Enforces that discovered versions appear in strict
2341
+ * descending order. Returns the first version that falls outside the current
2342
+ * version's major, minor, and patch boundaries if the current version is
2343
+ * `v1.0.0` or higher, or the first non-matching version for `v0.x.x` releases.
2344
+ *
2345
+ * @param currentVersion The version to evaluate against
2346
+ * @param changelogContent The raw markdown content to scan for versions
2347
+ * @returns The resolved stable version string or null when none is found
2348
+ * @throws If `currentVersion` is invalid or already stable, or if versions in the changelog are not listed in strict descending order
2349
+ */
2350
+ async function extractPreviousVersion(currentVersion, changelogContent) {
2351
+ const parsedCurrent = semver.parse(currentVersion);
2352
+ if (!currentVersion || !parsedCurrent) throw new Error(`The current version "${colors.bold(String(currentVersion))}" is not a valid semantic version.`);
2353
+ const currentMajor = parsedCurrent.major;
2354
+ if (currentMajor >= 1 && parsedCurrent.prerelease.length === 0) throw new Error(`The current version "${colors.bold(currentVersion)}" is already a stable release.`);
2355
+ const baseVersion = `${parsedCurrent.major}.${parsedCurrent.minor}.${parsedCurrent.patch}`;
2356
+ let priorVersion = null;
2357
+ for (const version of iterateChangelogVersions(changelogContent)) {
2358
+ const parsedVersion = semver.parse(version);
2359
+ /* istanbul ignore else */
2360
+ if (parsedVersion) {
2361
+ if (!priorVersion) {
2362
+ if (version !== currentVersion) return version;
2363
+ priorVersion = parsedVersion;
2364
+ } else {
2365
+ if (semver.gte(parsedVersion, priorVersion)) throw new Error(`Each newer release must have a higher version, but "${colors.bold(priorVersion.version)}" appears before "${colors.bold(version)}".`);
2366
+ priorVersion = parsedVersion;
2367
+ const { major, minor, patch } = parsedVersion;
2368
+ if (currentMajor >= 1 && `${major}.${minor}.${patch}` !== baseVersion) return version;
2369
+ }
2370
+ }
2371
+ }
2372
+ return null;
2373
+ }
2374
+ //#endregion
2375
+ //#region src/workflow/changelog/prependChangelog.ts
2376
+ var defaultChangelogTitle = "Changelog";
2377
+ /**
2378
+ * Prepend changelog content to a markdown file, creating it if necessary.
2379
+ *
2380
+ * Reads the existing file if present, prepends the new content before the main heading,
2381
+ * formats and writes the result back.
2382
+ *
2383
+ * @param filePath Path to the changelog file
2384
+ * @param revision Changelog content to prepend
2385
+ * @returns Promise that resolves when the changelog is written
2386
+ */
2387
+ async function prependChangelog(filePath, revision) {
2388
+ let content = "";
2389
+ try {
2390
+ content = await fs.readFile(filePath, "utf-8");
2391
+ } catch (err) {
2392
+ /* istanbul ignore next */
2393
+ if (err.code !== "ENOENT") throw err;
2394
+ }
2395
+ const root = fromMarkdown(content);
2396
+ let index = root.children.findIndex((node) => node.type === "heading" && node.depth === 1);
2397
+ if (index === -1) {
2398
+ index = 0;
2399
+ root.children.unshift({
2400
+ type: "heading",
2401
+ depth: 1,
2402
+ children: [{
2403
+ type: "text",
2404
+ value: defaultChangelogTitle
2405
+ }]
2406
+ });
2407
+ }
2408
+ root.children.splice(index + 1, 0, ...fromMarkdown(revision).children);
2409
+ content = toMarkdown(root);
2410
+ content = await formatFile(filePath, content);
2411
+ await fs.writeFile(filePath, content);
2412
+ }
2413
+ //#endregion
2414
+ //#region src/workflow/changelog/writeChangelog.ts
2415
+ /**
2416
+ * Write changelog content to the file system based on the release plan.
2417
+ *
2418
+ * @param cwd Repository working directory
2419
+ * @param plan Release plan containing package and changelog content
2420
+ * @returns Promise that resolves when the changelog file has been written
2421
+ */
2422
+ async function writeChangelog(cwd, plan) {
2423
+ if (plan.release?.changelog) {
2424
+ const changelogFile = plan.package.changelogFile || "CHANGELOG.md";
2425
+ await prependChangelog(path.join(cwd, plan.package.location, changelogFile), plan.release.changelog);
2426
+ }
2427
+ }
2428
+ //#endregion
2429
+ //#region package.json
2430
+ var version = "0.4.0";
2431
+ //#endregion
2432
+ //#region src/workflow/committing/generateReleaseCommitMessage.ts
2433
+ var NOTABLE_TYPES = [
2434
+ "feat",
2435
+ "fix",
2436
+ "perf",
2437
+ "refactor",
2438
+ "revert"
2439
+ ];
2440
+ /**
2441
+ * Generate a formatted release commit message based on release plans and
2442
+ * custom trailers.
2443
+ *
2444
+ * Compiles package version updates and included commit logs into a standardized
2445
+ * conventional commit message body, appending configured release agent and
2446
+ * custom trailers. Returns `null` if no valid release subject can be derived.
2447
+ *
2448
+ * @param cwd The working directory path
2449
+ * @param plans Readonly array of release plans containing package changes and commit history
2450
+ * @param trailers Optional record of custom git trailers to append to the commit
2451
+ * @returns The formatted release commit message string or `null` if the subject is empty
2452
+ * @example
2453
+ * ```
2454
+ * chore: release pkg-a@2.1.0, pkg-b@1.0.4
2455
+ *
2456
+ * Version Updates:
2457
+ * - pkg-a: 2.0.0 → 2.1.0
2458
+ * - pkg-b: 1.0.3 → 1.0.4
2459
+ *
2460
+ * Notable Changes:
2461
+ * - feat(pkg-a): support custom plugin entrypoints (#210)
2462
+ * - fix(pkg-b): correct minor typography bug in help text (#212)
2463
+ *
2464
+ * Release-Mode: Deferred
2465
+ * ```
2466
+ */
2467
+ async function generateReleaseCommitMessage(cwd, plans, trailers = {}) {
2468
+ const standalone = plans.length === 1;
2469
+ trailers = {
2470
+ [GIT_TRAILER_RELEASE_AGENT]: `ReelOut/${/* istanbul ignore next */ version}`,
2471
+ ...trailers
2472
+ };
2473
+ plans = plans.filter((plan) => plan.release?.tag?.name).toSorted((a, b) => {
2474
+ if (a.package.entry) return -1;
2475
+ if (b.package.entry) return 1;
2476
+ /* istanbul ignore next */
2477
+ return (a.package.name ?? "").localeCompare(b.package.name ?? "");
2478
+ });
2479
+ let subject;
2480
+ if (plans.length === 1) subject = standalone ? plans[0]?.release?.version : plans[0]?.release?.tag?.name;
2481
+ else if (plans.length >= 2 && plans.length <= 3) subject = plans.map((plan) => plan.release?.tag?.name).join(", ");
2482
+ else if (plans.length > 3) subject = `${plans.length} packages (${plans.slice(0, 2).map((plan) => plan.release?.tag?.name).join(", ")}, +${plans.length - 2} more)`;
2483
+ if (!subject) return null;
2484
+ const packages = plans.map((plan) => {
2485
+ return `- ${plan.package.name || plan.package.location}: ${plan.package.version} → ${plan.release?.version}`;
2486
+ });
2487
+ const commits = (await plans.reduce(async (acc, plan) => mergeGitHistory(cwd, await acc, plan.history), Promise.resolve([]))).filter((commit) => {
2488
+ const isNotableType = commit.type && NOTABLE_TYPES.includes(commit.type);
2489
+ const isBreaking = commit.notes.length > 0;
2490
+ return isNotableType || isBreaking;
2491
+ }).toReversed().map(({ header }) => `- ${header}`);
2492
+ return [
2493
+ `chore: release ${subject}`,
2494
+ packages.length >= 2 ? ["Version Updates:", ...packages].join("\n") : void 0,
2495
+ commits.length > 0 ? ["Notable Changes:", ...commits].join("\n") : void 0,
2496
+ Object.entries(trailers).map(([key, value]) => key && value != null ? `${key}: ${value}` : "").filter(Boolean).join("\n")
2497
+ ].filter(Boolean).join("\n\n");
2498
+ }
2499
+ //#endregion
2500
+ //#region src/plugin/HookManager.ts
2501
+ var HookPriority = {
2502
+ High: 50,
2503
+ Normal: 0,
2504
+ Low: -50
2505
+ };
2506
+ /**
2507
+ * Manage hook registrations and asynchronous execution chains.
2508
+ *
2509
+ * Stores handlers in a prioritized registry and executes them sequentially in
2510
+ * priority order.
2511
+ */
2512
+ var HookManager = class {
2513
+ #registry = /* @__PURE__ */ new Map();
2514
+ /**
2515
+ * Register a handler function for a specific hook.
2516
+ *
2517
+ * Adds the `handler` to the internal registry for `name` and sorts the list
2518
+ * so higher-priority handlers run first.
2519
+ *
2520
+ * @param name Name of the hook to register
2521
+ * @param handler Callback function executed when the hook triggers
2522
+ * @param priority Execution order rank where higher values run earlier
2523
+ */
2524
+ on(name, handler, priority = HookPriority.Normal) {
2525
+ const registrations = this.#registry.get(name) ?? [];
2526
+ registrations.push({
2527
+ name,
2528
+ handler,
2529
+ priority
2530
+ });
2531
+ registrations.sort((a, b) => b.priority - a.priority);
2532
+ this.#registry.set(name, registrations);
2533
+ }
2534
+ /**
2535
+ * Unregister a handler function from a specific hook.
2536
+ *
2537
+ * Removes matching `handler` references from the internal registry for
2538
+ * `name`. Takes no action if `name` has no registered handlers.
2539
+ *
2540
+ * @param name Name of the hook to unregister from
2541
+ * @param handler Reference of the handler function to remove
2542
+ */
2543
+ off(name, handler) {
2544
+ const registrations = this.#registry.get(name);
2545
+ if (!registrations) return;
2546
+ this.#registry.set(name, registrations.filter((registration) => registration.handler !== handler));
2547
+ }
2548
+ /**
2549
+ * Trigger execution of all handlers registered to a hook.
2550
+ *
2551
+ * Passes `context` through the handler pipeline in descending priority order.
2552
+ * Enables handlers to control execution flow using `next` and executes `done`
2553
+ * after the last handler completes.
2554
+ *
2555
+ * @param name Name of the hook to trigger
2556
+ * @param context Shared payload passed into each handler
2557
+ * @param done Optional final callback run after the pipeline completes
2558
+ * @returns Promise that resolves when execution completes
2559
+ */
2560
+ async emit(name, context, done) {
2561
+ const registrations = this.#registry.get(name) ?? [];
2562
+ const dispatch = async (index, context) => {
2563
+ const registration = registrations[index];
2564
+ if (!registration) return done ? await done(context) : void 0;
2565
+ let isNextCalled = false;
2566
+ return await registration.handler(context, async (context) => {
2567
+ if (isNextCalled) return;
2568
+ isNextCalled = true;
2569
+ return await dispatch(index + 1, context);
2570
+ });
2571
+ };
2572
+ return await dispatch(0, context);
2573
+ }
2574
+ };
2575
+ //#endregion
2576
+ //#region src/workflow/report/generateReleaseReport.ts
2577
+ /**
2578
+ * Generate a structured release report from the current workflow state.
2579
+ *
2580
+ * Extracts state information from `context` and organizes it into a report
2581
+ * containing workflow status, release plans, and package metadata. Omits
2582
+ * unversioned release plans from the finalized output.
2583
+ *
2584
+ * @param context Release execution context containing workflow state and plans
2585
+ * @returns Structured release report object containing workflow results
2586
+ */
2587
+ function generateReleaseReport(context) {
2588
+ return {
2589
+ status: context.status,
2590
+ phase: context.phase,
2591
+ error: Error.isError(context.error) ? context.error.message : typeof context.error === "string" ? context.error : null,
2592
+ packages: context.packages.map((pkg) => ({
2593
+ location: pkg.location,
2594
+ name: pkg.name,
2595
+ version: pkg.version
2596
+ })),
2597
+ plans: compact(context.plans.map((plan) => {
2598
+ if (!plan.release?.version) return null;
2599
+ return {
2600
+ package: {
2601
+ provider: plan.package.provider,
2602
+ entry: plan.package.entry,
2603
+ location: plan.package.location,
2604
+ name: plan.package.name,
2605
+ version: plan.package.version,
2606
+ private: !!plan.package.private
2607
+ },
2608
+ release: {
2609
+ type: plan.release.type,
2610
+ version: plan.release.version,
2611
+ tag: plan.release.tag?.name,
2612
+ changelog: plan.release.changelog
2613
+ }
2614
+ };
2615
+ }))
2616
+ };
2617
+ }
2618
+ //#endregion
2619
+ //#region src/workflow/report/printReleaseReport.ts
2620
+ /**
2621
+ * Print a formatted release report to the logger.
2622
+ *
2623
+ * Logs workflow `status` and details for planned package releases. Displays
2624
+ * package names, directories, and version changes on success, or outputs the
2625
+ * error message on failure.
2626
+ *
2627
+ * @param logger Logger instance for outputting messages
2628
+ * @param report Release report containing status and package details
2629
+ */
2630
+ function printReleaseReport(logger, report) {
2631
+ if (report.status) {
2632
+ const statusLabel = {
2633
+ success: colors.green("SUCCESS"),
2634
+ failure: colors.red("FAILURE")
2635
+ }[report.status];
2636
+ logger.info(`Status: ${statusLabel}`);
2637
+ }
2638
+ if (report.status === "failure") return logger.error(["Release complete:", colors.red(report.error || "An unexpected error occurred during the release process.")].join(" "));
2639
+ if (report.plans.length === 0) return logger.info(["Release complete:", colors.yellow("No packages are scheduled for release.")].join(" "));
2640
+ const header = [
2641
+ "Release complete:",
2642
+ colors.bold(colors.green(`${report.plans.length} released`)),
2643
+ colors.gray(`(${report.packages.length})`)
2644
+ ].join(" ");
2645
+ const list = report.plans.toSorted((a, b) => (a.package.name || "").localeCompare(b.package.name || "")).map((plan) => {
2646
+ let dir = path.normalize(path.join(plan.package.location, "."));
2647
+ dir = dir === "." ? dir : `./${dir}`;
2648
+ const name = plan.package.name ? colors.bgBlue(` ${plan.package.name} `) : !plan.package.entry && colors.gray(` ${dir} `);
2649
+ let version = [plan.release.version, plan.package.version].join(" ← ");
2650
+ version = ` ${version} `;
2651
+ const type = plan.release.type && colors.gray(` ${plan.release.type} `);
2652
+ return [[
2653
+ name,
2654
+ plan.release.type === "major" ? colors.bgRed(version) : colors.bgGreen(version),
2655
+ type
2656
+ ].filter(Boolean).join(""), plan.release.changelog?.replace(/^(#+ .+)$/gm, (_, header) => colors.cyan(header)).trim()].filter(Boolean).join("\n\n");
2657
+ }).join("\n\n");
2658
+ logger.info(`${header}\n\n${list}\n`);
2659
+ }
2660
+ //#endregion
2661
+ //#region src/workflow/executeReleaseWorkflow.ts
2662
+ /**
2663
+ * Execute the complete release workflow across all configured plugins.
2664
+ *
2665
+ * Runs each lifecycle phase sequentially, dispatching plugin hooks in onion
2666
+ * order based on declared priority. Logs hook execution timing for non-silent
2667
+ * runs and prints a release report upon completion or failure.
2668
+ *
2669
+ * @param context Release execution context containing runtime options and logger
2670
+ * @param plugins List of release plugins to execute
2671
+ * @returns Promise that resolves when all workflow phases complete
2672
+ * @throws If any lifecycle hook execution fails
2673
+ */
2674
+ async function executeReleaseWorkflow(context, plugins) {
2675
+ try {
2676
+ context.status = null;
2677
+ context.error = null;
2678
+ const manager = new HookManager();
2679
+ for (const hookName of RELEASE_HOOK_NAMES) for (const plugin of plugins) {
2680
+ let hook = plugin[hookName];
2681
+ if (typeof hook === "function") hook = { handler: hook };
2682
+ const handler = hook?.handler;
2683
+ const priority = hook?.priority;
2684
+ if (handler) manager.on(hookName, async (context, next) => {
2685
+ const current = context.phase = {
2686
+ hook: hookName,
2687
+ plugin: plugin.name
2688
+ };
2689
+ const label = `${colors.gray(`[${current.hook}]`)} ${current.plugin}`;
2690
+ let startedLogging = false;
2691
+ let hasError = false;
2692
+ startedLogging = true;
2693
+ context.logger.start(label);
2694
+ const currentFrame = { startTime: performance.now() };
2695
+ const nextFrame = { duration: 0 };
2696
+ try {
2697
+ return await handler.call(plugin, context, async () => {
2698
+ const startTime = performance.now();
2699
+ try {
2700
+ return await next(context);
2701
+ } finally {
2702
+ nextFrame.duration = performance.now() - startTime;
2703
+ }
2704
+ });
2705
+ } catch (err) {
2706
+ hasError = true;
2707
+ throw err;
2708
+ } finally {
2709
+ if (startedLogging) {
2710
+ const duration = performance.now() - currentFrame.startTime - nextFrame.duration;
2711
+ const message = [label, (duration >= 5e3 ? colors.yellow : colors.cyan)(`${(duration / 1e3).toFixed(2)}s`)].join(" ");
2712
+ if (hasError) context.logger.error(message);
2713
+ else context.logger.success(message);
2714
+ }
2715
+ }
2716
+ }, priority);
2717
+ }
2718
+ const dispatch = async (index, context) => {
2719
+ const hook = RELEASE_HOOK_NAMES[index];
2720
+ if (!hook) return;
2721
+ return await manager.emit(hook, context, (context) => dispatch(index + 1, context));
2722
+ };
2723
+ await dispatch(0, context);
2724
+ context.status = "success";
2725
+ } catch (err) {
2726
+ context.status = "failure";
2727
+ context.error = err;
2728
+ throw err;
2729
+ } finally {
2730
+ printReleaseReport(context.logger, generateReleaseReport(context));
2731
+ }
2732
+ }
2733
+ //#endregion
2734
+ export { countGitHistory as $, getCurrentGitTag as A, isDefined as At, ensureGitUserConfig as B, deriveReleaseType as Bt, extractSemVer as C, isMatch as Ct, isGitTagConnected as D, execGit as Dt, isGitTagPointed as E, formatFile as Et, createGitTag as F, GIT_TRAILER_RELEASE_AGENT as Ft, mergeGitHistory as G, showParsedGitHistory as H, determineReleaseType as Ht, readGitFile as I, RELEASE_HOOK_NAMES as It, expandGitHistory as J, GIT_REL_FLAGS as K, resolveGitRepository as L, SEMVER_REGEX as Lt, ensureGitTag as M, ALL_FILES as Mt, isGitTagPresent as N, DEFAULT_CHANGELOG_FILE as Nt, getLatestGitTag as O, execCommand as Ot, deleteGitTag as P, DEV_NULL as Pt, isGitShallowRepository as Q, pushGitChanges as R, isStableVersion as Rt, iterateChangelogVersions as S, readJson as St, buildDependencyGraph as T, interpolate as Tt, showGitHistory as U, bumpVersion as Ut, getGitConfigValue as V, pickPriorityReleaseType as Vt, restoreFullGitHistory as W, extractVersionQualifier as Wt, isGitAncestor as X, resolveGitRevision as Y, withShallowLock as Z, resolvePackageTag as _, isSemVerGitTag as _t, HookPriority as a, parseGitCommit as at, verifyPackageTag as b, createPlugin as bt, writeChangelog as c, createGitCommit as ct, buildReleaseNotes as d, deriveTransitionReleases as dt, getCurrentGitCommit as et, buildChangelog as f, deriveChangeReleases as ft, propagateDependencyUpdates as g, sanitizePrereleaseLabel as gt, isReleaseCommit as h, resolveReleaseChannel as ht, HookManager as i, parseGitPrettyFormat as it, generateGitTagName as j, buildTrailerPattern as jt, getGitTagMessage as k, compact as kt, prependChangelog as l, getCurrentGitBranch as lt, sliceUnreleased as m, resolveVersionQualifier as mt, printReleaseReport as n, GIT_PRETTY_FIELD_SEPARATOR as nt, generateReleaseCommitMessage as o, TTLCache as ot, streamPackageCommits as p, isCommitForPackage as pt, detectGitRelationship as q, generateReleaseReport as r, GIT_PRETTY_FORMAT as rt, version as s, extractMentions as st, executeReleaseWorkflow as t, getParsedGitCommit as tt, extractPreviousVersion as u, promotePrereleaseVersions as ut, resolvePackageStableTag as v, isSemVer as vt, extractPlainText as w, isClass as wt, extractLatestVersion as x, writeJson as xt, discoverPackageTag as y, findReleaseRule as yt, getGitRemote as z, isSameReleaseCycle as zt };
2735
+
2736
+ //# sourceMappingURL=workflow-CroJ6v4g.js.map