@reelout/core 0.13.0 → 0.14.0

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