@eserstack/codebase 0.0.0-bootstrap.0 → 5.0.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 (175) hide show
  1. package/README.md +302 -0
  2. package/dist/changelog-gen.d.ts +105 -0
  3. package/dist/changelog-gen.js +498 -0
  4. package/dist/changelog-text.d.ts +39 -0
  5. package/dist/changelog-text.js +82 -0
  6. package/dist/cli-support.d.ts +140 -0
  7. package/dist/cli-support.js +244 -0
  8. package/dist/cli-system/app-opts.d.ts +15 -0
  9. package/dist/cli-system/app-opts.js +13 -0
  10. package/dist/cli-system/app.d.ts +29 -0
  11. package/dist/cli-system/app.js +12 -0
  12. package/dist/cli-system/handlers/completions-setup.d.ts +14 -0
  13. package/dist/cli-system/handlers/completions-setup.js +139 -0
  14. package/dist/cli-system/handlers/completions.d.ts +3 -0
  15. package/dist/cli-system/handlers/completions.js +79 -0
  16. package/dist/cli-system/handlers/doctor.d.ts +8 -0
  17. package/dist/cli-system/handlers/doctor.js +146 -0
  18. package/dist/cli-system/handlers/info.d.ts +3 -0
  19. package/dist/cli-system/handlers/info.js +69 -0
  20. package/dist/cli-system/handlers/install.d.ts +8 -0
  21. package/dist/cli-system/handlers/install.js +137 -0
  22. package/dist/cli-system/handlers/mod.d.ts +12 -0
  23. package/dist/cli-system/handlers/mod.js +13 -0
  24. package/dist/cli-system/handlers/uninstall.d.ts +3 -0
  25. package/dist/cli-system/handlers/uninstall.js +60 -0
  26. package/dist/cli-system/handlers/update.d.ts +76 -0
  27. package/dist/cli-system/handlers/update.js +310 -0
  28. package/dist/cli-system/handlers/version-check.d.ts +16 -0
  29. package/dist/cli-system/handlers/version-check.js +176 -0
  30. package/dist/cli-system/handlers/version.d.ts +3 -0
  31. package/dist/cli-system/handlers/version.js +45 -0
  32. package/dist/cli-system/mod.d.ts +19 -0
  33. package/dist/cli-system/mod.js +52 -0
  34. package/dist/commitmsg.d.ts +28 -0
  35. package/dist/commitmsg.js +232 -0
  36. package/dist/directive-analysis.d.ts +75 -0
  37. package/dist/directive-analysis.js +223 -0
  38. package/dist/ffi-client.d.ts +11 -0
  39. package/dist/ffi-client.js +12 -0
  40. package/dist/file-tool.d.ts +96 -0
  41. package/dist/file-tool.js +274 -0
  42. package/dist/file-tools-shared.d.ts +81 -0
  43. package/dist/file-tools-shared.js +276 -0
  44. package/dist/gh-contributors.d.ts +89 -0
  45. package/dist/gh-contributors.js +205 -0
  46. package/dist/gh.d.ts +3 -0
  47. package/dist/gh.js +64 -0
  48. package/dist/git-listing.d.ts +27 -0
  49. package/dist/git-listing.js +69 -0
  50. package/dist/git.d.ts +172 -0
  51. package/dist/git.js +277 -0
  52. package/dist/install.d.ts +34 -0
  53. package/dist/install.js +421 -0
  54. package/dist/main.d.ts +22 -0
  55. package/dist/main.js +14 -0
  56. package/dist/mod.d.ts +25 -0
  57. package/dist/mod.js +8 -0
  58. package/dist/module.d.ts +10 -0
  59. package/dist/module.js +221 -0
  60. package/dist/native-functions.d.ts +1088 -0
  61. package/dist/native-functions.js +2 -0
  62. package/dist/npm-externals.d.ts +27 -0
  63. package/dist/npm-externals.js +34 -0
  64. package/dist/npm-workspace-specifiers.d.ts +6 -0
  65. package/dist/npm-workspace-specifiers.js +45 -0
  66. package/dist/package/loader.d.ts +34 -0
  67. package/dist/package/loader.js +203 -0
  68. package/dist/package/mod.d.ts +36 -0
  69. package/dist/package/mod.js +5 -0
  70. package/dist/package/types.d.ts +142 -0
  71. package/dist/package/types.js +32 -0
  72. package/dist/package/workspace.d.ts +33 -0
  73. package/dist/package/workspace.js +158 -0
  74. package/dist/package/writer.d.ts +52 -0
  75. package/dist/package/writer.js +278 -0
  76. package/dist/package.json +275 -0
  77. package/dist/release-notes.d.ts +90 -0
  78. package/dist/release-notes.js +236 -0
  79. package/dist/release-tag.d.ts +46 -0
  80. package/dist/release-tag.js +95 -0
  81. package/dist/release.d.ts +145 -0
  82. package/dist/release.js +584 -0
  83. package/dist/source-mask.d.ts +3 -0
  84. package/dist/source-mask.js +185 -0
  85. package/dist/validate-bom.d.ts +5 -0
  86. package/dist/validate-bom.js +43 -0
  87. package/dist/validate-case-conflict.d.ts +5 -0
  88. package/dist/validate-case-conflict.js +43 -0
  89. package/dist/validate-circular-deps.d.ts +11 -0
  90. package/dist/validate-circular-deps.js +53 -0
  91. package/dist/validate-code-conventions.d.ts +22 -0
  92. package/dist/validate-code-conventions.js +166 -0
  93. package/dist/validate-commit-msg.d.ts +50 -0
  94. package/dist/validate-commit-msg.js +182 -0
  95. package/dist/validate-docs.d.ts +20 -0
  96. package/dist/validate-docs.js +78 -0
  97. package/dist/validate-eof.d.ts +5 -0
  98. package/dist/validate-eof.js +61 -0
  99. package/dist/validate-error-coverage.d.ts +28 -0
  100. package/dist/validate-error-coverage.js +93 -0
  101. package/dist/validate-export-names.d.ts +17 -0
  102. package/dist/validate-export-names.js +56 -0
  103. package/dist/validate-filenames.d.ts +5 -0
  104. package/dist/validate-filenames.js +151 -0
  105. package/dist/validate-json.d.ts +5 -0
  106. package/dist/validate-json.js +71 -0
  107. package/dist/validate-large-files.d.ts +5 -0
  108. package/dist/validate-large-files.js +41 -0
  109. package/dist/validate-laroux-boundaries.d.ts +19 -0
  110. package/dist/validate-laroux-boundaries.js +59 -0
  111. package/dist/validate-licenses.d.ts +5 -0
  112. package/dist/validate-licenses.js +137 -0
  113. package/dist/validate-line-endings.d.ts +5 -0
  114. package/dist/validate-line-endings.js +47 -0
  115. package/dist/validate-merge-conflict.d.ts +5 -0
  116. package/dist/validate-merge-conflict.js +46 -0
  117. package/dist/validate-mod-exports.d.ts +16 -0
  118. package/dist/validate-mod-exports.js +56 -0
  119. package/dist/validate-naming-and-todos.d.ts +5 -0
  120. package/dist/validate-naming-and-todos.js +70 -0
  121. package/dist/validate-runtime-js-apis.d.ts +5 -0
  122. package/dist/validate-runtime-js-apis.js +78 -0
  123. package/dist/validate-secrets.d.ts +5 -0
  124. package/dist/validate-secrets.js +82 -0
  125. package/dist/validate-self-imports.d.ts +5 -0
  126. package/dist/validate-self-imports.js +78 -0
  127. package/dist/validate-server-loc.d.ts +32 -0
  128. package/dist/validate-server-loc.js +94 -0
  129. package/dist/validate-shebangs.d.ts +5 -0
  130. package/dist/validate-shebangs.js +33 -0
  131. package/dist/validate-stream.d.ts +25 -0
  132. package/dist/validate-stream.js +62 -0
  133. package/dist/validate-submodules.d.ts +5 -0
  134. package/dist/validate-submodules.js +43 -0
  135. package/dist/validate-symlinks.d.ts +5 -0
  136. package/dist/validate-symlinks.js +46 -0
  137. package/dist/validate-toml.d.ts +5 -0
  138. package/dist/validate-toml.js +40 -0
  139. package/dist/validate-trailing-whitespace.d.ts +5 -0
  140. package/dist/validate-trailing-whitespace.js +49 -0
  141. package/dist/validate-yaml.d.ts +5 -0
  142. package/dist/validate-yaml.js +40 -0
  143. package/dist/validation/config.d.ts +17 -0
  144. package/dist/validation/config.js +30 -0
  145. package/dist/validation/mod.d.ts +71 -0
  146. package/dist/validation/mod.js +479 -0
  147. package/dist/validation/registry.d.ts +57 -0
  148. package/dist/validation/registry.js +256 -0
  149. package/dist/validation/types.d.ts +101 -0
  150. package/dist/validation/types.js +2 -0
  151. package/dist/validation/validators/circular-deps.d.ts +7 -0
  152. package/dist/validation/validators/circular-deps.js +31 -0
  153. package/dist/validation/validators/docs.d.ts +7 -0
  154. package/dist/validation/validators/docs.js +38 -0
  155. package/dist/validation/validators/error-coverage.d.ts +2 -0
  156. package/dist/validation/validators/error-coverage.js +46 -0
  157. package/dist/validation/validators/export-names.d.ts +7 -0
  158. package/dist/validation/validators/export-names.js +31 -0
  159. package/dist/validation/validators/laroux-boundaries.d.ts +2 -0
  160. package/dist/validation/validators/laroux-boundaries.js +29 -0
  161. package/dist/validation/validators/mod-exports.d.ts +7 -0
  162. package/dist/validation/validators/mod-exports.js +32 -0
  163. package/dist/validation/validators/mod.d.ts +11 -0
  164. package/dist/validation/validators/mod.js +12 -0
  165. package/dist/validation/validators/server-loc.d.ts +2 -0
  166. package/dist/validation/validators/server-loc.js +48 -0
  167. package/dist/versions.d.ts +166 -0
  168. package/dist/versions.js +349 -0
  169. package/dist/violation-baseline.d.ts +58 -0
  170. package/dist/violation-baseline.js +144 -0
  171. package/dist/walk-stream.d.ts +24 -0
  172. package/dist/walk-stream.js +55 -0
  173. package/dist/workspace-discovery.d.ts +60 -0
  174. package/dist/workspace-discovery.js +130 -0
  175. package/package.json +225 -1
