@releasekit/notes 0.1.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,1473 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ ChangelogCreatorError: () => NotesError,
34
+ ConfigError: () => ConfigError,
35
+ EXIT_CODES: () => import_core2.EXIT_CODES,
36
+ GitHubError: () => GitHubError,
37
+ InputParseError: () => InputParseError,
38
+ LLMError: () => LLMError,
39
+ NotesError: () => NotesError,
40
+ TemplateError: () => TemplateError,
41
+ aggregateToRoot: () => aggregateToRoot,
42
+ createTemplateContext: () => createTemplateContext,
43
+ detectMonorepo: () => detectMonorepo,
44
+ getDefaultConfig: () => getDefaultConfig,
45
+ getExitCode: () => getExitCode,
46
+ loadAuth: () => import_config.loadAuth,
47
+ loadConfig: () => loadConfig,
48
+ parsePackageVersioner: () => parsePackageVersioner,
49
+ parsePackageVersionerFile: () => parsePackageVersionerFile,
50
+ parsePackageVersionerStdin: () => parsePackageVersionerStdin,
51
+ processInput: () => processInput,
52
+ renderJson: () => renderJson,
53
+ renderMarkdown: () => renderMarkdown,
54
+ runPipeline: () => runPipeline,
55
+ saveAuth: () => import_config.saveAuth,
56
+ writeJson: () => writeJson,
57
+ writeMarkdown: () => writeMarkdown,
58
+ writeMonorepoChangelogs: () => writeMonorepoChangelogs
59
+ });
60
+ module.exports = __toCommonJS(index_exports);
61
+
62
+ // src/core/config.ts
63
+ var import_config = require("@releasekit/config");
64
+ function loadConfig(projectDir = process.cwd(), configFile) {
65
+ const options = { cwd: projectDir, configPath: configFile };
66
+ return (0, import_config.loadNotesConfig)(options) ?? getDefaultConfig();
67
+ }
68
+ function getDefaultConfig() {
69
+ return {
70
+ output: [{ format: "markdown", file: "CHANGELOG.md" }],
71
+ updateStrategy: "prepend"
72
+ };
73
+ }
74
+
75
+ // src/core/pipeline.ts
76
+ var fs8 = __toESM(require("fs"), 1);
77
+ var path6 = __toESM(require("path"), 1);
78
+ var import_core7 = require("@releasekit/core");
79
+
80
+ // src/input/package-versioner.ts
81
+ var fs = __toESM(require("fs"), 1);
82
+
83
+ // src/errors/index.ts
84
+ var import_core = require("@releasekit/core");
85
+ var import_core2 = require("@releasekit/core");
86
+ var NotesError = class extends import_core.ReleaseKitError {
87
+ };
88
+ var InputParseError = class extends NotesError {
89
+ code = "INPUT_PARSE_ERROR";
90
+ suggestions = [
91
+ "Ensure input is valid JSON",
92
+ "Check that input matches expected schema",
93
+ "Use --input-source to specify format"
94
+ ];
95
+ };
96
+ var TemplateError = class extends NotesError {
97
+ code = "TEMPLATE_ERROR";
98
+ suggestions = [
99
+ "Check template syntax",
100
+ "Ensure all required files exist (document, version, entry)",
101
+ "Verify template engine matches file extension"
102
+ ];
103
+ };
104
+ var LLMError = class extends NotesError {
105
+ code = "LLM_ERROR";
106
+ suggestions = [
107
+ "Check API key is configured",
108
+ "Verify model name is correct",
109
+ "Check network connectivity",
110
+ "Try with --no-llm to skip LLM processing"
111
+ ];
112
+ };
113
+ var GitHubError = class extends NotesError {
114
+ code = "GITHUB_ERROR";
115
+ suggestions = [
116
+ "Ensure GITHUB_TOKEN is set",
117
+ "Check token has repo scope",
118
+ "Verify repository exists and is accessible"
119
+ ];
120
+ };
121
+ var ConfigError = class extends NotesError {
122
+ code = "CONFIG_ERROR";
123
+ suggestions = [
124
+ "Check config file syntax",
125
+ "Verify all required fields are present",
126
+ "Run releasekit-notes init to create default config"
127
+ ];
128
+ };
129
+ function getExitCode(error) {
130
+ switch (error.code) {
131
+ case "CONFIG_ERROR":
132
+ return import_core.EXIT_CODES.CONFIG_ERROR;
133
+ case "INPUT_PARSE_ERROR":
134
+ return import_core.EXIT_CODES.INPUT_ERROR;
135
+ case "TEMPLATE_ERROR":
136
+ return import_core.EXIT_CODES.TEMPLATE_ERROR;
137
+ case "LLM_ERROR":
138
+ return import_core.EXIT_CODES.LLM_ERROR;
139
+ case "GITHUB_ERROR":
140
+ return import_core.EXIT_CODES.GITHUB_ERROR;
141
+ default:
142
+ return import_core.EXIT_CODES.GENERAL_ERROR;
143
+ }
144
+ }
145
+
146
+ // src/input/package-versioner.ts
147
+ function normalizeEntryType(type) {
148
+ const typeMap = {
149
+ added: "added",
150
+ feat: "added",
151
+ feature: "added",
152
+ changed: "changed",
153
+ update: "changed",
154
+ refactor: "changed",
155
+ deprecated: "deprecated",
156
+ removed: "removed",
157
+ fixed: "fixed",
158
+ fix: "fixed",
159
+ security: "security",
160
+ sec: "security"
161
+ };
162
+ return typeMap[type.toLowerCase()] ?? "changed";
163
+ }
164
+ function parsePackageVersioner(json) {
165
+ let data;
166
+ try {
167
+ data = JSON.parse(json);
168
+ } catch (error) {
169
+ throw new InputParseError(`Invalid JSON input: ${error instanceof Error ? error.message : String(error)}`);
170
+ }
171
+ if (!data.changelogs || !Array.isArray(data.changelogs)) {
172
+ throw new InputParseError('Input must contain a "changelogs" array');
173
+ }
174
+ const packages = data.changelogs.map((changelog) => ({
175
+ packageName: changelog.packageName,
176
+ version: changelog.version,
177
+ previousVersion: changelog.previousVersion,
178
+ revisionRange: changelog.revisionRange,
179
+ repoUrl: changelog.repoUrl,
180
+ date: (/* @__PURE__ */ new Date()).toISOString().split("T")[0] ?? "",
181
+ entries: changelog.entries.map((entry) => ({
182
+ type: normalizeEntryType(entry.type),
183
+ description: entry.description,
184
+ issueIds: entry.issueIds,
185
+ scope: entry.scope,
186
+ originalType: entry.originalType,
187
+ breaking: entry.breaking ?? entry.originalType?.includes("!") ?? false
188
+ }))
189
+ }));
190
+ const repoUrl = packages[0]?.repoUrl ?? null;
191
+ return {
192
+ source: "package-versioner",
193
+ packages,
194
+ metadata: {
195
+ repoUrl: repoUrl ?? void 0
196
+ }
197
+ };
198
+ }
199
+ function parsePackageVersionerFile(filePath) {
200
+ const content = fs.readFileSync(filePath, "utf-8");
201
+ return parsePackageVersioner(content);
202
+ }
203
+ async function parsePackageVersionerStdin() {
204
+ const chunks = [];
205
+ for await (const chunk of process.stdin) {
206
+ chunks.push(chunk);
207
+ }
208
+ const content = chunks.join("");
209
+ return parsePackageVersioner(content);
210
+ }
211
+
212
+ // src/llm/defaults.ts
213
+ var LLM_DEFAULTS = {
214
+ timeout: 6e4,
215
+ maxTokens: 2e3,
216
+ temperature: 0.7,
217
+ concurrency: 5,
218
+ retry: {
219
+ maxAttempts: 3,
220
+ initialDelay: 1e3,
221
+ maxDelay: 3e4,
222
+ backoffFactor: 2
223
+ },
224
+ models: {
225
+ openai: "gpt-4o-mini",
226
+ "openai-compatible": "gpt-4o-mini",
227
+ anthropic: "claude-3-5-haiku-latest",
228
+ ollama: "llama3.2"
229
+ }
230
+ };
231
+
232
+ // src/llm/anthropic.ts
233
+ var import_sdk = __toESM(require("@anthropic-ai/sdk"), 1);
234
+
235
+ // src/llm/base.ts
236
+ var BaseLLMProvider = class {
237
+ getTimeout(options) {
238
+ return options?.timeout ?? LLM_DEFAULTS.timeout;
239
+ }
240
+ getMaxTokens(options) {
241
+ return options?.maxTokens ?? LLM_DEFAULTS.maxTokens;
242
+ }
243
+ getTemperature(options) {
244
+ return options?.temperature ?? LLM_DEFAULTS.temperature;
245
+ }
246
+ };
247
+
248
+ // src/llm/anthropic.ts
249
+ var AnthropicProvider = class extends BaseLLMProvider {
250
+ name = "anthropic";
251
+ client;
252
+ model;
253
+ constructor(config = {}) {
254
+ super();
255
+ const apiKey = config.apiKey ?? process.env.ANTHROPIC_API_KEY;
256
+ if (!apiKey) {
257
+ throw new LLMError("Anthropic API key not configured. Set ANTHROPIC_API_KEY or use --llm-api-key");
258
+ }
259
+ this.client = new import_sdk.default({ apiKey });
260
+ this.model = config.model ?? LLM_DEFAULTS.models.anthropic;
261
+ }
262
+ async complete(prompt, options) {
263
+ try {
264
+ const response = await this.client.messages.create({
265
+ model: this.model,
266
+ max_tokens: this.getMaxTokens(options),
267
+ messages: [{ role: "user", content: prompt }]
268
+ });
269
+ const firstBlock = response.content[0];
270
+ if (!firstBlock || firstBlock.type !== "text") {
271
+ throw new LLMError("Unexpected response format from Anthropic");
272
+ }
273
+ return firstBlock.text;
274
+ } catch (error) {
275
+ if (error instanceof LLMError) throw error;
276
+ throw new LLMError(`Anthropic API error: ${error instanceof Error ? error.message : String(error)}`);
277
+ }
278
+ }
279
+ };
280
+
281
+ // src/llm/ollama.ts
282
+ var OllamaProvider = class extends BaseLLMProvider {
283
+ name = "ollama";
284
+ baseURL;
285
+ model;
286
+ constructor(config = {}) {
287
+ super();
288
+ this.baseURL = config.baseURL ?? process.env.OLLAMA_BASE_URL ?? "http://localhost:11434";
289
+ this.model = config.model ?? LLM_DEFAULTS.models.ollama;
290
+ }
291
+ async complete(prompt, options) {
292
+ const requestBody = {
293
+ model: this.model,
294
+ prompt,
295
+ stream: false,
296
+ options: {
297
+ num_predict: this.getMaxTokens(options),
298
+ temperature: this.getTemperature(options)
299
+ }
300
+ };
301
+ try {
302
+ const response = await fetch(`${this.baseURL}/api/generate`, {
303
+ method: "POST",
304
+ headers: {
305
+ "Content-Type": "application/json"
306
+ },
307
+ body: JSON.stringify(requestBody)
308
+ });
309
+ if (!response.ok) {
310
+ const text = await response.text();
311
+ throw new LLMError(`Ollama request failed: ${response.status} ${text}`);
312
+ }
313
+ const data = await response.json();
314
+ if (!data.response) {
315
+ throw new LLMError("Empty response from Ollama");
316
+ }
317
+ return data.response;
318
+ } catch (error) {
319
+ if (error instanceof LLMError) throw error;
320
+ throw new LLMError(`Ollama error: ${error instanceof Error ? error.message : String(error)}`);
321
+ }
322
+ }
323
+ };
324
+
325
+ // src/llm/openai.ts
326
+ var import_openai = __toESM(require("openai"), 1);
327
+ var OpenAIProvider = class extends BaseLLMProvider {
328
+ name = "openai";
329
+ client;
330
+ model;
331
+ constructor(config = {}) {
332
+ super();
333
+ const apiKey = config.apiKey ?? process.env.OPENAI_API_KEY;
334
+ if (!apiKey) {
335
+ throw new LLMError("OpenAI API key not configured. Set OPENAI_API_KEY or use --llm-api-key");
336
+ }
337
+ this.client = new import_openai.default({
338
+ apiKey,
339
+ baseURL: config.baseURL
340
+ });
341
+ this.model = config.model ?? LLM_DEFAULTS.models.openai;
342
+ }
343
+ async complete(prompt, options) {
344
+ try {
345
+ const response = await this.client.chat.completions.create({
346
+ model: this.model,
347
+ messages: [{ role: "user", content: prompt }],
348
+ max_tokens: this.getMaxTokens(options),
349
+ temperature: this.getTemperature(options)
350
+ });
351
+ const content = response.choices[0]?.message?.content;
352
+ if (!content) {
353
+ throw new LLMError("Empty response from OpenAI");
354
+ }
355
+ return content;
356
+ } catch (error) {
357
+ if (error instanceof LLMError) throw error;
358
+ throw new LLMError(`OpenAI API error: ${error instanceof Error ? error.message : String(error)}`);
359
+ }
360
+ }
361
+ };
362
+
363
+ // src/llm/openai-compatible.ts
364
+ var import_openai2 = __toESM(require("openai"), 1);
365
+ var OpenAICompatibleProvider = class extends BaseLLMProvider {
366
+ name = "openai-compatible";
367
+ client;
368
+ model;
369
+ constructor(config) {
370
+ super();
371
+ const apiKey = config.apiKey ?? process.env.OPENAI_API_KEY ?? "dummy";
372
+ this.client = new import_openai2.default({
373
+ apiKey,
374
+ baseURL: config.baseURL
375
+ });
376
+ this.model = config.model ?? LLM_DEFAULTS.models["openai-compatible"];
377
+ }
378
+ async complete(prompt, options) {
379
+ try {
380
+ const response = await this.client.chat.completions.create({
381
+ model: this.model,
382
+ messages: [{ role: "user", content: prompt }],
383
+ max_tokens: this.getMaxTokens(options),
384
+ temperature: this.getTemperature(options)
385
+ });
386
+ const content = response.choices[0]?.message?.content;
387
+ if (!content) {
388
+ throw new LLMError("Empty response from LLM");
389
+ }
390
+ return content;
391
+ } catch (error) {
392
+ if (error instanceof LLMError) throw error;
393
+ throw new LLMError(`LLM API error: ${error instanceof Error ? error.message : String(error)}`);
394
+ }
395
+ }
396
+ };
397
+
398
+ // src/llm/tasks/categorize.ts
399
+ var import_core3 = require("@releasekit/core");
400
+ var CATEGORIZE_PROMPT = `You are categorizing changelog entries for a software release.
401
+
402
+ Given the following entries, group them into meaningful categories (e.g., "Core", "UI", "API", "Performance", "Bug Fixes", "Documentation").
403
+
404
+ Output a JSON object where keys are category names and values are arrays of entry indices (0-based).
405
+
406
+ Entries:
407
+ {{entries}}
408
+
409
+ Output only valid JSON, nothing else:`;
410
+ async function categorizeEntries(provider, entries, _context) {
411
+ if (entries.length === 0) {
412
+ return [];
413
+ }
414
+ const entriesText = entries.map((e, i) => `${i}. [${e.type}]${e.scope ? ` (${e.scope})` : ""}: ${e.description}`).join("\n");
415
+ const prompt = CATEGORIZE_PROMPT.replace("{{entries}}", entriesText);
416
+ try {
417
+ const response = await provider.complete(prompt);
418
+ const cleaned = response.replace(/^```(?:json)?\n?/, "").replace(/\n?```$/, "").trim();
419
+ const parsed = JSON.parse(cleaned);
420
+ const result = [];
421
+ for (const [category, indices] of Object.entries(parsed)) {
422
+ const categoryEntries = indices.map((i) => entries[i]).filter((e) => e !== void 0);
423
+ if (categoryEntries.length > 0) {
424
+ result.push({
425
+ category,
426
+ entries: categoryEntries
427
+ });
428
+ }
429
+ }
430
+ return result;
431
+ } catch (error) {
432
+ (0, import_core3.warn)(
433
+ `LLM categorization failed, falling back to General: ${error instanceof Error ? error.message : String(error)}`
434
+ );
435
+ return [{ category: "General", entries }];
436
+ }
437
+ }
438
+
439
+ // src/llm/tasks/enhance.ts
440
+ var ENHANCE_PROMPT = `You are improving changelog entries for a software project.
441
+ Given a technical commit message, rewrite it as a clear, user-friendly changelog entry.
442
+
443
+ Rules:
444
+ - Be concise (1-2 sentences max)
445
+ - Use present tense ("Add feature" not "Added feature")
446
+ - Focus on user impact, not implementation details
447
+ - Don't use technical jargon unless necessary
448
+ - Preserve the scope if mentioned (e.g., "core:", "api:")
449
+
450
+ Original entry:
451
+ Type: {{type}}
452
+ {{#if scope}}Scope: {{scope}}{{/if}}
453
+ Description: {{description}}
454
+
455
+ Rewritten description (only output the new description, nothing else):`;
456
+ async function enhanceEntry(provider, entry, _context) {
457
+ const prompt = ENHANCE_PROMPT.replace("{{type}}", entry.type).replace("{{#if scope}}Scope: {{scope}}{{/if}}", entry.scope ? `Scope: ${entry.scope}` : "").replace("{{description}}", entry.description);
458
+ const response = await provider.complete(prompt);
459
+ return response.trim();
460
+ }
461
+ async function enhanceEntries(provider, entries, context, concurrency = LLM_DEFAULTS.concurrency) {
462
+ const results = [];
463
+ for (let i = 0; i < entries.length; i += concurrency) {
464
+ const batch = entries.slice(i, i + concurrency);
465
+ const batchResults = await Promise.all(
466
+ batch.map(async (entry) => {
467
+ try {
468
+ const newDescription = await enhanceEntry(provider, entry, context);
469
+ return { ...entry, description: newDescription };
470
+ } catch {
471
+ return entry;
472
+ }
473
+ })
474
+ );
475
+ results.push(...batchResults);
476
+ }
477
+ return results;
478
+ }
479
+
480
+ // src/llm/tasks/release-notes.ts
481
+ var RELEASE_NOTES_PROMPT = `You are writing release notes for a software project.
482
+
483
+ Create engaging, user-friendly release notes for the following changes.
484
+
485
+ Rules:
486
+ - Start with a brief introduction (1-2 sentences)
487
+ - Group related changes into sections
488
+ - Use friendly, approachable language
489
+ - Highlight breaking changes prominently
490
+ - End with a brief conclusion or call to action
491
+ - Use markdown formatting
492
+
493
+ Version: {{version}}
494
+ {{#if previousVersion}}Previous version: {{previousVersion}}{{/if}}
495
+ Date: {{date}}
496
+
497
+ Changes:
498
+ {{entries}}
499
+
500
+ Release notes (output only the markdown content):`;
501
+ async function generateReleaseNotes(provider, entries, context) {
502
+ if (entries.length === 0) {
503
+ return `## Release ${context.version ?? "v1.0.0"}
504
+
505
+ No notable changes in this release.`;
506
+ }
507
+ const entriesText = entries.map((e) => {
508
+ let line = `- [${e.type}]`;
509
+ if (e.scope) line += ` (${e.scope})`;
510
+ line += `: ${e.description}`;
511
+ if (e.breaking) line += " **BREAKING**";
512
+ return line;
513
+ }).join("\n");
514
+ const prompt = RELEASE_NOTES_PROMPT.replace("{{version}}", context.version ?? "v1.0.0").replace(
515
+ "{{#if previousVersion}}Previous version: {{previousVersion}}{{/if}}",
516
+ context.previousVersion ? `Previous version: ${context.previousVersion}` : ""
517
+ ).replace("{{date}}", context.date ?? (/* @__PURE__ */ new Date()).toISOString().split("T")[0] ?? "").replace("{{entries}}", entriesText);
518
+ const response = await provider.complete(prompt);
519
+ return response.trim();
520
+ }
521
+
522
+ // src/llm/tasks/summarize.ts
523
+ var SUMMARIZE_PROMPT = `You are creating a summary of changes for a software release.
524
+
525
+ Given the following changelog entries, create a brief summary (2-3 sentences) that captures the main themes of this release.
526
+
527
+ Entries:
528
+ {{entries}}
529
+
530
+ Summary (only output the summary, nothing else):`;
531
+ async function summarizeEntries(provider, entries, _context) {
532
+ if (entries.length === 0) {
533
+ return "";
534
+ }
535
+ const entriesText = entries.map((e) => `- [${e.type}]${e.scope ? ` (${e.scope})` : ""}: ${e.description}`).join("\n");
536
+ const prompt = SUMMARIZE_PROMPT.replace("{{entries}}", entriesText);
537
+ const response = await provider.complete(prompt);
538
+ return response.trim();
539
+ }
540
+
541
+ // src/llm/index.ts
542
+ function createProvider(config) {
543
+ const authKeys = (0, import_config.loadAuth)();
544
+ const apiKey = config.apiKey ?? authKeys[config.provider];
545
+ switch (config.provider) {
546
+ case "openai":
547
+ return new OpenAIProvider({
548
+ apiKey,
549
+ baseURL: config.baseURL,
550
+ model: config.model
551
+ });
552
+ case "anthropic":
553
+ return new AnthropicProvider({
554
+ apiKey,
555
+ model: config.model
556
+ });
557
+ case "ollama":
558
+ return new OllamaProvider({
559
+ baseURL: config.baseURL,
560
+ model: config.model
561
+ });
562
+ case "openai-compatible": {
563
+ if (!config.baseURL) {
564
+ throw new LLMError("openai-compatible provider requires baseURL");
565
+ }
566
+ return new OpenAICompatibleProvider({
567
+ apiKey,
568
+ baseURL: config.baseURL,
569
+ model: config.model
570
+ });
571
+ }
572
+ default:
573
+ throw new LLMError(`Unknown LLM provider: ${config.provider}`);
574
+ }
575
+ }
576
+
577
+ // src/output/github-release.ts
578
+ var import_rest = require("@octokit/rest");
579
+ var import_core5 = require("@releasekit/core");
580
+
581
+ // src/output/markdown.ts
582
+ var fs2 = __toESM(require("fs"), 1);
583
+ var path = __toESM(require("path"), 1);
584
+ var import_core4 = require("@releasekit/core");
585
+ var TYPE_ORDER = ["added", "changed", "deprecated", "removed", "fixed", "security"];
586
+ var TYPE_LABELS = {
587
+ added: "Added",
588
+ changed: "Changed",
589
+ deprecated: "Deprecated",
590
+ removed: "Removed",
591
+ fixed: "Fixed",
592
+ security: "Security"
593
+ };
594
+ function groupEntriesByType(entries) {
595
+ const grouped = /* @__PURE__ */ new Map();
596
+ for (const type of TYPE_ORDER) {
597
+ grouped.set(type, []);
598
+ }
599
+ for (const entry of entries) {
600
+ const existing = grouped.get(entry.type) ?? [];
601
+ existing.push(entry);
602
+ grouped.set(entry.type, existing);
603
+ }
604
+ return grouped;
605
+ }
606
+ function formatEntry(entry) {
607
+ let line;
608
+ if (entry.breaking && entry.scope) {
609
+ line = `- **BREAKING** **${entry.scope}**: ${entry.description}`;
610
+ } else if (entry.breaking) {
611
+ line = `- **BREAKING** ${entry.description}`;
612
+ } else if (entry.scope) {
613
+ line = `- **${entry.scope}**: ${entry.description}`;
614
+ } else {
615
+ line = `- ${entry.description}`;
616
+ }
617
+ if (entry.issueIds && entry.issueIds.length > 0) {
618
+ line += ` (${entry.issueIds.join(", ")})`;
619
+ }
620
+ return line;
621
+ }
622
+ function formatVersion(context) {
623
+ const lines = [];
624
+ const versionHeader = context.previousVersion ? `## [${context.version}]` : `## ${context.version}`;
625
+ lines.push(`${versionHeader} - ${context.date}`);
626
+ lines.push("");
627
+ if (context.compareUrl) {
628
+ lines.push(`[Full Changelog](${context.compareUrl})`);
629
+ lines.push("");
630
+ }
631
+ const grouped = groupEntriesByType(context.entries);
632
+ for (const [type, entries] of grouped) {
633
+ if (entries.length === 0) continue;
634
+ lines.push(`### ${TYPE_LABELS[type]}`);
635
+ for (const entry of entries) {
636
+ lines.push(formatEntry(entry));
637
+ }
638
+ lines.push("");
639
+ }
640
+ return lines.join("\n");
641
+ }
642
+ function formatHeader() {
643
+ return `# Changelog
644
+
645
+ All notable changes to this project will be documented in this file.
646
+
647
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
648
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
649
+
650
+ `;
651
+ }
652
+ function renderMarkdown(contexts) {
653
+ const sections = [formatHeader()];
654
+ for (const context of contexts) {
655
+ sections.push(formatVersion(context));
656
+ }
657
+ return sections.join("\n");
658
+ }
659
+ function prependVersion(existingPath, context) {
660
+ let existing = "";
661
+ if (fs2.existsSync(existingPath)) {
662
+ existing = fs2.readFileSync(existingPath, "utf-8");
663
+ const headerEnd = existing.indexOf("\n## ");
664
+ if (headerEnd >= 0) {
665
+ const header = existing.slice(0, headerEnd);
666
+ const body = existing.slice(headerEnd + 1);
667
+ const newVersion = formatVersion(context);
668
+ return `${header}
669
+
670
+ ${newVersion}
671
+ ${body}`;
672
+ }
673
+ }
674
+ return renderMarkdown([context]);
675
+ }
676
+ function writeMarkdown(outputPath, contexts, config, dryRun) {
677
+ const content = renderMarkdown(contexts);
678
+ if (dryRun) {
679
+ (0, import_core4.info)("--- Changelog Preview ---");
680
+ console.log(content);
681
+ (0, import_core4.info)("--- End Preview ---");
682
+ return;
683
+ }
684
+ const dir = path.dirname(outputPath);
685
+ if (!fs2.existsSync(dir)) {
686
+ fs2.mkdirSync(dir, { recursive: true });
687
+ }
688
+ if (config.updateStrategy === "prepend" && fs2.existsSync(outputPath) && contexts.length === 1) {
689
+ const firstContext = contexts[0];
690
+ if (firstContext) {
691
+ const updated = prependVersion(outputPath, firstContext);
692
+ fs2.writeFileSync(outputPath, updated, "utf-8");
693
+ }
694
+ } else {
695
+ fs2.writeFileSync(outputPath, content, "utf-8");
696
+ }
697
+ (0, import_core4.success)(`Changelog written to ${outputPath}`);
698
+ }
699
+
700
+ // src/output/github-release.ts
701
+ var GitHubClient = class {
702
+ octokit;
703
+ owner;
704
+ repo;
705
+ constructor(options) {
706
+ const token = options.token ?? process.env.GITHUB_TOKEN;
707
+ if (!token) {
708
+ throw new GitHubError("GITHUB_TOKEN not set. Set it as an environment variable.");
709
+ }
710
+ this.octokit = new import_rest.Octokit({ auth: token });
711
+ this.owner = options.owner;
712
+ this.repo = options.repo;
713
+ }
714
+ async createRelease(context, options = {}) {
715
+ const tagName = `v${context.version}`;
716
+ let body;
717
+ if (context.enhanced?.releaseNotes) {
718
+ body = context.enhanced.releaseNotes;
719
+ } else {
720
+ body = renderMarkdown([context]);
721
+ }
722
+ (0, import_core5.info)(`Creating GitHub release for ${tagName}`);
723
+ try {
724
+ const response = await this.octokit.repos.createRelease({
725
+ owner: this.owner,
726
+ repo: this.repo,
727
+ tag_name: tagName,
728
+ name: tagName,
729
+ body,
730
+ draft: options.draft ?? false,
731
+ prerelease: options.prerelease ?? false,
732
+ generate_release_notes: options.generateNotes ?? false
733
+ });
734
+ (0, import_core5.success)(`Release created: ${response.data.html_url}`);
735
+ return {
736
+ id: response.data.id,
737
+ htmlUrl: response.data.html_url,
738
+ tagName
739
+ };
740
+ } catch (error) {
741
+ throw new GitHubError(`Failed to create release: ${error instanceof Error ? error.message : String(error)}`);
742
+ }
743
+ }
744
+ async updateRelease(releaseId, context, options = {}) {
745
+ const tagName = `v${context.version}`;
746
+ let body;
747
+ if (context.enhanced?.releaseNotes) {
748
+ body = context.enhanced.releaseNotes;
749
+ } else {
750
+ body = renderMarkdown([context]);
751
+ }
752
+ (0, import_core5.info)(`Updating GitHub release ${releaseId}`);
753
+ try {
754
+ const response = await this.octokit.repos.updateRelease({
755
+ owner: this.owner,
756
+ repo: this.repo,
757
+ release_id: releaseId,
758
+ tag_name: tagName,
759
+ name: tagName,
760
+ body,
761
+ draft: options.draft ?? false,
762
+ prerelease: options.prerelease ?? false
763
+ });
764
+ (0, import_core5.success)(`Release updated: ${response.data.html_url}`);
765
+ return {
766
+ id: response.data.id,
767
+ htmlUrl: response.data.html_url,
768
+ tagName
769
+ };
770
+ } catch (error) {
771
+ throw new GitHubError(`Failed to update release: ${error instanceof Error ? error.message : String(error)}`);
772
+ }
773
+ }
774
+ async getReleaseByTag(tag) {
775
+ try {
776
+ const response = await this.octokit.repos.getReleaseByTag({
777
+ owner: this.owner,
778
+ repo: this.repo,
779
+ tag
780
+ });
781
+ return {
782
+ id: response.data.id,
783
+ htmlUrl: response.data.html_url,
784
+ tagName: response.data.tag_name
785
+ };
786
+ } catch {
787
+ return null;
788
+ }
789
+ }
790
+ };
791
+ function parseRepoUrl(repoUrl) {
792
+ const patterns = [
793
+ /^https:\/\/github\.com\/([^/]+)\/([^/]+)/,
794
+ /^git@github\.com:([^/]+)\/([^/]+)/,
795
+ /^github\.com\/([^/]+)\/([^/]+)/
796
+ ];
797
+ for (const pattern of patterns) {
798
+ const match = repoUrl.match(pattern);
799
+ if (match?.[1] && match[2]) {
800
+ return {
801
+ owner: match[1],
802
+ repo: match[2].replace(/\.git$/, "")
803
+ };
804
+ }
805
+ }
806
+ return null;
807
+ }
808
+ async function createGitHubRelease(context, options) {
809
+ const client = new GitHubClient(options);
810
+ return client.createRelease(context, options);
811
+ }
812
+
813
+ // src/output/json.ts
814
+ var fs3 = __toESM(require("fs"), 1);
815
+ var path2 = __toESM(require("path"), 1);
816
+ var import_core6 = require("@releasekit/core");
817
+ function renderJson(contexts) {
818
+ return JSON.stringify(
819
+ {
820
+ versions: contexts.map((ctx) => ({
821
+ packageName: ctx.packageName,
822
+ version: ctx.version,
823
+ previousVersion: ctx.previousVersion,
824
+ date: ctx.date,
825
+ entries: ctx.entries,
826
+ compareUrl: ctx.compareUrl
827
+ }))
828
+ },
829
+ null,
830
+ 2
831
+ );
832
+ }
833
+ function writeJson(outputPath, contexts, dryRun) {
834
+ const content = renderJson(contexts);
835
+ if (dryRun) {
836
+ (0, import_core6.info)("--- JSON Output Preview ---");
837
+ console.log(content);
838
+ (0, import_core6.info)("--- End Preview ---");
839
+ return;
840
+ }
841
+ const dir = path2.dirname(outputPath);
842
+ if (!fs3.existsSync(dir)) {
843
+ fs3.mkdirSync(dir, { recursive: true });
844
+ }
845
+ fs3.writeFileSync(outputPath, content, "utf-8");
846
+ (0, import_core6.success)(`JSON output written to ${outputPath}`);
847
+ }
848
+
849
+ // src/templates/ejs.ts
850
+ var fs4 = __toESM(require("fs"), 1);
851
+ var import_ejs = __toESM(require("ejs"), 1);
852
+ function renderEjs(template, context) {
853
+ try {
854
+ return import_ejs.default.render(template, context);
855
+ } catch (error) {
856
+ throw new TemplateError(`EJS render error: ${error instanceof Error ? error.message : String(error)}`);
857
+ }
858
+ }
859
+ function renderEjsFile(filePath, context) {
860
+ if (!fs4.existsSync(filePath)) {
861
+ throw new TemplateError(`Template file not found: ${filePath}`);
862
+ }
863
+ const template = fs4.readFileSync(filePath, "utf-8");
864
+ return renderEjs(template, context);
865
+ }
866
+
867
+ // src/templates/handlebars.ts
868
+ var fs5 = __toESM(require("fs"), 1);
869
+ var path3 = __toESM(require("path"), 1);
870
+ var import_handlebars = __toESM(require("handlebars"), 1);
871
+ function registerHandlebarsHelpers() {
872
+ import_handlebars.default.registerHelper("capitalize", (str) => {
873
+ return str.charAt(0).toUpperCase() + str.slice(1);
874
+ });
875
+ import_handlebars.default.registerHelper("eq", (a, b) => {
876
+ return a === b;
877
+ });
878
+ import_handlebars.default.registerHelper("ne", (a, b) => {
879
+ return a !== b;
880
+ });
881
+ import_handlebars.default.registerHelper("join", (arr, separator) => {
882
+ return Array.isArray(arr) ? arr.join(separator) : "";
883
+ });
884
+ }
885
+ function renderHandlebars(template, context) {
886
+ registerHandlebarsHelpers();
887
+ try {
888
+ const compiled = import_handlebars.default.compile(template);
889
+ return compiled(context);
890
+ } catch (error) {
891
+ throw new TemplateError(`Handlebars render error: ${error instanceof Error ? error.message : String(error)}`);
892
+ }
893
+ }
894
+ function renderHandlebarsFile(filePath, context) {
895
+ if (!fs5.existsSync(filePath)) {
896
+ throw new TemplateError(`Template file not found: ${filePath}`);
897
+ }
898
+ const template = fs5.readFileSync(filePath, "utf-8");
899
+ return renderHandlebars(template, context);
900
+ }
901
+ function renderHandlebarsComposable(templateDir, context) {
902
+ registerHandlebarsHelpers();
903
+ const versionPath = path3.join(templateDir, "version.hbs");
904
+ const entryPath = path3.join(templateDir, "entry.hbs");
905
+ const documentPath = path3.join(templateDir, "document.hbs");
906
+ if (!fs5.existsSync(documentPath)) {
907
+ throw new TemplateError(`Document template not found: ${documentPath}`);
908
+ }
909
+ if (fs5.existsSync(versionPath)) {
910
+ import_handlebars.default.registerPartial("version", fs5.readFileSync(versionPath, "utf-8"));
911
+ }
912
+ if (fs5.existsSync(entryPath)) {
913
+ import_handlebars.default.registerPartial("entry", fs5.readFileSync(entryPath, "utf-8"));
914
+ }
915
+ try {
916
+ const compiled = import_handlebars.default.compile(fs5.readFileSync(documentPath, "utf-8"));
917
+ return compiled(context);
918
+ } catch (error) {
919
+ throw new TemplateError(`Handlebars render error: ${error instanceof Error ? error.message : String(error)}`);
920
+ }
921
+ }
922
+
923
+ // src/templates/liquid.ts
924
+ var fs6 = __toESM(require("fs"), 1);
925
+ var path4 = __toESM(require("path"), 1);
926
+ var import_liquidjs = require("liquidjs");
927
+ function createLiquidEngine(root) {
928
+ return new import_liquidjs.Liquid({
929
+ root: root ? [root] : [],
930
+ extname: ".liquid",
931
+ cache: false
932
+ });
933
+ }
934
+ function renderLiquid(template, context) {
935
+ const engine = createLiquidEngine();
936
+ try {
937
+ return engine.renderSync(engine.parse(template), context);
938
+ } catch (error) {
939
+ throw new TemplateError(`Liquid render error: ${error instanceof Error ? error.message : String(error)}`);
940
+ }
941
+ }
942
+ function renderLiquidFile(filePath, context) {
943
+ if (!fs6.existsSync(filePath)) {
944
+ throw new TemplateError(`Template file not found: ${filePath}`);
945
+ }
946
+ const template = fs6.readFileSync(filePath, "utf-8");
947
+ return renderLiquid(template, context);
948
+ }
949
+ function renderLiquidComposable(templateDir, context) {
950
+ const documentPath = path4.join(templateDir, "document.liquid");
951
+ if (!fs6.existsSync(documentPath)) {
952
+ throw new TemplateError(`Document template not found: ${documentPath}`);
953
+ }
954
+ const engine = createLiquidEngine(templateDir);
955
+ try {
956
+ return engine.renderFileSync("document", context);
957
+ } catch (error) {
958
+ throw new TemplateError(`Liquid render error: ${error instanceof Error ? error.message : String(error)}`);
959
+ }
960
+ }
961
+
962
+ // src/templates/loader.ts
963
+ var fs7 = __toESM(require("fs"), 1);
964
+ var path5 = __toESM(require("path"), 1);
965
+ function getEngineFromFile(filePath) {
966
+ const ext = path5.extname(filePath).toLowerCase();
967
+ switch (ext) {
968
+ case ".liquid":
969
+ return "liquid";
970
+ case ".hbs":
971
+ case ".handlebars":
972
+ return "handlebars";
973
+ case ".ejs":
974
+ return "ejs";
975
+ default:
976
+ throw new TemplateError(`Unknown template extension: ${ext}`);
977
+ }
978
+ }
979
+ function getRenderFn(engine) {
980
+ switch (engine) {
981
+ case "liquid":
982
+ return renderLiquid;
983
+ case "handlebars":
984
+ return renderHandlebars;
985
+ case "ejs":
986
+ return renderEjs;
987
+ }
988
+ }
989
+ function getRenderFileFn(engine) {
990
+ switch (engine) {
991
+ case "liquid":
992
+ return renderLiquidFile;
993
+ case "handlebars":
994
+ return renderHandlebarsFile;
995
+ case "ejs":
996
+ return renderEjsFile;
997
+ }
998
+ }
999
+ function detectTemplateMode(templatePath) {
1000
+ if (!fs7.existsSync(templatePath)) {
1001
+ throw new TemplateError(`Template path not found: ${templatePath}`);
1002
+ }
1003
+ const stat = fs7.statSync(templatePath);
1004
+ if (stat.isFile()) {
1005
+ return "single";
1006
+ }
1007
+ if (stat.isDirectory()) {
1008
+ return "composable";
1009
+ }
1010
+ throw new TemplateError(`Invalid template path: ${templatePath}`);
1011
+ }
1012
+ function renderSingleFile(templatePath, context, engine) {
1013
+ const resolvedEngine = engine ?? getEngineFromFile(templatePath);
1014
+ const renderFile = getRenderFileFn(resolvedEngine);
1015
+ return {
1016
+ content: renderFile(templatePath, context),
1017
+ engine: resolvedEngine
1018
+ };
1019
+ }
1020
+ function renderComposable(templateDir, context, engine) {
1021
+ const files = fs7.readdirSync(templateDir);
1022
+ const engineMap = {
1023
+ liquid: { document: "document.liquid", version: "version.liquid", entry: "entry.liquid" },
1024
+ handlebars: { document: "document.hbs", version: "version.hbs", entry: "entry.hbs" },
1025
+ ejs: { document: "document.ejs", version: "version.ejs", entry: "entry.ejs" }
1026
+ };
1027
+ let resolvedEngine;
1028
+ if (engine) {
1029
+ resolvedEngine = engine;
1030
+ } else {
1031
+ const detected = detectEngineFromFiles(templateDir, files);
1032
+ if (!detected) {
1033
+ throw new TemplateError(`Could not detect template engine. Found files: ${files.join(", ")}`);
1034
+ }
1035
+ resolvedEngine = detected;
1036
+ }
1037
+ if (resolvedEngine === "liquid") {
1038
+ return { content: renderLiquidComposable(templateDir, context), engine: resolvedEngine };
1039
+ }
1040
+ if (resolvedEngine === "handlebars") {
1041
+ return { content: renderHandlebarsComposable(templateDir, context), engine: resolvedEngine };
1042
+ }
1043
+ const expectedFiles = engineMap[resolvedEngine];
1044
+ const documentPath = path5.join(templateDir, expectedFiles.document);
1045
+ if (!fs7.existsSync(documentPath)) {
1046
+ throw new TemplateError(`Document template not found: ${expectedFiles.document}`);
1047
+ }
1048
+ const versionPath = path5.join(templateDir, expectedFiles.version);
1049
+ const entryPath = path5.join(templateDir, expectedFiles.entry);
1050
+ const render = getRenderFn(resolvedEngine);
1051
+ const entryTemplate = fs7.existsSync(entryPath) ? fs7.readFileSync(entryPath, "utf-8") : null;
1052
+ const versionTemplate = fs7.existsSync(versionPath) ? fs7.readFileSync(versionPath, "utf-8") : null;
1053
+ if (entryTemplate && versionTemplate) {
1054
+ const versionsWithEntries = context.versions.map((versionCtx) => {
1055
+ const entries = versionCtx.entries.map((entry) => {
1056
+ const entryCtx = { ...entry, packageName: versionCtx.packageName, version: versionCtx.version };
1057
+ return render(entryTemplate, entryCtx);
1058
+ });
1059
+ return render(versionTemplate, { ...versionCtx, renderedEntries: entries });
1060
+ });
1061
+ const docContext = { ...context, renderedVersions: versionsWithEntries };
1062
+ return {
1063
+ content: render(fs7.readFileSync(documentPath, "utf-8"), docContext),
1064
+ engine: resolvedEngine
1065
+ };
1066
+ }
1067
+ return renderSingleFile(documentPath, context, resolvedEngine);
1068
+ }
1069
+ function detectEngineFromFiles(_dir, files) {
1070
+ if (files.some((f) => f.endsWith(".liquid"))) return "liquid";
1071
+ if (files.some((f) => f.endsWith(".hbs") || f.endsWith(".handlebars"))) return "handlebars";
1072
+ if (files.some((f) => f.endsWith(".ejs"))) return "ejs";
1073
+ return null;
1074
+ }
1075
+ function validateDocumentContext(context, templatePath) {
1076
+ if (!context.project?.name) {
1077
+ throw new TemplateError(`${templatePath}: DocumentContext missing required field "project.name"`);
1078
+ }
1079
+ if (!Array.isArray(context.versions)) {
1080
+ throw new TemplateError(`${templatePath}: DocumentContext missing required field "versions" (must be an array)`);
1081
+ }
1082
+ const requiredVersionFields = ["packageName", "version", "date", "entries"];
1083
+ for (const [i, v] of context.versions.entries()) {
1084
+ for (const field of requiredVersionFields) {
1085
+ if (v[field] === void 0 || v[field] === null) {
1086
+ throw new TemplateError(`${templatePath}: versions[${i}] missing required field "${field}"`);
1087
+ }
1088
+ }
1089
+ if (!Array.isArray(v.entries)) {
1090
+ throw new TemplateError(`${templatePath}: versions[${i}].entries must be an array`);
1091
+ }
1092
+ }
1093
+ }
1094
+ function renderTemplate(templatePath, context, engine) {
1095
+ validateDocumentContext(context, templatePath);
1096
+ const mode = detectTemplateMode(templatePath);
1097
+ if (mode === "single") {
1098
+ return renderSingleFile(templatePath, context, engine);
1099
+ }
1100
+ return renderComposable(templatePath, context, engine);
1101
+ }
1102
+
1103
+ // src/utils/retry.ts
1104
+ function sleep(ms) {
1105
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1106
+ }
1107
+ async function withRetry(fn, options = {}) {
1108
+ const maxAttempts = options.maxAttempts ?? 3;
1109
+ const initialDelay = options.initialDelay ?? 1e3;
1110
+ const maxDelay = options.maxDelay ?? 3e4;
1111
+ const backoffFactor = options.backoffFactor ?? 2;
1112
+ let lastError;
1113
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
1114
+ try {
1115
+ return await fn();
1116
+ } catch (error) {
1117
+ lastError = error;
1118
+ if (attempt < maxAttempts - 1) {
1119
+ const base = Math.min(initialDelay * backoffFactor ** attempt, maxDelay);
1120
+ const jitter = base * 0.2 * (Math.random() * 2 - 1);
1121
+ await sleep(Math.max(0, base + jitter));
1122
+ }
1123
+ }
1124
+ }
1125
+ throw lastError;
1126
+ }
1127
+
1128
+ // src/core/pipeline.ts
1129
+ var import_meta = {};
1130
+ function generateCompareUrl(repoUrl, from, to) {
1131
+ if (/gitlab\.com/i.test(repoUrl)) {
1132
+ return `${repoUrl}/-/compare/${from}...${to}`;
1133
+ }
1134
+ if (/bitbucket\.org/i.test(repoUrl)) {
1135
+ return `${repoUrl}/branches/compare/${from}..${to}`;
1136
+ }
1137
+ return `${repoUrl}/compare/${from}...${to}`;
1138
+ }
1139
+ function createTemplateContext(pkg) {
1140
+ const compareUrl = pkg.repoUrl && pkg.previousVersion ? generateCompareUrl(pkg.repoUrl, pkg.previousVersion, pkg.version) : void 0;
1141
+ return {
1142
+ packageName: pkg.packageName,
1143
+ version: pkg.version,
1144
+ previousVersion: pkg.previousVersion,
1145
+ date: pkg.date,
1146
+ repoUrl: pkg.repoUrl,
1147
+ entries: pkg.entries,
1148
+ compareUrl
1149
+ };
1150
+ }
1151
+ function createDocumentContext(contexts, repoUrl) {
1152
+ const compareUrls = {};
1153
+ for (const ctx of contexts) {
1154
+ if (ctx.compareUrl) {
1155
+ compareUrls[ctx.version] = ctx.compareUrl;
1156
+ }
1157
+ }
1158
+ return {
1159
+ project: {
1160
+ name: contexts[0]?.packageName ?? "project",
1161
+ repoUrl
1162
+ },
1163
+ versions: contexts,
1164
+ compareUrls: Object.keys(compareUrls).length > 0 ? compareUrls : void 0
1165
+ };
1166
+ }
1167
+ async function processWithLLM(context, config) {
1168
+ if (!config.llm) {
1169
+ return context;
1170
+ }
1171
+ const tasks = config.llm.tasks ?? {};
1172
+ const llmContext = {
1173
+ packageName: context.packageName,
1174
+ version: context.version,
1175
+ previousVersion: context.previousVersion ?? void 0,
1176
+ date: context.date
1177
+ };
1178
+ const enhanced = {
1179
+ entries: context.entries
1180
+ };
1181
+ try {
1182
+ const rawProvider = createProvider(config.llm);
1183
+ const retryOpts = config.llm.retry ?? LLM_DEFAULTS.retry;
1184
+ const provider = {
1185
+ name: rawProvider.name,
1186
+ complete: (prompt, opts) => withRetry(() => rawProvider.complete(prompt, opts), retryOpts)
1187
+ };
1188
+ if (tasks.enhance) {
1189
+ (0, import_core7.debug)("Enhancing entries with LLM");
1190
+ enhanced.entries = await enhanceEntries(provider, context.entries, llmContext, config.llm.concurrency);
1191
+ }
1192
+ if (tasks.summarize) {
1193
+ (0, import_core7.debug)("Summarizing entries with LLM");
1194
+ enhanced.summary = await summarizeEntries(provider, enhanced.entries, llmContext);
1195
+ }
1196
+ if (tasks.categorize) {
1197
+ (0, import_core7.debug)("Categorizing entries with LLM");
1198
+ const categorized = await categorizeEntries(provider, enhanced.entries, llmContext);
1199
+ enhanced.categories = {};
1200
+ for (const cat of categorized) {
1201
+ enhanced.categories[cat.category] = cat.entries;
1202
+ }
1203
+ }
1204
+ if (tasks.releaseNotes) {
1205
+ (0, import_core7.debug)("Generating release notes with LLM");
1206
+ enhanced.releaseNotes = await generateReleaseNotes(provider, enhanced.entries, llmContext);
1207
+ }
1208
+ return {
1209
+ ...context,
1210
+ entries: enhanced.entries,
1211
+ enhanced
1212
+ };
1213
+ } catch (error) {
1214
+ (0, import_core7.warn)(`LLM processing failed: ${error instanceof Error ? error.message : String(error)}`);
1215
+ (0, import_core7.warn)("Falling back to raw entries");
1216
+ return context;
1217
+ }
1218
+ }
1219
+ function getBuiltinTemplatePath(style) {
1220
+ let packageRoot;
1221
+ try {
1222
+ const currentUrl = import_meta.url;
1223
+ packageRoot = path6.dirname(new URL(currentUrl).pathname);
1224
+ packageRoot = path6.join(packageRoot, "..", "..");
1225
+ } catch {
1226
+ packageRoot = __dirname;
1227
+ }
1228
+ return path6.join(packageRoot, "templates", style);
1229
+ }
1230
+ async function generateWithTemplate(contexts, config, outputPath, dryRun) {
1231
+ let templatePath;
1232
+ if (config.templates?.path) {
1233
+ templatePath = path6.resolve(config.templates.path);
1234
+ } else {
1235
+ templatePath = getBuiltinTemplatePath("keep-a-changelog");
1236
+ }
1237
+ const documentContext = createDocumentContext(
1238
+ contexts,
1239
+ config.templates?.path ? void 0 : contexts[0]?.repoUrl ?? void 0
1240
+ );
1241
+ const result = renderTemplate(templatePath, documentContext, config.templates?.engine);
1242
+ if (dryRun) {
1243
+ (0, import_core7.info)("--- Changelog Preview ---");
1244
+ console.log(result.content);
1245
+ (0, import_core7.info)("--- End Preview ---");
1246
+ return;
1247
+ }
1248
+ const dir = path6.dirname(outputPath);
1249
+ if (!fs8.existsSync(dir)) {
1250
+ fs8.mkdirSync(dir, { recursive: true });
1251
+ }
1252
+ fs8.writeFileSync(outputPath, result.content, "utf-8");
1253
+ (0, import_core7.success)(`Changelog written to ${outputPath} (using ${result.engine} template)`);
1254
+ }
1255
+ async function runPipeline(input, config, dryRun) {
1256
+ (0, import_core7.debug)(`Processing ${input.packages.length} package(s)`);
1257
+ let contexts = input.packages.map(createTemplateContext);
1258
+ if (config.llm && !process.env.CHANGELOG_NO_LLM && !dryRun) {
1259
+ (0, import_core7.info)("Processing with LLM enhancement");
1260
+ contexts = await Promise.all(contexts.map((ctx) => processWithLLM(ctx, config)));
1261
+ } else if (config.llm && dryRun) {
1262
+ (0, import_core7.info)("Skipping LLM processing in dry-run mode");
1263
+ }
1264
+ for (const output of config.output) {
1265
+ (0, import_core7.info)(`Generating ${output.format} output`);
1266
+ switch (output.format) {
1267
+ case "markdown": {
1268
+ const file = output.file ?? "CHANGELOG.md";
1269
+ if (config.templates?.path || output.options?.template) {
1270
+ await generateWithTemplate(contexts, config, file, dryRun);
1271
+ } else {
1272
+ writeMarkdown(file, contexts, config, dryRun);
1273
+ }
1274
+ break;
1275
+ }
1276
+ case "json": {
1277
+ const file = output.file ?? "changelog.json";
1278
+ writeJson(file, contexts, dryRun);
1279
+ break;
1280
+ }
1281
+ case "github-release": {
1282
+ if (dryRun) {
1283
+ (0, import_core7.info)("[DRY RUN] Would create GitHub release");
1284
+ break;
1285
+ }
1286
+ const firstContext = contexts[0];
1287
+ if (!firstContext) {
1288
+ (0, import_core7.warn)("No context available for GitHub release");
1289
+ break;
1290
+ }
1291
+ const repoUrl = firstContext.repoUrl;
1292
+ if (!repoUrl) {
1293
+ (0, import_core7.warn)("No repo URL available, cannot create GitHub release");
1294
+ break;
1295
+ }
1296
+ const parsed = parseRepoUrl(repoUrl);
1297
+ if (!parsed) {
1298
+ (0, import_core7.warn)(`Could not parse repo URL: ${repoUrl}`);
1299
+ break;
1300
+ }
1301
+ await createGitHubRelease(firstContext, {
1302
+ owner: parsed.owner,
1303
+ repo: parsed.repo,
1304
+ draft: output.options?.draft,
1305
+ prerelease: output.options?.prerelease
1306
+ });
1307
+ break;
1308
+ }
1309
+ }
1310
+ }
1311
+ }
1312
+ async function processInput(inputJson, config, dryRun) {
1313
+ const input = parsePackageVersioner(inputJson);
1314
+ await runPipeline(input, config, dryRun);
1315
+ }
1316
+
1317
+ // src/monorepo/aggregator.ts
1318
+ var fs9 = __toESM(require("fs"), 1);
1319
+ var path7 = __toESM(require("path"), 1);
1320
+ var import_core8 = require("@releasekit/core");
1321
+
1322
+ // src/monorepo/splitter.ts
1323
+ function splitByPackage(contexts) {
1324
+ const byPackage = /* @__PURE__ */ new Map();
1325
+ for (const ctx of contexts) {
1326
+ byPackage.set(ctx.packageName, ctx);
1327
+ }
1328
+ return byPackage;
1329
+ }
1330
+
1331
+ // src/monorepo/aggregator.ts
1332
+ function writeFile(outputPath, content, dryRun) {
1333
+ if (dryRun) {
1334
+ (0, import_core8.info)(`[DRY RUN] Would write to ${outputPath}`);
1335
+ console.log(content);
1336
+ return;
1337
+ }
1338
+ const dir = path7.dirname(outputPath);
1339
+ if (!fs9.existsSync(dir)) {
1340
+ fs9.mkdirSync(dir, { recursive: true });
1341
+ }
1342
+ fs9.writeFileSync(outputPath, content, "utf-8");
1343
+ (0, import_core8.success)(`Changelog written to ${outputPath}`);
1344
+ }
1345
+ function aggregateToRoot(contexts) {
1346
+ const aggregated = {
1347
+ packageName: "monorepo",
1348
+ version: contexts[0]?.version ?? "0.0.0",
1349
+ previousVersion: contexts[0]?.previousVersion ?? null,
1350
+ date: (/* @__PURE__ */ new Date()).toISOString().split("T")[0] ?? "",
1351
+ repoUrl: contexts[0]?.repoUrl ?? null,
1352
+ entries: []
1353
+ };
1354
+ for (const ctx of contexts) {
1355
+ for (const entry of ctx.entries) {
1356
+ aggregated.entries.push({
1357
+ ...entry,
1358
+ scope: entry.scope ? `${ctx.packageName}/${entry.scope}` : ctx.packageName
1359
+ });
1360
+ }
1361
+ }
1362
+ return aggregated;
1363
+ }
1364
+ function writeMonorepoChangelogs(contexts, options, config, dryRun) {
1365
+ if (options.mode === "root" || options.mode === "both") {
1366
+ const aggregated = aggregateToRoot(contexts);
1367
+ const rootPath = path7.join(options.rootPath, "CHANGELOG.md");
1368
+ (0, import_core8.info)(`Writing root changelog to ${rootPath}`);
1369
+ const rootContent = config.updateStrategy === "prepend" && fs9.existsSync(rootPath) ? prependVersion(rootPath, aggregated) : renderMarkdown([aggregated]);
1370
+ writeFile(rootPath, rootContent, dryRun);
1371
+ }
1372
+ if (options.mode === "packages" || options.mode === "both") {
1373
+ const byPackage = splitByPackage(contexts);
1374
+ const packageDirMap = buildPackageDirMap(options.rootPath, options.packagesPath);
1375
+ for (const [packageName, ctx] of byPackage) {
1376
+ const simpleName = packageName.split("/").pop();
1377
+ const packageDir = packageDirMap.get(packageName) ?? (simpleName ? packageDirMap.get(simpleName) : void 0) ?? null;
1378
+ if (packageDir) {
1379
+ const changelogPath = path7.join(packageDir, "CHANGELOG.md");
1380
+ (0, import_core8.info)(`Writing changelog for ${packageName} to ${changelogPath}`);
1381
+ const pkgContent = config.updateStrategy === "prepend" && fs9.existsSync(changelogPath) ? prependVersion(changelogPath, ctx) : renderMarkdown([ctx]);
1382
+ writeFile(changelogPath, pkgContent, dryRun);
1383
+ } else {
1384
+ (0, import_core8.info)(`Could not find directory for package ${packageName}, skipping`);
1385
+ }
1386
+ }
1387
+ }
1388
+ }
1389
+ function buildPackageDirMap(rootPath, packagesPath) {
1390
+ const map = /* @__PURE__ */ new Map();
1391
+ const packagesDir = path7.join(rootPath, packagesPath);
1392
+ if (!fs9.existsSync(packagesDir)) {
1393
+ return map;
1394
+ }
1395
+ for (const entry of fs9.readdirSync(packagesDir, { withFileTypes: true })) {
1396
+ if (!entry.isDirectory()) continue;
1397
+ const dirPath = path7.join(packagesDir, entry.name);
1398
+ map.set(entry.name, dirPath);
1399
+ const packageJsonPath = path7.join(dirPath, "package.json");
1400
+ if (fs9.existsSync(packageJsonPath)) {
1401
+ try {
1402
+ const pkg = JSON.parse(fs9.readFileSync(packageJsonPath, "utf-8"));
1403
+ if (pkg.name) {
1404
+ map.set(pkg.name, dirPath);
1405
+ }
1406
+ } catch {
1407
+ }
1408
+ }
1409
+ }
1410
+ return map;
1411
+ }
1412
+ function detectMonorepo(cwd) {
1413
+ const pnpmWorkspacesPath = path7.join(cwd, "pnpm-workspace.yaml");
1414
+ const packageJsonPath = path7.join(cwd, "package.json");
1415
+ if (fs9.existsSync(pnpmWorkspacesPath)) {
1416
+ const content = fs9.readFileSync(pnpmWorkspacesPath, "utf-8");
1417
+ const packagesMatch = content.match(/packages:\s*\n\s*-\s*['"]([^'"]+)['"]/);
1418
+ if (packagesMatch?.[1]) {
1419
+ const packagesGlob = packagesMatch[1];
1420
+ const packagesPath = packagesGlob.replace(/\/?\*$/, "").replace(/\/\*\*$/, "");
1421
+ return { isMonorepo: true, packagesPath: packagesPath || "packages" };
1422
+ }
1423
+ return { isMonorepo: true, packagesPath: "packages" };
1424
+ }
1425
+ if (fs9.existsSync(packageJsonPath)) {
1426
+ try {
1427
+ const content = fs9.readFileSync(packageJsonPath, "utf-8");
1428
+ const pkg = JSON.parse(content);
1429
+ if (pkg.workspaces) {
1430
+ const workspaces = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces.packages;
1431
+ if (workspaces?.length) {
1432
+ const firstWorkspace = workspaces[0];
1433
+ if (firstWorkspace) {
1434
+ const packagesPath = firstWorkspace.replace(/\/?\*$/, "").replace(/\/\*\*$/, "");
1435
+ return { isMonorepo: true, packagesPath: packagesPath || "packages" };
1436
+ }
1437
+ }
1438
+ }
1439
+ } catch {
1440
+ return { isMonorepo: false, packagesPath: "" };
1441
+ }
1442
+ }
1443
+ return { isMonorepo: false, packagesPath: "" };
1444
+ }
1445
+ // Annotate the CommonJS export names for ESM import in node:
1446
+ 0 && (module.exports = {
1447
+ ChangelogCreatorError,
1448
+ ConfigError,
1449
+ EXIT_CODES,
1450
+ GitHubError,
1451
+ InputParseError,
1452
+ LLMError,
1453
+ NotesError,
1454
+ TemplateError,
1455
+ aggregateToRoot,
1456
+ createTemplateContext,
1457
+ detectMonorepo,
1458
+ getDefaultConfig,
1459
+ getExitCode,
1460
+ loadAuth,
1461
+ loadConfig,
1462
+ parsePackageVersioner,
1463
+ parsePackageVersionerFile,
1464
+ parsePackageVersionerStdin,
1465
+ processInput,
1466
+ renderJson,
1467
+ renderMarkdown,
1468
+ runPipeline,
1469
+ saveAuth,
1470
+ writeJson,
1471
+ writeMarkdown,
1472
+ writeMonorepoChangelogs
1473
+ });