@releasekit/notes 0.3.0 → 0.4.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.
@@ -0,0 +1,1757 @@
1
+ import {
2
+ EXIT_CODES,
3
+ ReleaseKitError,
4
+ debug,
5
+ formatVersion,
6
+ info,
7
+ success,
8
+ warn,
9
+ writeMarkdown
10
+ } from "./chunk-7TJSPQPW.js";
11
+
12
+ // ../config/dist/index.js
13
+ import * as fs from "fs";
14
+ import * as path from "path";
15
+ import * as TOML from "smol-toml";
16
+ import * as fs3 from "fs";
17
+ import * as path3 from "path";
18
+ import { z as z2 } from "zod";
19
+ import { z } from "zod";
20
+ import * as fs2 from "fs";
21
+ import * as os from "os";
22
+ import * as path2 from "path";
23
+ var ConfigError = class extends ReleaseKitError {
24
+ code = "CONFIG_ERROR";
25
+ suggestions;
26
+ constructor(message, suggestions) {
27
+ super(message);
28
+ this.suggestions = suggestions ?? [
29
+ "Check that releasekit.config.json exists and is valid JSON",
30
+ "Run with --verbose for more details"
31
+ ];
32
+ }
33
+ };
34
+ var MAX_JSONC_LENGTH = 1e5;
35
+ function parseJsonc(content) {
36
+ if (content.length > MAX_JSONC_LENGTH) {
37
+ throw new Error(`JSONC content too long: ${content.length} characters (max ${MAX_JSONC_LENGTH})`);
38
+ }
39
+ try {
40
+ return JSON.parse(content);
41
+ } catch {
42
+ const cleaned = content.replace(/\/\/[^\r\n]{0,10000}$/gm, "").replace(/\/\*[\s\S]{0,50000}?\*\//g, "").trim();
43
+ return JSON.parse(cleaned);
44
+ }
45
+ }
46
+ var GitConfigSchema = z.object({
47
+ remote: z.string().default("origin"),
48
+ branch: z.string().default("main"),
49
+ pushMethod: z.enum(["auto", "ssh", "https"]).default("auto"),
50
+ /**
51
+ * Optional env var name containing a GitHub token for HTTPS pushes.
52
+ * When set, publish steps can use this token without mutating git remotes.
53
+ */
54
+ httpsTokenEnv: z.string().optional(),
55
+ push: z.boolean().optional(),
56
+ skipHooks: z.boolean().optional()
57
+ });
58
+ var MonorepoConfigSchema = z.object({
59
+ mode: z.enum(["root", "packages", "both"]).optional(),
60
+ rootPath: z.string().optional(),
61
+ packagesPath: z.string().optional(),
62
+ mainPackage: z.string().optional()
63
+ });
64
+ var BranchPatternSchema = z.object({
65
+ pattern: z.string(),
66
+ releaseType: z.enum(["major", "minor", "patch", "prerelease"])
67
+ });
68
+ var VersionCargoConfigSchema = z.object({
69
+ enabled: z.boolean().default(true),
70
+ paths: z.array(z.string()).optional()
71
+ });
72
+ var VersionConfigSchema = z.object({
73
+ tagTemplate: z.string().default("v{version}"),
74
+ packageSpecificTags: z.boolean().default(false),
75
+ preset: z.string().default("conventional"),
76
+ sync: z.boolean().default(true),
77
+ packages: z.array(z.string()).default([]),
78
+ mainPackage: z.string().optional(),
79
+ updateInternalDependencies: z.enum(["major", "minor", "patch", "no-internal-update"]).default("minor"),
80
+ skip: z.array(z.string()).optional(),
81
+ commitMessage: z.string().optional(),
82
+ versionStrategy: z.enum(["branchPattern", "commitMessage"]).default("commitMessage"),
83
+ branchPatterns: z.array(BranchPatternSchema).optional(),
84
+ defaultReleaseType: z.enum(["major", "minor", "patch", "prerelease"]).optional(),
85
+ mismatchStrategy: z.enum(["error", "warn", "ignore", "prefer-package", "prefer-git"]).default("warn"),
86
+ versionPrefix: z.string().default(""),
87
+ prereleaseIdentifier: z.string().optional(),
88
+ strictReachable: z.boolean().default(false),
89
+ cargo: VersionCargoConfigSchema.optional()
90
+ });
91
+ var NpmConfigSchema = z.object({
92
+ enabled: z.boolean().default(true),
93
+ auth: z.enum(["auto", "oidc", "token"]).default("auto"),
94
+ provenance: z.boolean().default(true),
95
+ access: z.enum(["public", "restricted"]).default("public"),
96
+ registry: z.string().default("https://registry.npmjs.org"),
97
+ copyFiles: z.array(z.string()).default(["LICENSE"]),
98
+ tag: z.string().default("latest")
99
+ });
100
+ var CargoPublishConfigSchema = z.object({
101
+ enabled: z.boolean().default(false),
102
+ noVerify: z.boolean().default(false),
103
+ publishOrder: z.array(z.string()).default([]),
104
+ clean: z.boolean().default(false)
105
+ });
106
+ var PublishGitConfigSchema = z.object({
107
+ push: z.boolean().default(true),
108
+ pushMethod: z.enum(["auto", "ssh", "https"]).optional(),
109
+ remote: z.string().optional(),
110
+ branch: z.string().optional(),
111
+ httpsTokenEnv: z.string().optional(),
112
+ skipHooks: z.boolean().optional()
113
+ });
114
+ var GitHubReleaseConfigSchema = z.object({
115
+ enabled: z.boolean().default(true),
116
+ draft: z.boolean().default(true),
117
+ perPackage: z.boolean().default(true),
118
+ prerelease: z.union([z.literal("auto"), z.boolean()]).default("auto"),
119
+ /**
120
+ * Controls the source for the GitHub release body.
121
+ * - 'auto': Use release notes if enabled, else changelog, else GitHub auto-generated.
122
+ * - 'releaseNotes': Use LLM-generated release notes (requires notes.releaseNotes.enabled: true).
123
+ * - 'changelog': Use formatted changelog entries.
124
+ * - 'generated': Use GitHub's auto-generated notes.
125
+ * - 'none': No body.
126
+ */
127
+ body: z.enum(["auto", "releaseNotes", "changelog", "generated", "none"]).default("auto")
128
+ });
129
+ var VerifyRegistryConfigSchema = z.object({
130
+ enabled: z.boolean().default(true),
131
+ maxAttempts: z.number().int().positive().default(5),
132
+ initialDelay: z.number().int().positive().default(15e3),
133
+ backoffMultiplier: z.number().positive().default(2)
134
+ });
135
+ var VerifyConfigSchema = z.object({
136
+ npm: VerifyRegistryConfigSchema.default({
137
+ enabled: true,
138
+ maxAttempts: 5,
139
+ initialDelay: 15e3,
140
+ backoffMultiplier: 2
141
+ }),
142
+ cargo: VerifyRegistryConfigSchema.default({
143
+ enabled: true,
144
+ maxAttempts: 10,
145
+ initialDelay: 3e4,
146
+ backoffMultiplier: 2
147
+ })
148
+ });
149
+ var PublishConfigSchema = z.object({
150
+ git: PublishGitConfigSchema.optional(),
151
+ npm: NpmConfigSchema.default({
152
+ enabled: true,
153
+ auth: "auto",
154
+ provenance: true,
155
+ access: "public",
156
+ registry: "https://registry.npmjs.org",
157
+ copyFiles: ["LICENSE"],
158
+ tag: "latest"
159
+ }),
160
+ cargo: CargoPublishConfigSchema.default({
161
+ enabled: false,
162
+ noVerify: false,
163
+ publishOrder: [],
164
+ clean: false
165
+ }),
166
+ githubRelease: GitHubReleaseConfigSchema.default({
167
+ enabled: true,
168
+ draft: true,
169
+ perPackage: true,
170
+ prerelease: "auto",
171
+ body: "auto"
172
+ }),
173
+ verify: VerifyConfigSchema.default({
174
+ npm: {
175
+ enabled: true,
176
+ maxAttempts: 5,
177
+ initialDelay: 15e3,
178
+ backoffMultiplier: 2
179
+ },
180
+ cargo: {
181
+ enabled: true,
182
+ maxAttempts: 10,
183
+ initialDelay: 3e4,
184
+ backoffMultiplier: 2
185
+ }
186
+ })
187
+ });
188
+ var TemplateConfigSchema = z.object({
189
+ path: z.string().optional(),
190
+ engine: z.enum(["handlebars", "liquid", "ejs"]).optional()
191
+ });
192
+ var LocationModeSchema = z.enum(["root", "packages", "both"]);
193
+ var ChangelogConfigSchema = z.object({
194
+ mode: LocationModeSchema.optional(),
195
+ file: z.string().optional(),
196
+ templates: TemplateConfigSchema.optional()
197
+ });
198
+ var LLMOptionsSchema = z.object({
199
+ timeout: z.number().optional(),
200
+ maxTokens: z.number().optional(),
201
+ temperature: z.number().optional()
202
+ });
203
+ var LLMRetryConfigSchema = z.object({
204
+ maxAttempts: z.number().int().positive().optional(),
205
+ initialDelay: z.number().nonnegative().optional(),
206
+ maxDelay: z.number().positive().optional(),
207
+ backoffFactor: z.number().positive().optional()
208
+ });
209
+ var LLMTasksConfigSchema = z.object({
210
+ summarize: z.boolean().optional(),
211
+ enhance: z.boolean().optional(),
212
+ categorize: z.boolean().optional(),
213
+ releaseNotes: z.boolean().optional()
214
+ });
215
+ var LLMCategorySchema = z.object({
216
+ name: z.string(),
217
+ description: z.string(),
218
+ scopes: z.array(z.string()).optional()
219
+ });
220
+ var ScopeRulesSchema = z.object({
221
+ allowed: z.array(z.string()).optional(),
222
+ caseSensitive: z.boolean().default(false),
223
+ invalidScopeAction: z.enum(["remove", "keep", "fallback"]).default("remove"),
224
+ fallbackScope: z.string().optional()
225
+ });
226
+ var ScopeConfigSchema = z.object({
227
+ mode: z.enum(["restricted", "packages", "none", "unrestricted"]).default("unrestricted"),
228
+ rules: ScopeRulesSchema.optional()
229
+ });
230
+ var LLMPromptOverridesSchema = z.object({
231
+ enhance: z.string().optional(),
232
+ categorize: z.string().optional(),
233
+ enhanceAndCategorize: z.string().optional(),
234
+ summarize: z.string().optional(),
235
+ releaseNotes: z.string().optional()
236
+ });
237
+ var LLMPromptsConfigSchema = z.object({
238
+ instructions: LLMPromptOverridesSchema.optional(),
239
+ templates: LLMPromptOverridesSchema.optional()
240
+ });
241
+ var LLMConfigSchema = z.object({
242
+ provider: z.string(),
243
+ model: z.string(),
244
+ baseURL: z.string().optional(),
245
+ apiKey: z.string().optional(),
246
+ options: LLMOptionsSchema.optional(),
247
+ concurrency: z.number().int().positive().optional(),
248
+ retry: LLMRetryConfigSchema.optional(),
249
+ tasks: LLMTasksConfigSchema.optional(),
250
+ categories: z.array(LLMCategorySchema).optional(),
251
+ style: z.string().optional(),
252
+ scopes: ScopeConfigSchema.optional(),
253
+ prompts: LLMPromptsConfigSchema.optional()
254
+ });
255
+ var ReleaseNotesConfigSchema = z.object({
256
+ mode: LocationModeSchema.optional(),
257
+ file: z.string().optional(),
258
+ templates: TemplateConfigSchema.optional(),
259
+ llm: LLMConfigSchema.optional()
260
+ });
261
+ var NotesInputConfigSchema = z.object({
262
+ source: z.string().optional(),
263
+ file: z.string().optional()
264
+ });
265
+ var NotesConfigSchema = z.object({
266
+ changelog: z.union([z.literal(false), ChangelogConfigSchema]).optional(),
267
+ releaseNotes: z.union([z.literal(false), ReleaseNotesConfigSchema]).optional(),
268
+ updateStrategy: z.enum(["prepend", "regenerate"]).optional()
269
+ });
270
+ var CILabelsConfigSchema = z.object({
271
+ stable: z.string().default("release:stable"),
272
+ prerelease: z.string().default("release:prerelease"),
273
+ skip: z.string().default("release:skip"),
274
+ major: z.string().default("release:major"),
275
+ minor: z.string().default("release:minor"),
276
+ patch: z.string().default("release:patch")
277
+ });
278
+ var CIConfigSchema = z.object({
279
+ releaseStrategy: z.enum(["manual", "direct", "standing-pr", "scheduled"]).default("direct"),
280
+ releaseTrigger: z.enum(["commit", "label"]).default("label"),
281
+ prPreview: z.boolean().default(true),
282
+ autoRelease: z.boolean().default(false),
283
+ /**
284
+ * Commit message prefixes that should not trigger a release.
285
+ * Defaults to `['chore: release ']` to match the release commit template
286
+ * (`chore: release ${packageName} v${version}`) and provide a
287
+ * secondary loop-prevention guard alongside `[skip ci]`.
288
+ */
289
+ skipPatterns: z.array(z.string()).default(["chore: release "]),
290
+ minChanges: z.number().int().positive().default(1),
291
+ labels: CILabelsConfigSchema.default({
292
+ stable: "release:stable",
293
+ prerelease: "release:prerelease",
294
+ skip: "release:skip",
295
+ major: "release:major",
296
+ minor: "release:minor",
297
+ patch: "release:patch"
298
+ })
299
+ });
300
+ var ReleaseCIConfigSchema = z.object({
301
+ skipPatterns: z.array(z.string().min(1)).optional(),
302
+ minChanges: z.number().int().positive().optional(),
303
+ /** Set to `false` to disable GitHub release creation in CI. */
304
+ githubRelease: z.literal(false).optional(),
305
+ /** Set to `false` to disable changelog generation in CI. */
306
+ notes: z.literal(false).optional()
307
+ });
308
+ var ReleaseConfigSchema = z.object({
309
+ /**
310
+ * Optional steps to enable. The version step always runs; only 'notes' and
311
+ * 'publish' can be opted out. Omitting a step is equivalent to --skip-<step>.
312
+ */
313
+ steps: z.array(z.enum(["notes", "publish"])).min(1).optional(),
314
+ ci: ReleaseCIConfigSchema.optional()
315
+ });
316
+ var ReleaseKitConfigSchema = z.object({
317
+ git: GitConfigSchema.optional(),
318
+ monorepo: MonorepoConfigSchema.optional(),
319
+ version: VersionConfigSchema.optional(),
320
+ publish: PublishConfigSchema.optional(),
321
+ notes: NotesConfigSchema.optional(),
322
+ ci: CIConfigSchema.optional(),
323
+ release: ReleaseConfigSchema.optional()
324
+ });
325
+ var MAX_INPUT_LENGTH = 1e4;
326
+ function substituteVariables(value) {
327
+ if (value.length > MAX_INPUT_LENGTH) {
328
+ throw new Error(`Input too long: ${value.length} characters (max ${MAX_INPUT_LENGTH})`);
329
+ }
330
+ const envPattern = /\{env:([^}]{1,1000})\}/g;
331
+ const filePattern = /\{file:([^}]{1,1000})\}/g;
332
+ let result = value;
333
+ result = result.replace(envPattern, (_, varName) => {
334
+ return process.env[varName] ?? "";
335
+ });
336
+ result = result.replace(filePattern, (_, filePath) => {
337
+ const expandedPath = filePath.startsWith("~") ? path2.join(os.homedir(), filePath.slice(1)) : filePath;
338
+ try {
339
+ return fs2.readFileSync(expandedPath, "utf-8").trim();
340
+ } catch {
341
+ return "";
342
+ }
343
+ });
344
+ return result;
345
+ }
346
+ var SOLE_REFERENCE_PATTERN = /^\{(?:env|file):[^}]+\}$/;
347
+ function substituteInObject(obj) {
348
+ if (typeof obj === "string") {
349
+ const result = substituteVariables(obj);
350
+ if (result === "" && SOLE_REFERENCE_PATTERN.test(obj)) {
351
+ return void 0;
352
+ }
353
+ return result;
354
+ }
355
+ if (Array.isArray(obj)) {
356
+ return obj.map((item) => substituteInObject(item));
357
+ }
358
+ if (obj && typeof obj === "object") {
359
+ const result = {};
360
+ for (const [key, value] of Object.entries(obj)) {
361
+ result[key] = substituteInObject(value);
362
+ }
363
+ return result;
364
+ }
365
+ return obj;
366
+ }
367
+ var AUTH_DIR = path2.join(os.homedir(), ".config", "releasekit");
368
+ var AUTH_FILE = path2.join(AUTH_DIR, "auth.json");
369
+ function loadAuth() {
370
+ if (fs2.existsSync(AUTH_FILE)) {
371
+ try {
372
+ const content = fs2.readFileSync(AUTH_FILE, "utf-8");
373
+ return JSON.parse(content);
374
+ } catch {
375
+ return {};
376
+ }
377
+ }
378
+ return {};
379
+ }
380
+ function saveAuth(provider, apiKey) {
381
+ if (!fs2.existsSync(AUTH_DIR)) {
382
+ fs2.mkdirSync(AUTH_DIR, { recursive: true });
383
+ }
384
+ const existing = loadAuth();
385
+ existing[provider] = apiKey;
386
+ fs2.writeFileSync(AUTH_FILE, JSON.stringify(existing, null, 2), { encoding: "utf-8", mode: 384 });
387
+ }
388
+ var CONFIG_FILE = "releasekit.config.json";
389
+ function loadConfigFile(configPath) {
390
+ if (!fs3.existsSync(configPath)) {
391
+ return {};
392
+ }
393
+ try {
394
+ const content = fs3.readFileSync(configPath, "utf-8");
395
+ const parsed = parseJsonc(content);
396
+ const substituted = substituteInObject(parsed);
397
+ return ReleaseKitConfigSchema.parse(substituted);
398
+ } catch (error) {
399
+ if (error instanceof z2.ZodError) {
400
+ const issues = error.issues.map((i) => ` ${i.path.join(".")}: ${i.message}`).join("\n");
401
+ throw new ConfigError(`Config validation errors:
402
+ ${issues}`);
403
+ }
404
+ if (error instanceof SyntaxError) {
405
+ throw new ConfigError(`Invalid JSON in config file: ${error.message}`);
406
+ }
407
+ throw error;
408
+ }
409
+ }
410
+ function loadConfig(options) {
411
+ const cwd = options?.cwd ?? process.cwd();
412
+ const configPath = options?.configPath ?? path3.join(cwd, CONFIG_FILE);
413
+ return loadConfigFile(configPath);
414
+ }
415
+
416
+ // src/errors/index.ts
417
+ var NotesError = class extends ReleaseKitError {
418
+ };
419
+ var InputParseError = class extends NotesError {
420
+ code = "INPUT_PARSE_ERROR";
421
+ suggestions = [
422
+ "Ensure input is valid JSON",
423
+ "Check that input matches expected schema",
424
+ "Use --input-source to specify format"
425
+ ];
426
+ };
427
+ var TemplateError = class extends NotesError {
428
+ code = "TEMPLATE_ERROR";
429
+ suggestions = [
430
+ "Check template syntax",
431
+ "Ensure all required files exist (document, version, entry)",
432
+ "Verify template engine matches file extension"
433
+ ];
434
+ };
435
+ var LLMError = class extends NotesError {
436
+ code = "LLM_ERROR";
437
+ suggestions = [
438
+ "Check API key is configured",
439
+ "Verify model name is correct",
440
+ "Check network connectivity",
441
+ "Try with --no-llm to skip LLM processing"
442
+ ];
443
+ };
444
+ var GitHubError = class extends NotesError {
445
+ code = "GITHUB_ERROR";
446
+ suggestions = [
447
+ "Ensure GITHUB_TOKEN is set",
448
+ "Check token has repo scope",
449
+ "Verify repository exists and is accessible"
450
+ ];
451
+ };
452
+ var ConfigError2 = class extends NotesError {
453
+ code = "CONFIG_ERROR";
454
+ suggestions = [
455
+ "Check config file syntax",
456
+ "Verify all required fields are present",
457
+ "Run releasekit-notes init to create default config"
458
+ ];
459
+ };
460
+ function getExitCode(error) {
461
+ switch (error.code) {
462
+ case "CONFIG_ERROR":
463
+ return EXIT_CODES.CONFIG_ERROR;
464
+ case "INPUT_PARSE_ERROR":
465
+ return EXIT_CODES.INPUT_ERROR;
466
+ case "TEMPLATE_ERROR":
467
+ return EXIT_CODES.TEMPLATE_ERROR;
468
+ case "LLM_ERROR":
469
+ return EXIT_CODES.LLM_ERROR;
470
+ case "GITHUB_ERROR":
471
+ return EXIT_CODES.GITHUB_ERROR;
472
+ default:
473
+ return EXIT_CODES.GENERAL_ERROR;
474
+ }
475
+ }
476
+
477
+ // src/input/version-output.ts
478
+ import * as fs4 from "fs";
479
+ function normalizeEntryType(type) {
480
+ const typeMap = {
481
+ added: "added",
482
+ feat: "added",
483
+ feature: "added",
484
+ changed: "changed",
485
+ update: "changed",
486
+ refactor: "changed",
487
+ deprecated: "deprecated",
488
+ removed: "removed",
489
+ fixed: "fixed",
490
+ fix: "fixed",
491
+ security: "security",
492
+ sec: "security"
493
+ };
494
+ return typeMap[type.toLowerCase()] ?? "changed";
495
+ }
496
+ function parseVersionOutput(json) {
497
+ let data;
498
+ try {
499
+ data = JSON.parse(json);
500
+ } catch (error) {
501
+ throw new InputParseError(`Invalid JSON input: ${error instanceof Error ? error.message : String(error)}`);
502
+ }
503
+ if (!data.changelogs || !Array.isArray(data.changelogs)) {
504
+ throw new InputParseError('Input must contain a "changelogs" array');
505
+ }
506
+ const packages = data.changelogs.map((changelog) => ({
507
+ packageName: changelog.packageName,
508
+ version: changelog.version,
509
+ previousVersion: changelog.previousVersion,
510
+ revisionRange: changelog.revisionRange,
511
+ repoUrl: changelog.repoUrl,
512
+ date: (/* @__PURE__ */ new Date()).toISOString().split("T")[0] ?? "",
513
+ entries: changelog.entries.map((entry) => ({
514
+ type: normalizeEntryType(entry.type),
515
+ description: entry.description,
516
+ issueIds: entry.issueIds,
517
+ scope: entry.scope,
518
+ originalType: entry.originalType,
519
+ breaking: entry.breaking ?? entry.originalType?.includes("!") ?? false
520
+ }))
521
+ }));
522
+ const repoUrl = packages[0]?.repoUrl ?? null;
523
+ return {
524
+ source: "version",
525
+ packages,
526
+ metadata: {
527
+ repoUrl: repoUrl ?? void 0
528
+ }
529
+ };
530
+ }
531
+ function parseVersionOutputFile(filePath) {
532
+ const content = fs4.readFileSync(filePath, "utf-8");
533
+ return parseVersionOutput(content);
534
+ }
535
+ async function parseVersionOutputStdin() {
536
+ const chunks = [];
537
+ for await (const chunk of process.stdin) {
538
+ chunks.push(chunk);
539
+ }
540
+ const content = chunks.join("");
541
+ return parseVersionOutput(content);
542
+ }
543
+
544
+ // src/core/config.ts
545
+ function loadConfig2(projectDir = process.cwd(), configFile) {
546
+ const options = { cwd: projectDir, configPath: configFile };
547
+ const fullConfig = loadConfig(options);
548
+ const config = fullConfig.notes ?? getDefaultConfig();
549
+ if (fullConfig.monorepo && !config.monorepo) {
550
+ config.monorepo = fullConfig.monorepo;
551
+ }
552
+ return config;
553
+ }
554
+ function getDefaultConfig() {
555
+ return {};
556
+ }
557
+
558
+ // src/core/pipeline.ts
559
+ import * as fs9 from "fs";
560
+ import * as path7 from "path";
561
+
562
+ // src/llm/defaults.ts
563
+ var LLM_DEFAULTS = {
564
+ timeout: 6e4,
565
+ maxTokens: 16384,
566
+ temperature: 0.7,
567
+ concurrency: 5,
568
+ retry: {
569
+ maxAttempts: 3,
570
+ initialDelay: 1e3,
571
+ maxDelay: 3e4,
572
+ backoffFactor: 2
573
+ },
574
+ models: {
575
+ openai: "gpt-4o-mini",
576
+ "openai-compatible": "gpt-4o-mini",
577
+ anthropic: "claude-haiku-4-5-20251001",
578
+ ollama: "llama3.2"
579
+ }
580
+ };
581
+
582
+ // src/llm/anthropic.ts
583
+ import Anthropic from "@anthropic-ai/sdk";
584
+
585
+ // src/llm/base.ts
586
+ var BaseLLMProvider = class {
587
+ getTimeout(options) {
588
+ return options?.timeout ?? LLM_DEFAULTS.timeout;
589
+ }
590
+ getMaxTokens(options) {
591
+ return options?.maxTokens ?? LLM_DEFAULTS.maxTokens;
592
+ }
593
+ getTemperature(options) {
594
+ return options?.temperature ?? LLM_DEFAULTS.temperature;
595
+ }
596
+ };
597
+
598
+ // src/llm/anthropic.ts
599
+ var AnthropicProvider = class extends BaseLLMProvider {
600
+ name = "anthropic";
601
+ client;
602
+ model;
603
+ constructor(config = {}) {
604
+ super();
605
+ const apiKey = config.apiKey ?? process.env.ANTHROPIC_API_KEY;
606
+ if (!apiKey) {
607
+ throw new LLMError("Anthropic API key not configured. Set ANTHROPIC_API_KEY or use --llm-api-key");
608
+ }
609
+ this.client = new Anthropic({ apiKey });
610
+ this.model = config.model ?? LLM_DEFAULTS.models.anthropic;
611
+ }
612
+ async complete(prompt, options) {
613
+ try {
614
+ const response = await this.client.messages.create({
615
+ model: this.model,
616
+ max_tokens: this.getMaxTokens(options),
617
+ messages: [{ role: "user", content: prompt }]
618
+ });
619
+ const firstBlock = response.content[0];
620
+ if (!firstBlock || firstBlock.type !== "text") {
621
+ throw new LLMError("Unexpected response format from Anthropic");
622
+ }
623
+ return firstBlock.text;
624
+ } catch (error) {
625
+ if (error instanceof LLMError) throw error;
626
+ throw new LLMError(`Anthropic API error: ${error instanceof Error ? error.message : String(error)}`);
627
+ }
628
+ }
629
+ };
630
+
631
+ // src/llm/ollama.ts
632
+ var OllamaProvider = class extends BaseLLMProvider {
633
+ name = "ollama";
634
+ baseURL;
635
+ model;
636
+ apiKey;
637
+ constructor(config = {}) {
638
+ super();
639
+ this.baseURL = config.baseURL ?? process.env.OLLAMA_BASE_URL ?? "http://localhost:11434";
640
+ this.model = config.model ?? LLM_DEFAULTS.models.ollama;
641
+ this.apiKey = config.apiKey ?? process.env.OLLAMA_API_KEY;
642
+ }
643
+ async complete(prompt, options) {
644
+ const requestBody = {
645
+ model: this.model,
646
+ messages: [{ role: "user", content: prompt }],
647
+ stream: false,
648
+ options: {
649
+ num_predict: this.getMaxTokens(options),
650
+ temperature: this.getTemperature(options)
651
+ }
652
+ };
653
+ try {
654
+ const headers = {
655
+ "Content-Type": "application/json"
656
+ };
657
+ if (this.apiKey) {
658
+ headers.Authorization = `Bearer ${this.apiKey}`;
659
+ }
660
+ const baseUrl = this.baseURL.endsWith("/api") ? this.baseURL.slice(0, -4) : this.baseURL;
661
+ const response = await fetch(`${baseUrl}/api/chat`, {
662
+ method: "POST",
663
+ headers,
664
+ body: JSON.stringify(requestBody)
665
+ });
666
+ if (!response.ok) {
667
+ if (response.status === 401 || response.status === 403) {
668
+ const text2 = await response.text();
669
+ const keyHint = this.apiKey ? "OLLAMA_API_KEY is set but may be invalid or rejected by the server." : "OLLAMA_API_KEY is not set. Set the environment variable or use --no-llm to skip LLM processing.";
670
+ throw new LLMError(
671
+ `Ollama request failed: ${response.status} ${response.statusText}${text2 ? ` - ${text2}` : ""}. ${keyHint}`
672
+ );
673
+ }
674
+ const text = await response.text();
675
+ throw new LLMError(`Ollama request failed: ${response.status} ${text}`);
676
+ }
677
+ const data = await response.json();
678
+ if (!data.message?.content) {
679
+ throw new LLMError("Empty response from Ollama");
680
+ }
681
+ return data.message.content;
682
+ } catch (error) {
683
+ if (error instanceof LLMError) throw error;
684
+ throw new LLMError(`Ollama error: ${error instanceof Error ? error.message : String(error)}`);
685
+ }
686
+ }
687
+ };
688
+
689
+ // src/llm/openai.ts
690
+ import OpenAI from "openai";
691
+ var OpenAIProvider = class extends BaseLLMProvider {
692
+ name = "openai";
693
+ client;
694
+ model;
695
+ constructor(config = {}) {
696
+ super();
697
+ const apiKey = config.apiKey ?? process.env.OPENAI_API_KEY;
698
+ if (!apiKey) {
699
+ throw new LLMError("OpenAI API key not configured. Set OPENAI_API_KEY or use --llm-api-key");
700
+ }
701
+ this.client = new OpenAI({
702
+ apiKey,
703
+ baseURL: config.baseURL
704
+ });
705
+ this.model = config.model ?? LLM_DEFAULTS.models.openai;
706
+ }
707
+ async complete(prompt, options) {
708
+ try {
709
+ const response = await this.client.chat.completions.create({
710
+ model: this.model,
711
+ messages: [{ role: "user", content: prompt }],
712
+ max_tokens: this.getMaxTokens(options),
713
+ temperature: this.getTemperature(options)
714
+ });
715
+ const content = response.choices[0]?.message?.content;
716
+ if (!content) {
717
+ throw new LLMError("Empty response from OpenAI");
718
+ }
719
+ return content;
720
+ } catch (error) {
721
+ if (error instanceof LLMError) throw error;
722
+ throw new LLMError(`OpenAI API error: ${error instanceof Error ? error.message : String(error)}`);
723
+ }
724
+ }
725
+ };
726
+
727
+ // src/llm/openai-compatible.ts
728
+ import OpenAI2 from "openai";
729
+ var OpenAICompatibleProvider = class extends BaseLLMProvider {
730
+ name = "openai-compatible";
731
+ client;
732
+ model;
733
+ constructor(config) {
734
+ super();
735
+ const apiKey = config.apiKey ?? process.env.OPENAI_API_KEY ?? "dummy";
736
+ this.client = new OpenAI2({
737
+ apiKey,
738
+ baseURL: config.baseURL
739
+ });
740
+ this.model = config.model ?? LLM_DEFAULTS.models["openai-compatible"];
741
+ }
742
+ async complete(prompt, options) {
743
+ try {
744
+ const response = await this.client.chat.completions.create({
745
+ model: this.model,
746
+ messages: [{ role: "user", content: prompt }],
747
+ max_tokens: this.getMaxTokens(options),
748
+ temperature: this.getTemperature(options)
749
+ });
750
+ const content = response.choices[0]?.message?.content;
751
+ if (!content) {
752
+ throw new LLMError("Empty response from LLM");
753
+ }
754
+ return content;
755
+ } catch (error) {
756
+ if (error instanceof LLMError) throw error;
757
+ throw new LLMError(`LLM API error: ${error instanceof Error ? error.message : String(error)}`);
758
+ }
759
+ }
760
+ };
761
+
762
+ // src/utils/json.ts
763
+ function extractJsonFromResponse(response) {
764
+ const stripped = response.replace(/^```(?:json)?\n?/, "").replace(/\n?```$/, "").trim();
765
+ const objectMatch = stripped.match(/\{[\s\S]*\}/);
766
+ if (objectMatch) return objectMatch[0];
767
+ const arrayMatch = stripped.match(/\[[\s\S]*\]/);
768
+ if (arrayMatch) return arrayMatch[0];
769
+ return stripped;
770
+ }
771
+
772
+ // src/llm/prompts.ts
773
+ function resolvePrompt(taskName, defaultPrompt, promptsConfig) {
774
+ if (!promptsConfig) return defaultPrompt;
775
+ const fullTemplate = promptsConfig.templates?.[taskName];
776
+ if (fullTemplate) return fullTemplate;
777
+ const additionalInstructions = promptsConfig.instructions?.[taskName];
778
+ if (additionalInstructions) {
779
+ const insertionPoint = defaultPrompt.lastIndexOf("Output only valid JSON");
780
+ if (insertionPoint !== -1) {
781
+ return `${defaultPrompt.slice(0, insertionPoint)}Additional instructions:
782
+ ${additionalInstructions}
783
+
784
+ ${defaultPrompt.slice(insertionPoint)}`;
785
+ }
786
+ return `${defaultPrompt}
787
+
788
+ Additional instructions:
789
+ ${additionalInstructions}`;
790
+ }
791
+ return defaultPrompt;
792
+ }
793
+
794
+ // src/llm/scopes.ts
795
+ function getAllowedScopesFromCategories(categories) {
796
+ const scopeMap = /* @__PURE__ */ new Map();
797
+ for (const cat of categories) {
798
+ if (cat.scopes && cat.scopes.length > 0) {
799
+ scopeMap.set(cat.name, cat.scopes);
800
+ }
801
+ }
802
+ return scopeMap;
803
+ }
804
+ function resolveAllowedScopes(scopeConfig, categories, packageNames) {
805
+ if (!scopeConfig || scopeConfig.mode === "unrestricted") return null;
806
+ if (scopeConfig.mode === "none") return [];
807
+ if (scopeConfig.mode === "packages") return packageNames ?? [];
808
+ if (scopeConfig.mode === "restricted") {
809
+ const explicit = scopeConfig.rules?.allowed ?? [];
810
+ const all = new Set(explicit);
811
+ if (categories) {
812
+ const fromCategories = getAllowedScopesFromCategories(categories);
813
+ for (const scopes of fromCategories.values()) {
814
+ for (const s of scopes) all.add(s);
815
+ }
816
+ }
817
+ return [...all];
818
+ }
819
+ return null;
820
+ }
821
+ function validateScope(scope, allowedScopes, rules) {
822
+ if (!scope || allowedScopes === null) return scope;
823
+ if (allowedScopes.length === 0) return void 0;
824
+ const caseSensitive = rules?.caseSensitive ?? false;
825
+ const normalise = (s) => caseSensitive ? s : s.toLowerCase();
826
+ const isAllowed = allowedScopes.some((a) => normalise(a) === normalise(scope));
827
+ if (isAllowed) return scope;
828
+ switch (rules?.invalidScopeAction ?? "remove") {
829
+ case "keep":
830
+ return scope;
831
+ case "fallback":
832
+ return rules?.fallbackScope;
833
+ default:
834
+ return void 0;
835
+ }
836
+ }
837
+ function validateEntryScopes(entries, scopeConfig, categories) {
838
+ const allowedScopes = resolveAllowedScopes(scopeConfig, categories);
839
+ if (allowedScopes === null) return entries;
840
+ return entries.map((entry) => ({
841
+ ...entry,
842
+ scope: validateScope(entry.scope, allowedScopes, scopeConfig?.rules)
843
+ }));
844
+ }
845
+
846
+ // src/llm/tasks/categorize.ts
847
+ var DEFAULT_CATEGORIZE_PROMPT = `You are categorizing changelog entries for a software release.
848
+
849
+ Given the following entries, group them into meaningful categories (e.g., "Core", "UI", "API", "Performance", "Bug Fixes", "Documentation").
850
+
851
+ Output a JSON object where keys are category names and values are arrays of entry indices (0-based).
852
+
853
+ Entries:
854
+ {{entries}}
855
+
856
+ Output only valid JSON, nothing else:`;
857
+ function buildCustomCategorizePrompt(categories) {
858
+ const categoryList = categories.map((c) => {
859
+ const scopeInfo = c.scopes?.length ? ` Allowed scopes: ${c.scopes.join(", ")}.` : "";
860
+ return `- "${c.name}": ${c.description}${scopeInfo}`;
861
+ }).join("\n");
862
+ const scopeMap = getAllowedScopesFromCategories(categories);
863
+ let scopeInstructions = "";
864
+ if (scopeMap.size > 0) {
865
+ const entries = [];
866
+ for (const [catName, scopes] of scopeMap) {
867
+ entries.push(`For "${catName}", assign a scope from: ${scopes.join(", ")}.`);
868
+ }
869
+ scopeInstructions = `
870
+
871
+ ${entries.join("\n")}
872
+ Only use scopes from these predefined lists. If an entry does not fit any scope, set scope to null.`;
873
+ }
874
+ return `You are categorizing changelog entries for a software release.
875
+
876
+ Given the following entries, group them into the specified categories. Only use the categories listed below in this exact order:
877
+
878
+ Categories:
879
+ ${categoryList}${scopeInstructions}
880
+
881
+ Output a JSON object with two fields:
882
+ - "categories": an object where keys are category names and values are arrays of entry indices (0-based)
883
+ - "scopes": an object where keys are entry indices (as strings) and values are scope labels. Only include entries that have a valid scope from the predefined list.
884
+
885
+ Entries:
886
+ {{entries}}
887
+
888
+ Output only valid JSON, nothing else:`;
889
+ }
890
+ async function categorizeEntries(provider, entries, context) {
891
+ if (entries.length === 0) {
892
+ return [];
893
+ }
894
+ const entriesCopy = entries.map((e) => ({ ...e, scope: void 0 }));
895
+ const entriesText = entriesCopy.map((e, i) => `${i}. [${e.type}]: ${e.description}`).join("\n");
896
+ const hasCustomCategories = context.categories && context.categories.length > 0;
897
+ const defaultPrompt = hasCustomCategories ? buildCustomCategorizePrompt(context.categories) : DEFAULT_CATEGORIZE_PROMPT;
898
+ const promptTemplate = resolvePrompt("categorize", defaultPrompt, context.prompts);
899
+ const prompt = promptTemplate.replace("{{entries}}", entriesText);
900
+ try {
901
+ const response = await provider.complete(prompt);
902
+ const parsed = JSON.parse(extractJsonFromResponse(response));
903
+ const result = [];
904
+ if (hasCustomCategories && parsed.categories) {
905
+ const categoryMap = parsed.categories;
906
+ const scopeMap = parsed.scopes || {};
907
+ for (const [indexStr, scope] of Object.entries(scopeMap)) {
908
+ const idx = Number.parseInt(indexStr, 10);
909
+ if (entriesCopy[idx] && scope && scope.trim()) {
910
+ entriesCopy[idx] = { ...entriesCopy[idx], scope: scope.trim() };
911
+ }
912
+ }
913
+ const validatedEntries = validateEntryScopes(entriesCopy, context.scopes, context.categories);
914
+ for (const [category, rawIndices] of Object.entries(categoryMap)) {
915
+ const indices = Array.isArray(rawIndices) ? rawIndices : [];
916
+ const categoryEntries = indices.map((i) => validatedEntries[i]).filter((e) => e !== void 0);
917
+ if (categoryEntries.length > 0) {
918
+ result.push({ category, entries: categoryEntries });
919
+ }
920
+ }
921
+ } else {
922
+ const categoryMap = parsed;
923
+ for (const [category, rawIndices] of Object.entries(categoryMap)) {
924
+ const indices = Array.isArray(rawIndices) ? rawIndices : [];
925
+ const categoryEntries = indices.map((i) => entriesCopy[i]).filter((e) => e !== void 0);
926
+ if (categoryEntries.length > 0) {
927
+ result.push({ category, entries: categoryEntries });
928
+ }
929
+ }
930
+ }
931
+ return result;
932
+ } catch (error) {
933
+ warn(
934
+ `LLM categorization failed, falling back to General: ${error instanceof Error ? error.message : String(error)}`
935
+ );
936
+ return [{ category: "General", entries: entriesCopy }];
937
+ }
938
+ }
939
+
940
+ // src/llm/tasks/enhance.ts
941
+ var DEFAULT_ENHANCE_PROMPT = `You are improving changelog entries for a software project.
942
+ Given a technical commit message, rewrite it as a clear, user-friendly changelog entry.
943
+
944
+ Rules:
945
+ - Be concise (1-2 sentences max)
946
+ - Focus on user impact, not implementation details
947
+ - Don't use technical jargon unless necessary
948
+ - Preserve the scope if mentioned (e.g., "core:", "api:")
949
+ {{style}}
950
+
951
+ Original entry:
952
+ Type: {{type}}
953
+ {{#if scope}}Scope: {{scope}}{{/if}}
954
+ Description: {{description}}
955
+
956
+ Rewritten description (only output the new description, nothing else):`;
957
+ async function enhanceEntry(provider, entry, context) {
958
+ const styleText = context.style ? `- ${context.style}` : '- Use present tense ("Add feature" not "Added feature")';
959
+ const defaultPrompt = DEFAULT_ENHANCE_PROMPT.replace("{{style}}", styleText).replace("{{type}}", entry.type).replace("{{#if scope}}Scope: {{scope}}{{/if}}", entry.scope ? `Scope: ${entry.scope}` : "").replace("{{description}}", entry.description);
960
+ const prompt = resolvePrompt("enhance", defaultPrompt, context.prompts);
961
+ const response = await provider.complete(prompt);
962
+ return response.trim();
963
+ }
964
+ async function enhanceEntries(provider, entries, context, concurrency = LLM_DEFAULTS.concurrency) {
965
+ const results = [];
966
+ for (let i = 0; i < entries.length; i += concurrency) {
967
+ const batch = entries.slice(i, i + concurrency);
968
+ const batchResults = await Promise.all(
969
+ batch.map(async (entry) => {
970
+ try {
971
+ const newDescription = await enhanceEntry(provider, entry, context);
972
+ return { ...entry, description: newDescription };
973
+ } catch {
974
+ return entry;
975
+ }
976
+ })
977
+ );
978
+ results.push(...batchResults);
979
+ }
980
+ return results;
981
+ }
982
+
983
+ // src/utils/retry.ts
984
+ function sleep(ms) {
985
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
986
+ }
987
+ async function withRetry(fn, options = {}) {
988
+ const maxAttempts = options.maxAttempts ?? 3;
989
+ const initialDelay = options.initialDelay ?? 1e3;
990
+ const maxDelay = options.maxDelay ?? 3e4;
991
+ const backoffFactor = options.backoffFactor ?? 2;
992
+ let lastError;
993
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
994
+ try {
995
+ return await fn();
996
+ } catch (error) {
997
+ lastError = error;
998
+ if (attempt < maxAttempts - 1) {
999
+ const base = Math.min(initialDelay * backoffFactor ** attempt, maxDelay);
1000
+ const jitter = base * 0.2 * (Math.random() * 2 - 1);
1001
+ await sleep(Math.max(0, base + jitter));
1002
+ }
1003
+ }
1004
+ }
1005
+ throw lastError;
1006
+ }
1007
+
1008
+ // src/llm/tasks/enhance-and-categorize.ts
1009
+ function buildPrompt(entries, categories, style) {
1010
+ const entriesText = entries.map((e, i) => `${i}. [${e.type}]${e.scope ? ` (${e.scope})` : ""}: ${e.description}`).join("\n");
1011
+ const styleText = style || 'Use present tense ("Add feature" not "Added feature"). Be concise.';
1012
+ const categorySection = categories ? `Categories (use ONLY these):
1013
+ ${categories.map((c) => {
1014
+ const scopeInfo = c.scopes?.length ? ` Allowed scopes: ${c.scopes.join(", ")}.` : "";
1015
+ return `- "${c.name}": ${c.description}${scopeInfo}`;
1016
+ }).join("\n")}` : `Categories: Group into meaningful categories (e.g., "New", "Fixed", "Changed", "Removed").`;
1017
+ let scopeInstruction = "";
1018
+ if (categories) {
1019
+ const scopeMap = getAllowedScopesFromCategories(categories);
1020
+ if (scopeMap.size > 0) {
1021
+ const parts = [];
1022
+ for (const [catName, scopes] of scopeMap) {
1023
+ parts.push(`For "${catName}" entries, assign a scope from: ${scopes.join(", ")}.`);
1024
+ }
1025
+ scopeInstruction = `
1026
+ ${parts.join("\n")}
1027
+ Only use scopes from these predefined lists. Set scope to null if no scope applies.`;
1028
+ }
1029
+ }
1030
+ return `You are generating release notes for a software project. Given the following changelog entries, do two things:
1031
+
1032
+ 1. **Rewrite** each entry as a clear, user-friendly description
1033
+ 2. **Categorize** each entry into the appropriate category
1034
+
1035
+ Style guidelines:
1036
+ - ${styleText}
1037
+ - Be concise (1 short sentence per entry)
1038
+ - Focus on what changed, not implementation details
1039
+
1040
+ ${categorySection}${scopeInstruction}
1041
+
1042
+ Entries:
1043
+ ${entriesText}
1044
+
1045
+ Output a JSON object with:
1046
+ - "entries": array of objects, one per input entry (same order), each with: { "description": "rewritten text", "category": "CategoryName", "scope": "optional subcategory label or null" }
1047
+
1048
+ Output only valid JSON, nothing else:`;
1049
+ }
1050
+ async function enhanceAndCategorize(provider, entries, context) {
1051
+ if (entries.length === 0) {
1052
+ return { enhancedEntries: [], categories: [] };
1053
+ }
1054
+ const retryOpts = LLM_DEFAULTS.retry;
1055
+ try {
1056
+ return await withRetry(async () => {
1057
+ const defaultPrompt = buildPrompt(entries, context.categories, context.style);
1058
+ const prompt = resolvePrompt("enhanceAndCategorize", defaultPrompt, context.prompts);
1059
+ const response = await provider.complete(prompt);
1060
+ const parsed = JSON.parse(extractJsonFromResponse(response));
1061
+ if (!Array.isArray(parsed.entries)) {
1062
+ throw new Error('Response missing "entries" array');
1063
+ }
1064
+ const enhancedEntries = entries.map((original, i) => {
1065
+ const result = parsed.entries[i];
1066
+ if (!result) return original;
1067
+ return {
1068
+ ...original,
1069
+ description: result.description || original.description,
1070
+ scope: result.scope || original.scope
1071
+ };
1072
+ });
1073
+ const validatedEntries = validateEntryScopes(enhancedEntries, context.scopes, context.categories);
1074
+ const categoryMap = /* @__PURE__ */ new Map();
1075
+ for (let i = 0; i < parsed.entries.length; i++) {
1076
+ const result = parsed.entries[i];
1077
+ const category = result?.category || "General";
1078
+ const entry = validatedEntries[i];
1079
+ if (!entry) continue;
1080
+ if (!categoryMap.has(category)) {
1081
+ categoryMap.set(category, []);
1082
+ }
1083
+ categoryMap.get(category)?.push(entry);
1084
+ }
1085
+ const categories = [];
1086
+ for (const [category, catEntries] of categoryMap) {
1087
+ categories.push({ category, entries: catEntries });
1088
+ }
1089
+ return { enhancedEntries: validatedEntries, categories };
1090
+ }, retryOpts);
1091
+ } catch (error) {
1092
+ warn(
1093
+ `Combined enhance+categorize failed after ${retryOpts.maxAttempts} attempts: ${error instanceof Error ? error.message : String(error)}`
1094
+ );
1095
+ return {
1096
+ enhancedEntries: entries,
1097
+ categories: [{ category: "General", entries }]
1098
+ };
1099
+ }
1100
+ }
1101
+
1102
+ // src/llm/tasks/release-notes.ts
1103
+ var DEFAULT_RELEASE_NOTES_PROMPT = `You are writing release notes for a software project.
1104
+
1105
+ Create engaging, user-friendly release notes for the following changes.
1106
+
1107
+ Rules:
1108
+ - Start with a brief introduction (1-2 sentences)
1109
+ - Group related changes into sections
1110
+ - Use friendly, approachable language
1111
+ - Highlight breaking changes prominently
1112
+ - End with a brief conclusion or call to action
1113
+ - Use markdown formatting
1114
+
1115
+ Version: {{version}}
1116
+ {{#if previousVersion}}Previous version: {{previousVersion}}{{/if}}
1117
+ Date: {{date}}
1118
+
1119
+ Changes:
1120
+ {{entries}}
1121
+
1122
+ Release notes (output only the markdown content):`;
1123
+ async function generateReleaseNotes(provider, entries, context) {
1124
+ if (entries.length === 0) {
1125
+ return `## Release ${context.version ?? "v1.0.0"}
1126
+
1127
+ No notable changes in this release.`;
1128
+ }
1129
+ const entriesText = entries.map((e) => {
1130
+ let line = `- [${e.type}]`;
1131
+ if (e.scope) line += ` (${e.scope})`;
1132
+ line += `: ${e.description}`;
1133
+ if (e.breaking) line += " **BREAKING**";
1134
+ return line;
1135
+ }).join("\n");
1136
+ const defaultPrompt = DEFAULT_RELEASE_NOTES_PROMPT.replace("{{version}}", context.version ?? "v1.0.0").replace(
1137
+ "{{#if previousVersion}}Previous version: {{previousVersion}}{{/if}}",
1138
+ context.previousVersion ? `Previous version: ${context.previousVersion}` : ""
1139
+ ).replace("{{date}}", context.date ?? (/* @__PURE__ */ new Date()).toISOString().split("T")[0] ?? "").replace("{{entries}}", entriesText);
1140
+ const prompt = resolvePrompt("releaseNotes", defaultPrompt, context.prompts);
1141
+ const response = await provider.complete(prompt);
1142
+ return response.trim();
1143
+ }
1144
+
1145
+ // src/llm/tasks/summarize.ts
1146
+ var DEFAULT_SUMMARIZE_PROMPT = `You are creating a summary of changes for a software release.
1147
+
1148
+ Given the following changelog entries, create a brief summary (2-3 sentences) that captures the main themes of this release.
1149
+
1150
+ Entries:
1151
+ {{entries}}
1152
+
1153
+ Summary (only output the summary, nothing else):`;
1154
+ async function summarizeEntries(provider, entries, context) {
1155
+ if (entries.length === 0) {
1156
+ return "";
1157
+ }
1158
+ const entriesText = entries.map((e) => `- [${e.type}]${e.scope ? ` (${e.scope})` : ""}: ${e.description}`).join("\n");
1159
+ const defaultPrompt = DEFAULT_SUMMARIZE_PROMPT.replace("{{entries}}", entriesText);
1160
+ const prompt = resolvePrompt("summarize", defaultPrompt, context.prompts);
1161
+ const response = await provider.complete(prompt);
1162
+ return response.trim();
1163
+ }
1164
+
1165
+ // src/llm/index.ts
1166
+ function createProvider(config) {
1167
+ const authKeys = loadAuth();
1168
+ const apiKey = config.apiKey ?? authKeys[config.provider];
1169
+ switch (config.provider) {
1170
+ case "openai":
1171
+ return new OpenAIProvider({
1172
+ apiKey,
1173
+ baseURL: config.baseURL,
1174
+ model: config.model
1175
+ });
1176
+ case "anthropic":
1177
+ return new AnthropicProvider({
1178
+ apiKey,
1179
+ model: config.model
1180
+ });
1181
+ case "ollama":
1182
+ return new OllamaProvider({
1183
+ apiKey,
1184
+ baseURL: config.baseURL,
1185
+ model: config.model
1186
+ });
1187
+ case "openai-compatible": {
1188
+ if (!config.baseURL) {
1189
+ throw new LLMError("openai-compatible provider requires baseURL");
1190
+ }
1191
+ return new OpenAICompatibleProvider({
1192
+ apiKey,
1193
+ baseURL: config.baseURL,
1194
+ model: config.model
1195
+ });
1196
+ }
1197
+ default:
1198
+ throw new LLMError(`Unknown LLM provider: ${config.provider}`);
1199
+ }
1200
+ }
1201
+
1202
+ // src/templates/ejs.ts
1203
+ import * as fs5 from "fs";
1204
+ import ejs from "ejs";
1205
+ function renderEjs(template, context) {
1206
+ try {
1207
+ return ejs.render(template, context);
1208
+ } catch (error) {
1209
+ throw new TemplateError(`EJS render error: ${error instanceof Error ? error.message : String(error)}`);
1210
+ }
1211
+ }
1212
+ function renderEjsFile(filePath, context) {
1213
+ if (!fs5.existsSync(filePath)) {
1214
+ throw new TemplateError(`Template file not found: ${filePath}`);
1215
+ }
1216
+ const template = fs5.readFileSync(filePath, "utf-8");
1217
+ return renderEjs(template, context);
1218
+ }
1219
+
1220
+ // src/templates/handlebars.ts
1221
+ import * as fs6 from "fs";
1222
+ import * as path4 from "path";
1223
+ import Handlebars from "handlebars";
1224
+ function registerHandlebarsHelpers() {
1225
+ Handlebars.registerHelper("capitalize", (str) => {
1226
+ return str.charAt(0).toUpperCase() + str.slice(1);
1227
+ });
1228
+ Handlebars.registerHelper("eq", (a, b) => {
1229
+ return a === b;
1230
+ });
1231
+ Handlebars.registerHelper("ne", (a, b) => {
1232
+ return a !== b;
1233
+ });
1234
+ Handlebars.registerHelper("join", (arr, separator) => {
1235
+ return Array.isArray(arr) ? arr.join(separator) : "";
1236
+ });
1237
+ }
1238
+ function renderHandlebars(template, context) {
1239
+ registerHandlebarsHelpers();
1240
+ try {
1241
+ const compiled = Handlebars.compile(template);
1242
+ return compiled(context);
1243
+ } catch (error) {
1244
+ throw new TemplateError(`Handlebars render error: ${error instanceof Error ? error.message : String(error)}`);
1245
+ }
1246
+ }
1247
+ function renderHandlebarsFile(filePath, context) {
1248
+ if (!fs6.existsSync(filePath)) {
1249
+ throw new TemplateError(`Template file not found: ${filePath}`);
1250
+ }
1251
+ const template = fs6.readFileSync(filePath, "utf-8");
1252
+ return renderHandlebars(template, context);
1253
+ }
1254
+ function renderHandlebarsComposable(templateDir, context) {
1255
+ registerHandlebarsHelpers();
1256
+ const versionPath = path4.join(templateDir, "version.hbs");
1257
+ const entryPath = path4.join(templateDir, "entry.hbs");
1258
+ const documentPath = path4.join(templateDir, "document.hbs");
1259
+ if (!fs6.existsSync(documentPath)) {
1260
+ throw new TemplateError(`Document template not found: ${documentPath}`);
1261
+ }
1262
+ if (fs6.existsSync(versionPath)) {
1263
+ Handlebars.registerPartial("version", fs6.readFileSync(versionPath, "utf-8"));
1264
+ }
1265
+ if (fs6.existsSync(entryPath)) {
1266
+ Handlebars.registerPartial("entry", fs6.readFileSync(entryPath, "utf-8"));
1267
+ }
1268
+ try {
1269
+ const compiled = Handlebars.compile(fs6.readFileSync(documentPath, "utf-8"));
1270
+ return compiled(context);
1271
+ } catch (error) {
1272
+ throw new TemplateError(`Handlebars render error: ${error instanceof Error ? error.message : String(error)}`);
1273
+ }
1274
+ }
1275
+
1276
+ // src/templates/liquid.ts
1277
+ import * as fs7 from "fs";
1278
+ import * as path5 from "path";
1279
+ import { Liquid } from "liquidjs";
1280
+ function createLiquidEngine(root) {
1281
+ return new Liquid({
1282
+ root: root ? [root] : [],
1283
+ extname: ".liquid",
1284
+ cache: false
1285
+ });
1286
+ }
1287
+ function renderLiquid(template, context) {
1288
+ const engine = createLiquidEngine();
1289
+ try {
1290
+ return engine.renderSync(engine.parse(template), context);
1291
+ } catch (error) {
1292
+ throw new TemplateError(`Liquid render error: ${error instanceof Error ? error.message : String(error)}`);
1293
+ }
1294
+ }
1295
+ function renderLiquidFile(filePath, context) {
1296
+ if (!fs7.existsSync(filePath)) {
1297
+ throw new TemplateError(`Template file not found: ${filePath}`);
1298
+ }
1299
+ const template = fs7.readFileSync(filePath, "utf-8");
1300
+ return renderLiquid(template, context);
1301
+ }
1302
+ function renderLiquidComposable(templateDir, context) {
1303
+ const documentPath = path5.join(templateDir, "document.liquid");
1304
+ if (!fs7.existsSync(documentPath)) {
1305
+ throw new TemplateError(`Document template not found: ${documentPath}`);
1306
+ }
1307
+ const engine = createLiquidEngine(templateDir);
1308
+ try {
1309
+ return engine.renderFileSync("document", context);
1310
+ } catch (error) {
1311
+ throw new TemplateError(`Liquid render error: ${error instanceof Error ? error.message : String(error)}`);
1312
+ }
1313
+ }
1314
+
1315
+ // src/templates/loader.ts
1316
+ import * as fs8 from "fs";
1317
+ import * as path6 from "path";
1318
+ function getEngineFromFile(filePath) {
1319
+ const ext = path6.extname(filePath).toLowerCase();
1320
+ switch (ext) {
1321
+ case ".liquid":
1322
+ return "liquid";
1323
+ case ".hbs":
1324
+ case ".handlebars":
1325
+ return "handlebars";
1326
+ case ".ejs":
1327
+ return "ejs";
1328
+ default:
1329
+ throw new TemplateError(`Unknown template extension: ${ext}`);
1330
+ }
1331
+ }
1332
+ function getRenderFn(engine) {
1333
+ switch (engine) {
1334
+ case "liquid":
1335
+ return renderLiquid;
1336
+ case "handlebars":
1337
+ return renderHandlebars;
1338
+ case "ejs":
1339
+ return renderEjs;
1340
+ }
1341
+ }
1342
+ function getRenderFileFn(engine) {
1343
+ switch (engine) {
1344
+ case "liquid":
1345
+ return renderLiquidFile;
1346
+ case "handlebars":
1347
+ return renderHandlebarsFile;
1348
+ case "ejs":
1349
+ return renderEjsFile;
1350
+ }
1351
+ }
1352
+ function detectTemplateMode(templatePath) {
1353
+ if (!fs8.existsSync(templatePath)) {
1354
+ throw new TemplateError(`Template path not found: ${templatePath}`);
1355
+ }
1356
+ const stat = fs8.statSync(templatePath);
1357
+ if (stat.isFile()) {
1358
+ return "single";
1359
+ }
1360
+ if (stat.isDirectory()) {
1361
+ return "composable";
1362
+ }
1363
+ throw new TemplateError(`Invalid template path: ${templatePath}`);
1364
+ }
1365
+ function renderSingleFile(templatePath, context, engine) {
1366
+ const resolvedEngine = engine ?? getEngineFromFile(templatePath);
1367
+ const renderFile = getRenderFileFn(resolvedEngine);
1368
+ return {
1369
+ content: renderFile(templatePath, context),
1370
+ engine: resolvedEngine
1371
+ };
1372
+ }
1373
+ function renderComposable(templateDir, context, engine) {
1374
+ const files = fs8.readdirSync(templateDir);
1375
+ const engineMap = {
1376
+ liquid: { document: "document.liquid", version: "version.liquid", entry: "entry.liquid" },
1377
+ handlebars: { document: "document.hbs", version: "version.hbs", entry: "entry.hbs" },
1378
+ ejs: { document: "document.ejs", version: "version.ejs", entry: "entry.ejs" }
1379
+ };
1380
+ let resolvedEngine;
1381
+ if (engine) {
1382
+ resolvedEngine = engine;
1383
+ } else {
1384
+ const detected = detectEngineFromFiles(templateDir, files);
1385
+ if (!detected) {
1386
+ throw new TemplateError(`Could not detect template engine. Found files: ${files.join(", ")}`);
1387
+ }
1388
+ resolvedEngine = detected;
1389
+ }
1390
+ if (resolvedEngine === "liquid") {
1391
+ return { content: renderLiquidComposable(templateDir, context), engine: resolvedEngine };
1392
+ }
1393
+ if (resolvedEngine === "handlebars") {
1394
+ return { content: renderHandlebarsComposable(templateDir, context), engine: resolvedEngine };
1395
+ }
1396
+ const expectedFiles = engineMap[resolvedEngine];
1397
+ const documentPath = path6.join(templateDir, expectedFiles.document);
1398
+ if (!fs8.existsSync(documentPath)) {
1399
+ throw new TemplateError(`Document template not found: ${expectedFiles.document}`);
1400
+ }
1401
+ const versionPath = path6.join(templateDir, expectedFiles.version);
1402
+ const entryPath = path6.join(templateDir, expectedFiles.entry);
1403
+ const render = getRenderFn(resolvedEngine);
1404
+ const entryTemplate = fs8.existsSync(entryPath) ? fs8.readFileSync(entryPath, "utf-8") : null;
1405
+ const versionTemplate = fs8.existsSync(versionPath) ? fs8.readFileSync(versionPath, "utf-8") : null;
1406
+ if (entryTemplate && versionTemplate) {
1407
+ const versionsWithEntries = context.versions.map((versionCtx) => {
1408
+ const entries = versionCtx.entries.map((entry) => {
1409
+ const entryCtx = { ...entry, packageName: versionCtx.packageName, version: versionCtx.version };
1410
+ return render(entryTemplate, entryCtx);
1411
+ });
1412
+ return render(versionTemplate, { ...versionCtx, renderedEntries: entries });
1413
+ });
1414
+ const docContext = { ...context, renderedVersions: versionsWithEntries };
1415
+ return {
1416
+ content: render(fs8.readFileSync(documentPath, "utf-8"), docContext),
1417
+ engine: resolvedEngine
1418
+ };
1419
+ }
1420
+ return renderSingleFile(documentPath, context, resolvedEngine);
1421
+ }
1422
+ function detectEngineFromFiles(_dir, files) {
1423
+ if (files.some((f) => f.endsWith(".liquid"))) return "liquid";
1424
+ if (files.some((f) => f.endsWith(".hbs") || f.endsWith(".handlebars"))) return "handlebars";
1425
+ if (files.some((f) => f.endsWith(".ejs"))) return "ejs";
1426
+ return null;
1427
+ }
1428
+ function validateDocumentContext(context, templatePath) {
1429
+ if (!context.project?.name) {
1430
+ throw new TemplateError(`${templatePath}: DocumentContext missing required field "project.name"`);
1431
+ }
1432
+ if (!Array.isArray(context.versions)) {
1433
+ throw new TemplateError(`${templatePath}: DocumentContext missing required field "versions" (must be an array)`);
1434
+ }
1435
+ const requiredVersionFields = ["packageName", "version", "date", "entries"];
1436
+ for (const [i, v] of context.versions.entries()) {
1437
+ for (const field of requiredVersionFields) {
1438
+ if (v[field] === void 0 || v[field] === null) {
1439
+ throw new TemplateError(`${templatePath}: versions[${i}] missing required field "${field}"`);
1440
+ }
1441
+ }
1442
+ if (!Array.isArray(v.entries)) {
1443
+ throw new TemplateError(`${templatePath}: versions[${i}].entries must be an array`);
1444
+ }
1445
+ }
1446
+ }
1447
+ function renderTemplate(templatePath, context, engine) {
1448
+ validateDocumentContext(context, templatePath);
1449
+ const mode = detectTemplateMode(templatePath);
1450
+ if (mode === "single") {
1451
+ return renderSingleFile(templatePath, context, engine);
1452
+ }
1453
+ return renderComposable(templatePath, context, engine);
1454
+ }
1455
+
1456
+ // src/core/pipeline.ts
1457
+ function generateCompareUrl(repoUrl, from, to, packageName) {
1458
+ const isPackageSpecific = from.includes("@") && packageName && from.includes(packageName);
1459
+ let fromVersion;
1460
+ let toVersion;
1461
+ if (isPackageSpecific) {
1462
+ fromVersion = from;
1463
+ toVersion = `${packageName}@${to.startsWith("v") ? "" : "v"}${to}`;
1464
+ } else {
1465
+ fromVersion = from.replace(/^v/, "");
1466
+ toVersion = to.replace(/^v/, "");
1467
+ }
1468
+ if (/gitlab\.com/i.test(repoUrl)) {
1469
+ return `${repoUrl}/-/compare/${fromVersion}...${toVersion}`;
1470
+ }
1471
+ if (/bitbucket\.org/i.test(repoUrl)) {
1472
+ return `${repoUrl}/branches/compare/${fromVersion}..${toVersion}`;
1473
+ }
1474
+ return `${repoUrl}/compare/${fromVersion}...${toVersion}`;
1475
+ }
1476
+ function buildOrderedCategories(rawCategories, configCategories) {
1477
+ const order = configCategories?.map((c) => c.name) ?? [];
1478
+ const mapped = rawCategories.map((c) => ({ name: c.category, entries: c.entries }));
1479
+ if (order.length === 0) return mapped;
1480
+ return mapped.sort((a, b) => {
1481
+ const ai = order.indexOf(a.name);
1482
+ const bi = order.indexOf(b.name);
1483
+ return (ai === -1 ? order.length : ai) - (bi === -1 ? order.length : bi);
1484
+ });
1485
+ }
1486
+ function createTemplateContext(pkg) {
1487
+ const compareUrl = pkg.repoUrl && pkg.previousVersion ? generateCompareUrl(pkg.repoUrl, pkg.previousVersion, pkg.version, pkg.packageName) : void 0;
1488
+ return {
1489
+ packageName: pkg.packageName,
1490
+ version: pkg.version,
1491
+ previousVersion: pkg.previousVersion,
1492
+ date: pkg.date,
1493
+ repoUrl: pkg.repoUrl,
1494
+ entries: pkg.entries,
1495
+ compareUrl
1496
+ };
1497
+ }
1498
+ function createDocumentContext(contexts, repoUrl) {
1499
+ const compareUrls = {};
1500
+ for (const ctx of contexts) {
1501
+ if (ctx.compareUrl) {
1502
+ compareUrls[ctx.version] = ctx.compareUrl;
1503
+ }
1504
+ }
1505
+ return {
1506
+ project: {
1507
+ name: contexts[0]?.packageName ?? "project",
1508
+ repoUrl
1509
+ },
1510
+ versions: contexts,
1511
+ compareUrls: Object.keys(compareUrls).length > 0 ? compareUrls : void 0
1512
+ };
1513
+ }
1514
+ async function processWithLLM(context, llmConfig) {
1515
+ const tasks = llmConfig.tasks ?? {};
1516
+ const llmContext = {
1517
+ packageName: context.packageName,
1518
+ version: context.version,
1519
+ previousVersion: context.previousVersion ?? void 0,
1520
+ date: context.date,
1521
+ categories: llmConfig.categories,
1522
+ style: llmConfig.style,
1523
+ scopes: llmConfig.scopes,
1524
+ prompts: llmConfig.prompts
1525
+ };
1526
+ const enhanced = {
1527
+ entries: context.entries
1528
+ };
1529
+ try {
1530
+ info(`Using LLM provider: ${llmConfig.provider}${llmConfig.model ? ` (${llmConfig.model})` : ""}`);
1531
+ if (llmConfig.baseURL) {
1532
+ info(`LLM base URL: ${llmConfig.baseURL}`);
1533
+ }
1534
+ const rawProvider = createProvider(llmConfig);
1535
+ const retryOpts = llmConfig.retry ?? LLM_DEFAULTS.retry;
1536
+ const configOptions = llmConfig.options;
1537
+ const provider = {
1538
+ name: rawProvider.name,
1539
+ complete: (prompt, opts) => withRetry(() => rawProvider.complete(prompt, { ...configOptions, ...opts }), retryOpts)
1540
+ };
1541
+ const activeTasks = Object.entries(tasks).filter(([, enabled]) => enabled).map(([name]) => name);
1542
+ info(`Running LLM tasks: ${activeTasks.join(", ")}`);
1543
+ if (tasks.enhance && tasks.categorize) {
1544
+ info("Enhancing and categorizing entries with LLM...");
1545
+ const result = await enhanceAndCategorize(provider, context.entries, llmContext);
1546
+ enhanced.entries = result.enhancedEntries;
1547
+ enhanced.categories = buildOrderedCategories(result.categories, llmContext.categories);
1548
+ info(`Enhanced ${enhanced.entries.length} entries into ${result.categories.length} categories`);
1549
+ } else {
1550
+ if (tasks.enhance) {
1551
+ info("Enhancing entries with LLM...");
1552
+ enhanced.entries = await enhanceEntries(provider, context.entries, llmContext, llmConfig.concurrency);
1553
+ info(`Enhanced ${enhanced.entries.length} entries`);
1554
+ }
1555
+ if (tasks.categorize) {
1556
+ info("Categorizing entries with LLM...");
1557
+ const categorized = await categorizeEntries(provider, enhanced.entries, llmContext);
1558
+ enhanced.categories = buildOrderedCategories(categorized, llmContext.categories);
1559
+ info(`Created ${categorized.length} categories`);
1560
+ }
1561
+ }
1562
+ if (tasks.summarize) {
1563
+ info("Summarizing entries with LLM...");
1564
+ enhanced.summary = await summarizeEntries(provider, enhanced.entries, llmContext);
1565
+ if (enhanced.summary) {
1566
+ info("Summary generated successfully");
1567
+ debug(`Summary: ${enhanced.summary.substring(0, 100)}...`);
1568
+ } else {
1569
+ warn("Summary generation returned empty result");
1570
+ }
1571
+ }
1572
+ if (tasks.releaseNotes) {
1573
+ info("Generating release notes with LLM...");
1574
+ enhanced.releaseNotes = await generateReleaseNotes(provider, enhanced.entries, llmContext);
1575
+ if (enhanced.releaseNotes) {
1576
+ info("Release notes generated successfully");
1577
+ } else {
1578
+ warn("Release notes generation returned empty result");
1579
+ }
1580
+ }
1581
+ return {
1582
+ ...context,
1583
+ enhanced
1584
+ };
1585
+ } catch (error) {
1586
+ warn(`LLM processing failed: ${error instanceof Error ? error.message : String(error)}`);
1587
+ warn("Falling back to raw entries");
1588
+ return context;
1589
+ }
1590
+ }
1591
+ function getBuiltinTemplatePath(style) {
1592
+ let packageRoot;
1593
+ try {
1594
+ const currentUrl = import.meta.url;
1595
+ packageRoot = path7.dirname(new URL(currentUrl).pathname);
1596
+ packageRoot = path7.join(packageRoot, "..", "..");
1597
+ } catch {
1598
+ packageRoot = __dirname;
1599
+ }
1600
+ return path7.join(packageRoot, "templates", style);
1601
+ }
1602
+ async function generateWithTemplate(contexts, templatesConfig, outputPath, repoUrl, dryRun) {
1603
+ let templatePath;
1604
+ if (templatesConfig?.path) {
1605
+ templatePath = path7.resolve(templatesConfig.path);
1606
+ } else {
1607
+ templatePath = getBuiltinTemplatePath("keep-a-changelog");
1608
+ }
1609
+ const documentContext = createDocumentContext(contexts, templatesConfig?.path ? void 0 : repoUrl);
1610
+ const result = renderTemplate(templatePath, documentContext, templatesConfig?.engine);
1611
+ if (dryRun) {
1612
+ info(`[DRY RUN] Changelog preview (would write to ${outputPath}):`);
1613
+ info(result.content);
1614
+ return;
1615
+ }
1616
+ if (outputPath === "-") {
1617
+ process.stdout.write(result.content);
1618
+ return;
1619
+ }
1620
+ const dir = path7.dirname(outputPath);
1621
+ if (!fs9.existsSync(dir)) {
1622
+ fs9.mkdirSync(dir, { recursive: true });
1623
+ }
1624
+ fs9.writeFileSync(outputPath, result.content, "utf-8");
1625
+ const label = /changelog/i.test(outputPath) ? "Changelog" : "Release notes";
1626
+ success(`${label} written to ${outputPath} (using ${result.engine} template)`);
1627
+ }
1628
+ async function runPipeline(input, config, dryRun) {
1629
+ debug(`Processing ${input.packages.length} package(s)`);
1630
+ let contexts = input.packages.map(createTemplateContext);
1631
+ const changelogConfig = config.changelog === false ? false : { mode: "root", ...config.changelog ?? {} };
1632
+ const releaseNotesConfig = config.releaseNotes === false || config.releaseNotes === void 0 ? void 0 : config.releaseNotes.mode !== void 0 || config.releaseNotes.file !== void 0 ? { mode: "root", ...config.releaseNotes } : config.releaseNotes;
1633
+ const llmConfig = releaseNotesConfig?.llm;
1634
+ if (llmConfig && !process.env.CHANGELOG_NO_LLM) {
1635
+ info("Processing with LLM enhancement");
1636
+ contexts = await Promise.all(contexts.map((ctx) => processWithLLM(ctx, llmConfig)));
1637
+ }
1638
+ const files = [];
1639
+ const fmtOpts = {
1640
+ includePackageName: contexts.length > 1 || contexts.some((c) => c.packageName.includes("/"))
1641
+ };
1642
+ if (changelogConfig !== false && changelogConfig.mode) {
1643
+ const fileName = changelogConfig.file ?? "CHANGELOG.md";
1644
+ const mode = changelogConfig.mode;
1645
+ info(`Generating changelog \u2192 ${fileName}`);
1646
+ try {
1647
+ if (mode === "root" || mode === "both") {
1648
+ if (changelogConfig.templates?.path) {
1649
+ await generateWithTemplate(
1650
+ contexts,
1651
+ changelogConfig.templates,
1652
+ fileName,
1653
+ contexts[0]?.repoUrl ?? void 0,
1654
+ dryRun
1655
+ );
1656
+ } else {
1657
+ writeMarkdown(fileName, contexts, config, dryRun, fmtOpts);
1658
+ }
1659
+ if (!dryRun) files.push(fileName);
1660
+ }
1661
+ if (mode === "packages" || mode === "both") {
1662
+ const monoFiles = await writeMonorepoFiles(contexts, config, dryRun, changelogConfig.file ?? "CHANGELOG.md");
1663
+ files.push(...monoFiles);
1664
+ }
1665
+ } catch (error) {
1666
+ warn(`Failed to write changelog: ${error instanceof Error ? error.message : String(error)}`);
1667
+ }
1668
+ }
1669
+ if (releaseNotesConfig?.mode) {
1670
+ const fileName = releaseNotesConfig.file ?? "RELEASE_NOTES.md";
1671
+ const mode = releaseNotesConfig.mode;
1672
+ info(`Generating release notes \u2192 ${fileName}`);
1673
+ try {
1674
+ if (mode === "root" || mode === "both") {
1675
+ if (releaseNotesConfig.templates?.path) {
1676
+ await generateWithTemplate(
1677
+ contexts,
1678
+ releaseNotesConfig.templates,
1679
+ fileName,
1680
+ contexts[0]?.repoUrl ?? void 0,
1681
+ dryRun
1682
+ );
1683
+ } else {
1684
+ writeMarkdown(fileName, contexts, config, dryRun, fmtOpts);
1685
+ }
1686
+ if (!dryRun) files.push(fileName);
1687
+ }
1688
+ if (mode === "packages" || mode === "both") {
1689
+ const monoFiles = await writeMonorepoFiles(
1690
+ contexts,
1691
+ config,
1692
+ dryRun,
1693
+ releaseNotesConfig.file ?? "RELEASE_NOTES.md"
1694
+ );
1695
+ files.push(...monoFiles);
1696
+ }
1697
+ } catch (error) {
1698
+ warn(`Failed to write release notes: ${error instanceof Error ? error.message : String(error)}`);
1699
+ }
1700
+ }
1701
+ const packageNotes = {};
1702
+ const releaseNotesResult = {};
1703
+ for (const ctx of contexts) {
1704
+ packageNotes[ctx.packageName] = formatVersion(ctx);
1705
+ if (ctx.enhanced?.releaseNotes) {
1706
+ releaseNotesResult[ctx.packageName] = ctx.enhanced.releaseNotes;
1707
+ }
1708
+ }
1709
+ return {
1710
+ packageNotes,
1711
+ files,
1712
+ releaseNotes: Object.keys(releaseNotesResult).length > 0 ? releaseNotesResult : void 0
1713
+ };
1714
+ }
1715
+ async function processInput(inputJson, config, dryRun) {
1716
+ const input = parseVersionOutput(inputJson);
1717
+ return runPipeline(input, config, dryRun);
1718
+ }
1719
+ async function writeMonorepoFiles(contexts, config, dryRun, fileName) {
1720
+ const { detectMonorepo, writeMonorepoChangelogs } = await import("./aggregator-IUQUAVJC.js");
1721
+ const cwd = process.cwd();
1722
+ const detected = detectMonorepo(cwd);
1723
+ if (!detected.isMonorepo) return [];
1724
+ const monoFiles = writeMonorepoChangelogs(
1725
+ contexts,
1726
+ {
1727
+ rootPath: config.monorepo?.rootPath ?? cwd,
1728
+ packagesPath: config.monorepo?.packagesPath ?? detected.packagesPath,
1729
+ mode: "packages",
1730
+ fileName
1731
+ },
1732
+ config,
1733
+ dryRun
1734
+ );
1735
+ return monoFiles;
1736
+ }
1737
+
1738
+ export {
1739
+ loadAuth,
1740
+ saveAuth,
1741
+ loadConfig,
1742
+ NotesError,
1743
+ InputParseError,
1744
+ TemplateError,
1745
+ LLMError,
1746
+ GitHubError,
1747
+ ConfigError2 as ConfigError,
1748
+ getExitCode,
1749
+ parseVersionOutput,
1750
+ parseVersionOutputFile,
1751
+ parseVersionOutputStdin,
1752
+ loadConfig2,
1753
+ getDefaultConfig,
1754
+ createTemplateContext,
1755
+ runPipeline,
1756
+ processInput
1757
+ };