@@ -0,0 +1,498 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * CHANGELOG auto-generation from conventional commits.
4
+ *
5
+ * Reads git history since the last tag, parses conventional commit messages,
6
+ * deduplicates "take" series, and writes a new section to CHANGELOG.md with the
7
+ * notes that were under `## Unreleased`.
8
+ *
9
+ * Library usage:
10
+ * ```typescript
11
+ * import * as changelogGen from "@eserstack/codebase/changelog-gen";
12
+ *
13
+ * // Parse commits into changelog entries
14
+ * const entries = changelogGen.parseConventionalCommits([
15
+ * { subject: "feat(auth): add login", hash: "abc123", body: "" },
16
+ * ]);
17
+ *
18
+ * // Generate a changelog section
19
+ * const section = changelogGen.generateChangelogSection("4.1.2", entries);
20
+ * ```
21
+ *
22
+ * CLI usage:
23
+ * node ./changelog-gen.ts [--dry-run]
24
+ *
25
+ * @module
26
+ */
27
+ import * as primitives from "@eserstack/primitives";
28
+ import * as standards from "@eserstack/standards";
29
+ import * as functions from "@eserstack/functions";
30
+ import * as tui from "@eserstack/shell/tui";
31
+ import * as cliSupport from "./cli-support.js";
32
+ import * as ffiClient from "./ffi-client.js";
33
+ // =============================================================================
34
+ // Commit type → CHANGELOG section mapping
35
+ // =============================================================================
36
+ const SECTION_MAP = {
37
+ feat: "Added",
38
+ fix: "Fixed",
39
+ refactor: "Changed",
40
+ perf: "Changed",
41
+ docs: "Changed",
42
+ revert: "Removed",
43
+ };
44
+ /** Commit types that are skipped (not user-facing) */
45
+ const SKIP_TYPES = new Set(["chore", "ci", "test"]);
46
+ // =============================================================================
47
+ // Pure functions (exported for testing)
48
+ // =============================================================================
49
+ /**
50
+ * Pattern for conventional commit: type(scope): message
51
+ * Also handles: type: message (no scope)
52
+ */
53
+ const CONVENTIONAL_PATTERN = /^(\w+)(?:\(([^)]+)\))?!?:\s{1,5}(.+)$/;
54
+ /**
55
+ * Pattern for "take" suffix: (take II), (take III), (take 2), etc.
56
+ * Supports Roman numerals (I, V, X, L, C, D, M) and Arabic numbers.
57
+ */
58
+ const TAKE_PATTERN = /\s{0,100}\(take\s{1,100}[IVXLCDM\d]+\)\s{0,100}\.?$/i;
59
+ /**
60
+ * Parse a single commit subject as a conventional commit.
61
+ * Returns undefined if the subject doesn't match the conventional format.
62
+ */
63
+ export const parseConventionalCommit = (subject, hash) => {
64
+ const match = subject.match(CONVENTIONAL_PATTERN);
65
+ if (match === null) {
66
+ return undefined;
67
+ }
68
+ return {
69
+ type: match[1].toLowerCase(),
70
+ scope: match[2],
71
+ message: match[3].trim(),
72
+ hash,
73
+ };
74
+ };
75
+ /**
76
+ * Strip the "take" suffix from a message.
77
+ * "authentication system (take II)." → "authentication system."
78
+ * "authentication system (take 3)" → "authentication system"
79
+ */
80
+ export const stripTakeSuffix = (message) => {
81
+ return message.replace(TAKE_PATTERN, "").trim();
82
+ };
83
+ /**
84
+ * Parse an array of git commits into conventional commits.
85
+ * Non-conventional commits are silently skipped.
86
+ */
87
+ export const parseConventionalCommits = (commits) => {
88
+ const result = [];
89
+ for (const commit of commits) {
90
+ const parsed = parseConventionalCommit(commit.subject, commit.hash);
91
+ if (parsed !== undefined) {
92
+ result.push(parsed);
93
+ }
94
+ }
95
+ return result;
96
+ };
97
+ /**
98
+ * Deduplicate commits by stripping "take" suffixes and keeping only the first
99
+ * occurrence of each unique type+message pair.
100
+ */
101
+ export const deduplicateCommits = (commits) => {
102
+ const seen = new Set();
103
+ const result = [];
104
+ for (const commit of commits) {
105
+ const normalized = stripTakeSuffix(commit.message);
106
+ // Normalize trailing punctuation for dedup key comparison
107
+ const keyMsg = normalized.replace(/[.\s]{1,20}$/, "").toLowerCase();
108
+ const key = `${commit.type}:${keyMsg}`;
109
+ if (seen.has(key)) {
110
+ continue;
111
+ }
112
+ seen.add(key);
113
+ result.push({
114
+ ...commit,
115
+ message: normalized,
116
+ });
117
+ }
118
+ return result;
119
+ };
120
+ /**
121
+ * Group commits by CHANGELOG section.
122
+ * Skips commit types that are not user-facing (chore, ci, test).
123
+ */
124
+ export const groupBySection = (commits) => {
125
+ const groups = new Map();
126
+ for (const commit of commits) {
127
+ if (SKIP_TYPES.has(commit.type)) {
128
+ continue;
129
+ }
130
+ const section = SECTION_MAP[commit.type];
131
+ if (section === undefined) {
132
+ continue;
133
+ }
134
+ const group = groups.get(section);
135
+ if (group !== undefined) {
136
+ group.push(commit);
137
+ }
138
+ else {
139
+ groups.set(section, [commit]);
140
+ }
141
+ }
142
+ return groups;
143
+ };
144
+ /**
145
+ * Format a single commit as a markdown list item.
146
+ * With scope: "- **auth:** add login system"
147
+ * Without scope: "- add login system"
148
+ */
149
+ const formatEntry = (commit) => {
150
+ // The wildcard scope "*" names no package, and "**" + "*" + "**" would
151
+ // render as a run of asterisks, so it gets no label.
152
+ if (commit.scope !== undefined && commit.scope !== "*") {
153
+ return `- **${commit.scope}:** ${commit.message}`;
154
+ }
155
+ return `- ${commit.message}`;
156
+ };
157
+ /**
158
+ * Generate a complete CHANGELOG section from grouped commits.
159
+ */
160
+ export const generateChangelogSection = (version, commits) => {
161
+ // Match the Go generator (pkg/ajan/codebasefx/changelog.go): headings are
162
+ // bare. A "## v4.3.1" heading is recognised by neither the Go dedup nor the
163
+ // release-notes parser, so a v-prefixed caller would silently produce a
164
+ // duplicate section and empty release notes.
165
+ const bare = version.replace(/^v/, "");
166
+ const grouped = groupBySection(commits);
167
+ if (grouped.size === 0) {
168
+ const today = new Date().toISOString().split("T")[0];
169
+ return `## ${bare} - ${today}\n\n_Maintenance release._`;
170
+ }
171
+ const today = new Date().toISOString().split("T")[0];
172
+ const lines = [`## ${bare} - ${today}`];
173
+ // Ordered sections matching Keep a Changelog convention
174
+ const sectionOrder = [
175
+ "Added",
176
+ "Changed",
177
+ "Fixed",
178
+ "Removed",
179
+ ];
180
+ for (const section of sectionOrder) {
181
+ const entries = grouped.get(section);
182
+ if (entries === undefined || entries.length === 0) {
183
+ continue;
184
+ }
185
+ lines.push("", `### ${section}`, "");
186
+ for (const entry of entries) {
187
+ lines.push(formatEntry(entry));
188
+ }
189
+ }
190
+ return lines.join("\n");
191
+ };
192
+ /** Matches `## Unreleased`, `## [Unreleased]` and the form with a link. */
193
+ const UNRELEASED_HEADING = /^##\s{1,100}\[?unreleased\]?(\(.{0,1000}\))?\s{0,100}$/i;
194
+ /**
195
+ * The short hash the Go generator ends every entry with. Text a person wrote
196
+ * does not end in one.
197
+ */
198
+ const GENERATED_ENTRY_SUFFIX = /\s\([0-9a-f]{7,40}\)$/;
199
+ /** Section order of the Go generator, which every released section follows. */
200
+ const SUBSECTION_ORDER = ["added", "fixed", "changed", "removed"];
201
+ const isBlank = (line) => line.trim() === "";
202
+ const isIndentedText = (line) => !isBlank(line) && (line.startsWith(" ") || line.startsWith("\t"));
203
+ const normalizeEntry = (text) => text.trim().replace(/\s{1,1000}/g, " ");
204
+ const trimBlankLines = (lines) => {
205
+ let start = 0;
206
+ let end = lines.length;
207
+ while (start < end && isBlank(lines[start])) {
208
+ start++;
209
+ }
210
+ while (end > start && isBlank(lines[end - 1])) {
211
+ end--;
212
+ }
213
+ return lines.slice(start, end);
214
+ };
215
+ /**
216
+ * Follows fenced code blocks, where a line that reads like a heading or a list
217
+ * item is only text. The returned function takes lines in order and tells
218
+ * whether each opens, closes or sits in a fence.
219
+ */
220
+ const createFenceTracker = () => {
221
+ let marker = "";
222
+ let size = 0;
223
+ return (line) => {
224
+ const trimmed = line.trimStart();
225
+ const first = trimmed.charAt(0);
226
+ let run = 0;
227
+ if (first === "`" || first === "~") {
228
+ while (trimmed.charAt(run) === first) {
229
+ run++;
230
+ }
231
+ }
232
+ if (size === 0) {
233
+ // A backtick in the info string makes it an inline code span instead.
234
+ if (run < 3 || (first === "`" && trimmed.slice(run).includes("`"))) {
235
+ return false;
236
+ }
237
+ marker = first;
238
+ size = run;
239
+ return true;
240
+ }
241
+ if (run >= size && first === marker && isBlank(trimmed.slice(run))) {
242
+ size = 0;
243
+ }
244
+ return true;
245
+ };
246
+ };
247
+ /**
248
+ * Cuts lines at each heading with the given prefix outside a fence. Each block
249
+ * starts with its heading; `head` holds the lines before the first one.
250
+ */
251
+ const splitAtHeadings = (lines, prefix) => {
252
+ const inFence = createFenceTracker();
253
+ const starts = [];
254
+ lines.forEach((line, index) => {
255
+ if (!inFence(line) && line.startsWith(prefix)) {
256
+ starts.push(index);
257
+ }
258
+ });
259
+ return {
260
+ head: starts.length === 0 ? lines : lines.slice(0, starts[0]),
261
+ blocks: starts.map((start, i) => lines.slice(start, starts[i + 1])),
262
+ };
263
+ };
264
+ /**
265
+ * Appends `b` to `a`. Two lists stay one tight list, since a blank line between
266
+ * them would make oxfmt space every item of the result.
267
+ */
268
+ const joinBodies = (first, second) => {
269
+ const a = trimBlankLines(first);
270
+ const b = trimBlankLines(second);
271
+ if (a.length === 0 || b.length === 0) {
272
+ return [...a, ...b];
273
+ }
274
+ const last = a[a.length - 1];
275
+ const tight = (last.startsWith("- ") || last.startsWith(" ")) && b[0].startsWith("- ");
276
+ return tight ? [...a, ...b] : [...a, "", ...b];
277
+ };
278
+ /**
279
+ * Removes the entries an earlier run generated from a subsection's body: list
280
+ * items that end in a commit hash or that the new section lists again. An item
281
+ * with more paragraphs was written by a person.
282
+ */
283
+ const dropGeneratedEntries = (body, regenerated) => {
284
+ const inFence = createFenceTracker();
285
+ const kept = [];
286
+ let i = 0;
287
+ while (i < body.length) {
288
+ if (inFence(body[i]) || !body[i].startsWith("- ")) {
289
+ kept.push(body[i]);
290
+ i++;
291
+ continue;
292
+ }
293
+ let end = i + 1;
294
+ while (end < body.length && isIndentedText(body[end])) {
295
+ end++;
296
+ }
297
+ let next = end;
298
+ while (next < body.length && isBlank(body[next])) {
299
+ next++;
300
+ }
301
+ const entry = normalizeEntry(body.slice(i, end).join(" "));
302
+ const generated = regenerated.has(entry) || GENERATED_ENTRY_SUFFIX.test(entry);
303
+ const continues = next < body.length && isIndentedText(body[next]);
304
+ if (!generated || continues) {
305
+ kept.push(body[i]);
306
+ i++;
307
+ continue;
308
+ }
309
+ i = end;
310
+ while (i < body.length &&
311
+ isBlank(body[i]) &&
312
+ (kept.length === 0 || isBlank(kept[kept.length - 1]))) {
313
+ i++;
314
+ }
315
+ }
316
+ return kept;
317
+ };
318
+ const subsectionTitle = (heading) => heading.replace(/^### /, "").trim();
319
+ /** Generated sections in their order, then every other subsection. */
320
+ const subsectionRank = (title) => {
321
+ const rank = SUBSECTION_ORDER.indexOf(title.toLowerCase());
322
+ return rank === -1 ? SUBSECTION_ORDER.length : rank;
323
+ };
324
+ /**
325
+ * Builds a version's section from the generated section, the body the version's
326
+ * section already has on a re-run, and the notes that were under Unreleased.
327
+ *
328
+ * The order follows the CHANGELOG.md style: text directly under the heading,
329
+ * then the sections in the generator's order, then Migration and any other
330
+ * hand-written subsection. A hand-written list joins the generated section of
331
+ * its name. On a re-run the old generated entries go, since the new section
332
+ * lists them again; everything else in the old body was written by a person
333
+ * and stays.
334
+ */
335
+ const mergeReleaseSection = (newSection, previous, notes) => {
336
+ const generated = splitAtHeadings(newSection.split("\n"), "### ");
337
+ const [heading = "", ...restOfHead] = trimBlankLines(generated.head);
338
+ const generatedText = trimBlankLines(restOfHead);
339
+ const subsections = [];
340
+ const addSubsection = (subsectionHeading, body) => {
341
+ const title = subsectionTitle(subsectionHeading);
342
+ const existing = subsections.find((subsection) => subsection.title.toLowerCase() === title.toLowerCase());
343
+ if (existing !== undefined) {
344
+ existing.body = joinBodies(existing.body, body);
345
+ return;
346
+ }
347
+ subsections.push({
348
+ heading: subsectionHeading,
349
+ title,
350
+ body: trimBlankLines(body),
351
+ });
352
+ };
353
+ const regenerated = new Set();
354
+ for (const [subsectionHeading, ...body] of generated.blocks) {
355
+ addSubsection(subsectionHeading, body);
356
+ for (const line of body) {
357
+ if (line.startsWith("- ")) {
358
+ regenerated.add(normalizeEntry(line));
359
+ }
360
+ }
361
+ }
362
+ const old = splitAtHeadings(previous, "### ");
363
+ const moved = splitAtHeadings(notes, "### ");
364
+ const oldText = trimBlankLines(old.head);
365
+ const sameText = oldText.length === generatedText.length &&
366
+ oldText.every((line, i) => line === generatedText[i]);
367
+ const text = joinBodies(sameText ? generatedText : joinBodies(generatedText, oldText), moved.head);
368
+ for (const [subsectionHeading, ...body] of old.blocks) {
369
+ const isGeneratedName = subsectionRank(subsectionTitle(subsectionHeading)) <
370
+ SUBSECTION_ORDER.length;
371
+ addSubsection(subsectionHeading, isGeneratedName ? dropGeneratedEntries(body, regenerated) : body);
372
+ }
373
+ for (const [subsectionHeading, ...body] of moved.blocks) {
374
+ addSubsection(subsectionHeading, body);
375
+ }
376
+ const ordered = subsections.toSorted((a, b) => subsectionRank(a.title) - subsectionRank(b.title));
377
+ const result = text.length > 0 ? [heading, "", ...text] : [heading];
378
+ for (const subsection of ordered) {
379
+ if (subsection.body.length > 0) {
380
+ result.push("", subsection.heading, "", ...subsection.body);
381
+ }
382
+ }
383
+ return result;
384
+ };
385
+ /** Whether a heading line is the version's, in the bare or the legacy style. */
386
+ const isVersionHeading = (line, bare) => {
387
+ const stripped = line.trim();
388
+ return (stripped === `## ${bare}` ||
389
+ stripped.startsWith(`## ${bare} `) ||
390
+ stripped.startsWith(`## [${bare}]`) ||
391
+ stripped.startsWith(`## [v${bare}]`));
392
+ };
393
+ /**
394
+ * Writes a version's section into CHANGELOG.md content and moves the notes under
395
+ * `## Unreleased` into it, leaving that heading empty above the section. This is
396
+ * the same layout as InsertIntoChangelog in pkg/ajan/codebasefx, which is what a
397
+ * release runs: {@link generateChangelog} calls the Go generator through the
398
+ * bridge, and a Go test compares the two on the same cases.
399
+ *
400
+ * The section goes below Unreleased, or first when there is no Unreleased. An
401
+ * existing section of the version is replaced in place, and the text in it a
402
+ * person wrote stays.
403
+ *
404
+ * @param version - The version string to check for duplicates (e.g., "4.1.2")
405
+ */
406
+ export const insertIntoChangelog = (changelogContent, newSection, version) => {
407
+ const { head, blocks } = splitAtHeadings(changelogContent.split("\n"), "## ");
408
+ const unreleased = blocks.filter((block) => UNRELEASED_HEADING.test(block[0]));
409
+ const rest = blocks.filter((block) => !UNRELEASED_HEADING.test(block[0]));
410
+ const notes = unreleased.flatMap((block) => ["", ...block.slice(1)]);
411
+ const bare = version?.replace(/^v/, "");
412
+ const existing = bare === undefined || bare === ""
413
+ ? -1
414
+ : rest.findIndex((block) => isVersionHeading(block[0], bare));
415
+ const merged = mergeReleaseSection(newSection, existing === -1 ? [] : rest[existing].slice(1), notes);
416
+ if (existing === -1) {
417
+ rest.unshift(merged);
418
+ }
419
+ else {
420
+ rest[existing] = merged;
421
+ }
422
+ const parts = [
423
+ head,
424
+ ...(unreleased.length > 0 ? [unreleased[0].slice(0, 1)] : []),
425
+ ...rest,
426
+ ]
427
+ .map((block) => trimBlankLines(block))
428
+ .filter((block) => block.length > 0)
429
+ .map((block) => block.join("\n"));
430
+ return `${parts.join("\n\n")}\n`;
431
+ };
432
+ // =============================================================================
433
+ // Main logic
434
+ // =============================================================================
435
+ /**
436
+ * Generate a changelog entry from conventional commits since the last tag and
437
+ * write it to CHANGELOG.md, moving the notes under `## Unreleased` into it. The
438
+ * Go generator does the work, so this needs the native library, and `content`
439
+ * holds the generated entries only. A dry run writes nothing.
440
+ */
441
+ export const generateChangelog = async (options = {}) => {
442
+ const lib = await ffiClient.requireLib();
443
+ const parsed = lib.call("codebaseGenerateChangelog", {
444
+ dir: options.root ?? ".",
445
+ // Omitted when undefined, which leaves the Go-side fallback in charge.
446
+ version: options.version,
447
+ dryRun: options.dryRun ?? false,
448
+ });
449
+ if ("error" in parsed) {
450
+ throw new Error(parsed.error);
451
+ }
452
+ return parsed;
453
+ };
454
+ // =============================================================================
455
+ // CLI interface (Handler/Adapter/ResponseMapper pattern)
456
+ // =============================================================================
457
+ /** Handler: wraps generateChangelog as a Task via fromPromise. */
458
+ export const generateChangelogHandler = (input) => functions.task.fromPromise(() => generateChangelog(input));
459
+ /** Adapter: CliEvent → GenerateChangelogOptions */
460
+ const cliAdapter = (event) => primitives.results.ok({ dryRun: event.flags["dry-run"] === true });
461
+ /** ResponseMapper: formats GenerateChangelogResult for CLI output. */
462
+ const cliResponseMapper = (result) => {
463
+ const { ctx } = cliSupport.getCliContext();
464
+ if (primitives.results.isFail(result)) {
465
+ const message = result.error instanceof Error
466
+ ? result.error.message
467
+ : String(result.error);
468
+ tui.log.error(ctx, message);
469
+ return primitives.results.fail({ exitCode: 1 });
470
+ }
471
+ const { value } = result;
472
+ if (value.dryRun) {
473
+ tui.log.warn(ctx, "[DRY RUN] Generated changelog preview:");
474
+ tui.log.info(ctx, `\n${value.content}`);
475
+ }
476
+ else {
477
+ tui.log.success(ctx, `Added ${value.entryCount} entries to CHANGELOG.md for v${value.version}`);
478
+ }
479
+ return primitives.results.ok(undefined);
480
+ };
481
+ /** Runnable CLI trigger for changelog-gen. */
482
+ export const handleCli = functions.handler.createTrigger({
483
+ handler: generateChangelogHandler,
484
+ adaptInput: cliAdapter,
485
+ adaptOutput: cliResponseMapper,
486
+ });
487
+ /** Parse the changelog-gen arguments: `--dry-run` (`-n`). */
488
+ export const parseCliArgs = (cliArgs) => cliSupport.parseCliEvent("changelog-gen", cliArgs, {
489
+ "dry-run": { type: "boolean", short: "n" },
490
+ });
491
+ /** CLI entry point. */
492
+ export const main = async (cliArgs) => await handleCli(parseCliArgs(cliArgs));
493
+ if (import.meta.main) {
494
+ // Entry point: the await only runs when this file is executed directly.
495
+ // oxlint-disable-next-line node/no-top-level-await
496
+ const result = await main(standards.crossRuntime.runtime.process.args);
497
+ cliSupport.runCliMain(result, cliSupport.getCliContext().output);
498
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * CHANGELOG.md parsing with no imports, so a release job can extract notes
3
+ * with a bare `node` and nothing installed from a registry.
4
+ *
5
+ * @module
6
+ */
7
+ /**
8
+ * A parsed entry from a CHANGELOG.md file.
9
+ */
10
+ export type ChangelogEntry = {
11
+ /** Version string (e.g., "4.0.43") */
12
+ readonly version: string;
13
+ /** Release date (e.g., "2024-07-16"), empty if not specified */
14
+ readonly date: string;
15
+ /** Git tag (e.g., "v4.0.43") */
16
+ readonly tag: string;
17
+ /** Formatted release notes markdown */
18
+ readonly notes: string;
19
+ };
20
+ /**
21
+ * Matches a release heading: `## 1.2.3 - 2026-01-01`, or the legacy
22
+ * `## [v1.2.3] - 2026-01-01`. The validate job in build.yml mirrors it.
23
+ */
24
+ export declare const HEADING_PATTERN: RegExp;
25
+ /**
26
+ * Normalizes a tag string by stripping `refs/tags/` prefix and ensuring a `v` prefix.
27
+ *
28
+ * @param rawTag - The raw tag string
29
+ * @returns Normalized tag with `v` prefix
30
+ */
31
+ export declare const normalizeTag: (rawTag: string) => string;
32
+ /**
33
+ * Parses raw changelog text into structured entries.
34
+ * This is a pure function with no I/O — useful for testing.
35
+ *
36
+ * @param text - Raw CHANGELOG.md content
37
+ * @returns Array of changelog entries, most recent first
38
+ */
39
+ export declare const parseChangelogText: (text: string) => ChangelogEntry[];
@@ -0,0 +1,82 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ /**
3
+ * CHANGELOG.md parsing with no imports, so a release job can extract notes
4
+ * with a bare `node` and nothing installed from a registry.
5
+ *
6
+ * @module
7
+ */
8
+ /**
9
+ * Matches a release heading: `## 1.2.3 - 2026-01-01`, or the legacy
10
+ * `## [v1.2.3] - 2026-01-01`. The validate job in build.yml mirrors it.
11
+ */
12
+ export const HEADING_PATTERN = /^##\s{1,100}\[?([^\]\s]+)\]?\s{0,100}-?\s{0,100}([0-9]{4}-[0-9]{2}-[0-9]{2})?\s{0,100}$/;
13
+ /**
14
+ * Normalizes a tag string by stripping `refs/tags/` prefix and ensuring a `v` prefix.
15
+ *
16
+ * @param rawTag - The raw tag string
17
+ * @returns Normalized tag with `v` prefix
18
+ */
19
+ export const normalizeTag = (rawTag) => {
20
+ const trimmed = rawTag.trim().replace(/^refs\/tags\//, "");
21
+ return trimmed.startsWith("v") ? trimmed : `v${trimmed}`;
22
+ };
23
+ /**
24
+ * Parses raw changelog text into structured entries.
25
+ * This is a pure function with no I/O — useful for testing.
26
+ *
27
+ * @param text - Raw CHANGELOG.md content
28
+ * @returns Array of changelog entries, most recent first
29
+ */
30
+ export const parseChangelogText = (text) => {
31
+ const lines = text.split(/\r?\n/);
32
+ const headings = [];
33
+ for (let index = 0; index < lines.length; index += 1) {
34
+ const line = lines[index];
35
+ const m = line.match(HEADING_PATTERN);
36
+ if (m === null) {
37
+ continue;
38
+ }
39
+ // The file carries both heading styles: bare "## 1.2.3 - date" from the
40
+ // current generator and legacy "## [v1.2.3] - date" sections. Strip the
41
+ // `v` first, or the legacy ones fail the digit test below and vanish from
42
+ // the parse entirely.
43
+ const version = m[1].replace(/^v/, "");
44
+ // Skip non-version headings like [Unreleased]
45
+ if (!/^\d/.test(version)) {
46
+ continue;
47
+ }
48
+ headings.push({
49
+ version,
50
+ date: m[2] ?? "",
51
+ headingLineIndex: index,
52
+ });
53
+ }
54
+ if (headings.length === 0) {
55
+ return [];
56
+ }
57
+ return headings.map((heading, index) => {
58
+ const nextHeading = headings[index + 1];
59
+ const bodyStart = heading.headingLineIndex + 1;
60
+ const bodyEnd = nextHeading !== undefined ? nextHeading.headingLineIndex : lines.length;
61
+ const bodyLines = lines.slice(bodyStart, bodyEnd);
62
+ while (bodyLines.length > 0 && bodyLines[0].trim() === "") {
63
+ bodyLines.shift();
64
+ }
65
+ while (bodyLines.length > 0 &&
66
+ bodyLines[bodyLines.length - 1].trim() === "") {
67
+ bodyLines.pop();
68
+ }
69
+ const notesParts = [
70
+ `## ${heading.version}${heading.date !== "" ? ` - ${heading.date}` : ""}`,
71
+ ];
72
+ if (bodyLines.length > 0) {
73
+ notesParts.push("", ...bodyLines);
74
+ }
75
+ return {
76
+ version: heading.version,
77
+ date: heading.date,
78
+ tag: `v${heading.version}`,
79
+ notes: `${notesParts.join("\n").trim()}\n`,
80
+ };
81
+ });
82
+ };