tst-changelog 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/README.md ADDED
@@ -0,0 +1,106 @@
1
+ # tst-changelog
2
+
3
+ AI-powered changelog generator using OpenRouter. Analyzes your git commits and staged changes to automatically generate changelog entries following the [Keep a Changelog](https://keepachangelog.com/) format.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add tst-changelog
9
+ # or
10
+ npm install tst-changelog
11
+ ```
12
+
13
+ ## Configuration
14
+
15
+ Create a `tst-changelog.yaml` file in your project root:
16
+
17
+ ```yaml
18
+ # AI Configuration
19
+ ai:
20
+ provider: openrouter
21
+ model: anthropic/claude-3-haiku
22
+ token: ${OPENROUTER_API_KEY} # Supports environment variables
23
+
24
+ # Changelog Configuration
25
+ changelog:
26
+ file: CHANGELOG.md
27
+ format: keepachangelog
28
+ includeDate: true
29
+ groupBy: type
30
+
31
+ # Git Configuration
32
+ git:
33
+ baseBranch: main
34
+ analyzeDepth: 50
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ ### CLI
40
+
41
+ ```bash
42
+ # Basic usage (reads config from ./tst-changelog.yaml)
43
+ npx tst-changelog
44
+
45
+ # With options
46
+ npx tst-changelog --config ./custom-config.yaml
47
+ npx tst-changelog --dry-run # Preview without modifying files
48
+ npx tst-changelog --verbose # Enable detailed output
49
+ ```
50
+
51
+ ### Pre-commit Hook (with Husky)
52
+
53
+ Add to your `.husky/pre-commit`:
54
+
55
+ ```bash
56
+ #!/bin/sh
57
+ . "$(dirname "$0")/_/husky.sh"
58
+
59
+ npx tst-changelog
60
+ ```
61
+
62
+ ### Programmatic Usage
63
+
64
+ ```typescript
65
+ import { loadConfig, GitService, AIService, ChangelogService } from 'tst-changelog';
66
+
67
+ const config = loadConfig('./tst-changelog.yaml');
68
+ const git = new GitService(config.git);
69
+ const ai = new AIService(config.ai);
70
+ const changelog = new ChangelogService(config.changelog);
71
+
72
+ const staged = await git.getStagedChanges();
73
+ const commits = await git.getUnmergedCommits();
74
+ const generated = await ai.generateChangelog(commits, staged);
75
+ const content = changelog.update(generated);
76
+ changelog.write(content);
77
+ ```
78
+
79
+ ## How It Works
80
+
81
+ 1. Reads your configuration from `tst-changelog.yaml`
82
+ 2. Collects staged git changes and recent commits
83
+ 3. Sends the context to OpenRouter AI for analysis
84
+ 4. Parses conventional commits (feat:, fix:, etc.)
85
+ 5. Generates changelog entries grouped by type
86
+ 6. Updates or creates CHANGELOG.md
87
+ 7. Stages the changelog file for commit
88
+
89
+ ## Supported Change Types
90
+
91
+ Following Keep a Changelog format:
92
+
93
+ - **Added** - New features
94
+ - **Changed** - Changes in existing functionality
95
+ - **Deprecated** - Features to be removed
96
+ - **Removed** - Removed features
97
+ - **Fixed** - Bug fixes
98
+ - **Security** - Security improvements
99
+
100
+ ## Environment Variables
101
+
102
+ - `OPENROUTER_API_KEY` - Your OpenRouter API key
103
+
104
+ ## License
105
+
106
+ MIT
@@ -0,0 +1,136 @@
1
+ interface AIConfig {
2
+ provider: 'openrouter';
3
+ model: string;
4
+ token: string;
5
+ }
6
+ interface ChangelogConfig {
7
+ file: string;
8
+ format: 'keepachangelog' | 'simple';
9
+ includeDate: boolean;
10
+ groupBy: 'type' | 'scope' | 'none';
11
+ }
12
+ interface GitConfig {
13
+ baseBranch: string;
14
+ analyzeDepth: number;
15
+ }
16
+ interface Config {
17
+ ai: AIConfig;
18
+ changelog: ChangelogConfig;
19
+ git: GitConfig;
20
+ }
21
+ interface CommitInfo {
22
+ hash: string;
23
+ message: string;
24
+ author: string;
25
+ date: string;
26
+ body?: string;
27
+ }
28
+ interface StagedChanges {
29
+ files: string[];
30
+ diff: string;
31
+ }
32
+ interface ChangelogEntry {
33
+ version?: string;
34
+ date: string;
35
+ sections: ChangelogSection[];
36
+ }
37
+ interface ChangelogSection {
38
+ type: ChangeType;
39
+ items: string[];
40
+ }
41
+ type ChangeType = 'Added' | 'Changed' | 'Deprecated' | 'Removed' | 'Fixed' | 'Security';
42
+ interface GeneratedChangelog {
43
+ raw: string;
44
+ sections: ChangelogSection[];
45
+ }
46
+ interface CLIOptions {
47
+ config?: string;
48
+ dryRun?: boolean;
49
+ verbose?: boolean;
50
+ }
51
+
52
+ /**
53
+ * Load configuration from yaml file
54
+ */
55
+ declare function loadConfig(configPath?: string): Config;
56
+
57
+ declare class GitService {
58
+ private git;
59
+ private config;
60
+ constructor(config: GitConfig, cwd?: string);
61
+ /**
62
+ * Get list of staged files
63
+ */
64
+ getStagedFiles(): Promise<string[]>;
65
+ /**
66
+ * Get diff of staged changes
67
+ */
68
+ getStagedDiff(): Promise<string>;
69
+ /**
70
+ * Get staged changes (files + diff)
71
+ */
72
+ getStagedChanges(): Promise<StagedChanges>;
73
+ /**
74
+ * Get recent commits from the base branch
75
+ */
76
+ getRecentCommits(count?: number): Promise<CommitInfo[]>;
77
+ /**
78
+ * Get commits not yet in base branch (for feature branches)
79
+ */
80
+ getUnmergedCommits(): Promise<CommitInfo[]>;
81
+ /**
82
+ * Get current branch name
83
+ */
84
+ getCurrentBranch(): Promise<string>;
85
+ /**
86
+ * Stage a file
87
+ */
88
+ stageFile(filePath: string): Promise<void>;
89
+ /**
90
+ * Check if we're in a git repository
91
+ */
92
+ isGitRepo(): Promise<boolean>;
93
+ }
94
+
95
+ declare class AIService {
96
+ private config;
97
+ constructor(config: AIConfig);
98
+ /**
99
+ * Generate changelog entries from commits and staged changes
100
+ */
101
+ generateChangelog(commits: CommitInfo[], staged: StagedChanges): Promise<GeneratedChangelog>;
102
+ private buildPrompt;
103
+ private callOpenRouter;
104
+ private parseResponse;
105
+ }
106
+
107
+ declare class ChangelogService {
108
+ private config;
109
+ private filePath;
110
+ constructor(config: ChangelogConfig, cwd?: string);
111
+ /**
112
+ * Read existing changelog content
113
+ */
114
+ read(): string | null;
115
+ /**
116
+ * Generate new changelog entry
117
+ */
118
+ formatEntry(generated: GeneratedChangelog, version?: string): string;
119
+ private sortSections;
120
+ private formatSection;
121
+ /**
122
+ * Update or create changelog with new entry
123
+ */
124
+ update(generated: GeneratedChangelog, version?: string): string;
125
+ private findSectionEnd;
126
+ /**
127
+ * Write changelog to file
128
+ */
129
+ write(content: string): void;
130
+ /**
131
+ * Get the file path
132
+ */
133
+ getFilePath(): string;
134
+ }
135
+
136
+ export { type AIConfig, AIService, type CLIOptions, type ChangeType, type ChangelogConfig, type ChangelogEntry, type ChangelogSection, ChangelogService, type CommitInfo, type Config, type GeneratedChangelog, type GitConfig, GitService, type StagedChanges, loadConfig };
package/dist/index.js ADDED
@@ -0,0 +1,503 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { Command } from "commander";
5
+
6
+ // src/config.ts
7
+ import { readFileSync, existsSync } from "fs";
8
+ import { resolve } from "path";
9
+ import { parse } from "yaml";
10
+ var DEFAULT_CONFIG = {
11
+ ai: {
12
+ provider: "openrouter",
13
+ model: "anthropic/claude-3-haiku",
14
+ token: ""
15
+ },
16
+ changelog: {
17
+ file: "CHANGELOG.md",
18
+ format: "keepachangelog",
19
+ includeDate: true,
20
+ groupBy: "type"
21
+ },
22
+ git: {
23
+ baseBranch: "main",
24
+ analyzeDepth: 50
25
+ }
26
+ };
27
+ function resolveEnvVars(value) {
28
+ return value.replace(/\$\{([^}]+)\}/g, (_, envVar) => {
29
+ const envValue = process.env[envVar];
30
+ if (!envValue) {
31
+ throw new Error(`Environment variable ${envVar} is not set`);
32
+ }
33
+ return envValue;
34
+ });
35
+ }
36
+ function resolveConfigEnvVars(obj) {
37
+ if (typeof obj === "string") {
38
+ return resolveEnvVars(obj);
39
+ }
40
+ if (Array.isArray(obj)) {
41
+ return obj.map(resolveConfigEnvVars);
42
+ }
43
+ if (obj && typeof obj === "object") {
44
+ const resolved = {};
45
+ for (const [key, value] of Object.entries(obj)) {
46
+ resolved[key] = resolveConfigEnvVars(value);
47
+ }
48
+ return resolved;
49
+ }
50
+ return obj;
51
+ }
52
+ function deepMerge(target, source) {
53
+ return {
54
+ ai: { ...target.ai, ...source.ai },
55
+ changelog: { ...target.changelog, ...source.changelog },
56
+ git: { ...target.git, ...source.git }
57
+ };
58
+ }
59
+ function loadConfig(configPath) {
60
+ const defaultPaths = ["tst-changelog.yaml", "tst-changelog.yml", ".tst-changelog.yaml"];
61
+ let filePath;
62
+ if (configPath) {
63
+ filePath = resolve(process.cwd(), configPath);
64
+ if (!existsSync(filePath)) {
65
+ throw new Error(`Config file not found: ${filePath}`);
66
+ }
67
+ } else {
68
+ for (const p of defaultPaths) {
69
+ const fullPath = resolve(process.cwd(), p);
70
+ if (existsSync(fullPath)) {
71
+ filePath = fullPath;
72
+ break;
73
+ }
74
+ }
75
+ }
76
+ if (!filePath) {
77
+ console.warn("No config file found, using defaults");
78
+ return resolveConfigEnvVars(DEFAULT_CONFIG);
79
+ }
80
+ const content = readFileSync(filePath, "utf-8");
81
+ const parsed = parse(content);
82
+ const merged = deepMerge(DEFAULT_CONFIG, parsed);
83
+ return resolveConfigEnvVars(merged);
84
+ }
85
+
86
+ // src/git.ts
87
+ import simpleGit from "simple-git";
88
+ var GitService = class {
89
+ git;
90
+ config;
91
+ constructor(config, cwd) {
92
+ this.git = simpleGit(cwd);
93
+ this.config = config;
94
+ }
95
+ /**
96
+ * Get list of staged files
97
+ */
98
+ async getStagedFiles() {
99
+ const status = await this.git.status();
100
+ return status.staged;
101
+ }
102
+ /**
103
+ * Get diff of staged changes
104
+ */
105
+ async getStagedDiff() {
106
+ const diff = await this.git.diff(["--cached"]);
107
+ return diff;
108
+ }
109
+ /**
110
+ * Get staged changes (files + diff)
111
+ */
112
+ async getStagedChanges() {
113
+ const [files, diff] = await Promise.all([
114
+ this.getStagedFiles(),
115
+ this.getStagedDiff()
116
+ ]);
117
+ return { files, diff };
118
+ }
119
+ /**
120
+ * Get recent commits from the base branch
121
+ */
122
+ async getRecentCommits(count) {
123
+ const limit = count ?? this.config.analyzeDepth;
124
+ const log = await this.git.log({
125
+ maxCount: limit,
126
+ format: {
127
+ hash: "%H",
128
+ message: "%s",
129
+ author: "%an",
130
+ date: "%aI",
131
+ body: "%b"
132
+ }
133
+ });
134
+ return log.all.map((commit) => ({
135
+ hash: commit.hash,
136
+ message: commit.message,
137
+ author: commit.author,
138
+ date: commit.date,
139
+ body: commit.body?.trim() || void 0
140
+ }));
141
+ }
142
+ /**
143
+ * Get commits not yet in base branch (for feature branches)
144
+ */
145
+ async getUnmergedCommits() {
146
+ try {
147
+ const log = await this.git.log({
148
+ from: this.config.baseBranch,
149
+ to: "HEAD",
150
+ format: {
151
+ hash: "%H",
152
+ message: "%s",
153
+ author: "%an",
154
+ date: "%aI",
155
+ body: "%b"
156
+ }
157
+ });
158
+ return log.all.map((commit) => ({
159
+ hash: commit.hash,
160
+ message: commit.message,
161
+ author: commit.author,
162
+ date: commit.date,
163
+ body: commit.body?.trim() || void 0
164
+ }));
165
+ } catch {
166
+ return [];
167
+ }
168
+ }
169
+ /**
170
+ * Get current branch name
171
+ */
172
+ async getCurrentBranch() {
173
+ const branch = await this.git.revparse(["--abbrev-ref", "HEAD"]);
174
+ return branch.trim();
175
+ }
176
+ /**
177
+ * Stage a file
178
+ */
179
+ async stageFile(filePath) {
180
+ await this.git.add(filePath);
181
+ }
182
+ /**
183
+ * Check if we're in a git repository
184
+ */
185
+ async isGitRepo() {
186
+ try {
187
+ await this.git.revparse(["--git-dir"]);
188
+ return true;
189
+ } catch {
190
+ return false;
191
+ }
192
+ }
193
+ };
194
+
195
+ // src/ai.ts
196
+ var OPENROUTER_API_URL = "https://openrouter.ai/api/v1/chat/completions";
197
+ var SYSTEM_PROMPT = `You are a changelog generator. Your task is to analyze git commits and staged changes to generate changelog entries following the Keep a Changelog format.
198
+
199
+ Output Format:
200
+ Return ONLY a JSON object with the following structure:
201
+ {
202
+ "sections": [
203
+ {
204
+ "type": "Added" | "Changed" | "Deprecated" | "Removed" | "Fixed" | "Security",
205
+ "items": ["description 1", "description 2"]
206
+ }
207
+ ]
208
+ }
209
+
210
+ Guidelines:
211
+ - Use present tense (e.g., "Add feature" not "Added feature")
212
+ - Be concise but descriptive
213
+ - Group related changes together
214
+ - Focus on user-facing changes
215
+ - Ignore merge commits and trivial changes
216
+ - Parse conventional commits (feat:, fix:, etc.) into appropriate sections:
217
+ - feat: -> Added
218
+ - fix: -> Fixed
219
+ - docs:, style:, refactor:, perf:, test:, chore: -> Changed
220
+ - BREAKING CHANGE: -> Changed (mention breaking)
221
+ - deprecate: -> Deprecated
222
+ - remove: -> Removed
223
+ - security: -> Security`;
224
+ var AIService = class {
225
+ config;
226
+ constructor(config) {
227
+ this.config = config;
228
+ }
229
+ /**
230
+ * Generate changelog entries from commits and staged changes
231
+ */
232
+ async generateChangelog(commits, staged) {
233
+ const userPrompt = this.buildPrompt(commits, staged);
234
+ const response = await this.callOpenRouter(userPrompt);
235
+ return this.parseResponse(response);
236
+ }
237
+ buildPrompt(commits, staged) {
238
+ const parts = [];
239
+ if (commits.length > 0) {
240
+ parts.push("## Recent Commits:");
241
+ for (const commit of commits.slice(0, 20)) {
242
+ parts.push(`- ${commit.message}`);
243
+ if (commit.body) {
244
+ parts.push(` ${commit.body}`);
245
+ }
246
+ }
247
+ }
248
+ if (staged.files.length > 0) {
249
+ parts.push("\n## Staged Files:");
250
+ parts.push(staged.files.join("\n"));
251
+ }
252
+ if (staged.diff) {
253
+ const maxDiffLength = 4e3;
254
+ const truncatedDiff = staged.diff.length > maxDiffLength ? staged.diff.slice(0, maxDiffLength) + "\n... (truncated)" : staged.diff;
255
+ parts.push("\n## Staged Diff:");
256
+ parts.push("```diff");
257
+ parts.push(truncatedDiff);
258
+ parts.push("```");
259
+ }
260
+ parts.push("\nGenerate changelog entries for these changes.");
261
+ return parts.join("\n");
262
+ }
263
+ async callOpenRouter(prompt) {
264
+ const response = await fetch(OPENROUTER_API_URL, {
265
+ method: "POST",
266
+ headers: {
267
+ "Content-Type": "application/json",
268
+ "Authorization": `Bearer ${this.config.token}`,
269
+ "HTTP-Referer": "https://github.com/testudosrl/tst-libs",
270
+ "X-Title": "tst-changelog"
271
+ },
272
+ body: JSON.stringify({
273
+ model: this.config.model,
274
+ messages: [
275
+ { role: "system", content: SYSTEM_PROMPT },
276
+ { role: "user", content: prompt }
277
+ ],
278
+ temperature: 0.3,
279
+ max_tokens: 1e3
280
+ })
281
+ });
282
+ if (!response.ok) {
283
+ const error = await response.text();
284
+ throw new Error(`OpenRouter API error: ${response.status} - ${error}`);
285
+ }
286
+ const data = await response.json();
287
+ return data.choices[0]?.message?.content ?? "";
288
+ }
289
+ parseResponse(response) {
290
+ try {
291
+ let jsonStr = response;
292
+ const codeBlockMatch = response.match(/```(?:json)?\s*([\s\S]*?)```/);
293
+ if (codeBlockMatch) {
294
+ jsonStr = codeBlockMatch[1];
295
+ } else {
296
+ const jsonObjectMatch = response.match(/\{[\s\S]*"sections"[\s\S]*\}/);
297
+ if (jsonObjectMatch) {
298
+ jsonStr = jsonObjectMatch[0];
299
+ }
300
+ }
301
+ const parsed = JSON.parse(jsonStr.trim());
302
+ const validTypes = ["Added", "Changed", "Deprecated", "Removed", "Fixed", "Security"];
303
+ const sections = parsed.sections.filter((s) => validTypes.includes(s.type)).map((s) => ({
304
+ type: s.type,
305
+ items: Array.isArray(s.items) ? s.items.filter((i) => typeof i === "string") : []
306
+ })).filter((s) => s.items.length > 0);
307
+ return {
308
+ raw: response,
309
+ sections
310
+ };
311
+ } catch (error) {
312
+ console.error("Failed to parse AI response:", error);
313
+ console.error("Raw response:", response);
314
+ return {
315
+ raw: response,
316
+ sections: []
317
+ };
318
+ }
319
+ }
320
+ };
321
+
322
+ // src/changelog.ts
323
+ import { readFileSync as readFileSync2, writeFileSync, existsSync as existsSync2 } from "fs";
324
+ import { resolve as resolve2 } from "path";
325
+ var KEEPACHANGELOG_HEADER = `# Changelog
326
+
327
+ All notable changes to this project will be documented in this file.
328
+
329
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
330
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
331
+
332
+ `;
333
+ var SECTION_ORDER = ["Added", "Changed", "Deprecated", "Removed", "Fixed", "Security"];
334
+ var ChangelogService = class {
335
+ config;
336
+ filePath;
337
+ constructor(config, cwd) {
338
+ this.config = config;
339
+ this.filePath = resolve2(cwd ?? process.cwd(), config.file);
340
+ }
341
+ /**
342
+ * Read existing changelog content
343
+ */
344
+ read() {
345
+ if (!existsSync2(this.filePath)) {
346
+ return null;
347
+ }
348
+ return readFileSync2(this.filePath, "utf-8");
349
+ }
350
+ /**
351
+ * Generate new changelog entry
352
+ */
353
+ formatEntry(generated, version) {
354
+ const date = this.config.includeDate ? (/* @__PURE__ */ new Date()).toISOString().split("T")[0] : "";
355
+ const versionStr = version ?? "Unreleased";
356
+ const headerLine = date ? `## [${versionStr}] - ${date}` : `## [${versionStr}]`;
357
+ const sections = this.sortSections(generated.sections);
358
+ const sectionLines = sections.map((section) => this.formatSection(section)).join("\n\n");
359
+ return `${headerLine}
360
+
361
+ ${sectionLines}`;
362
+ }
363
+ sortSections(sections) {
364
+ return [...sections].sort((a, b) => {
365
+ const indexA = SECTION_ORDER.indexOf(a.type);
366
+ const indexB = SECTION_ORDER.indexOf(b.type);
367
+ return indexA - indexB;
368
+ });
369
+ }
370
+ formatSection(section) {
371
+ const items = section.items.map((item) => `- ${item}`).join("\n");
372
+ return `### ${section.type}
373
+
374
+ ${items}`;
375
+ }
376
+ /**
377
+ * Update or create changelog with new entry
378
+ */
379
+ update(generated, version) {
380
+ const newEntry = this.formatEntry(generated, version);
381
+ const existing = this.read();
382
+ if (!existing) {
383
+ return KEEPACHANGELOG_HEADER + newEntry + "\n";
384
+ }
385
+ const lines = existing.split("\n");
386
+ let insertIndex = -1;
387
+ for (let i = 0; i < lines.length; i++) {
388
+ const line = lines[i];
389
+ if (line.startsWith("## [Unreleased]")) {
390
+ const endIndex = this.findSectionEnd(lines, i + 1);
391
+ const before2 = lines.slice(0, i).join("\n");
392
+ const after2 = lines.slice(endIndex).join("\n");
393
+ return before2 + (before2.endsWith("\n") ? "" : "\n") + newEntry + "\n\n" + after2;
394
+ }
395
+ if (line.startsWith("## [") && insertIndex === -1) {
396
+ insertIndex = i;
397
+ break;
398
+ }
399
+ }
400
+ if (insertIndex === -1) {
401
+ return existing.trimEnd() + "\n\n" + newEntry + "\n";
402
+ }
403
+ const before = lines.slice(0, insertIndex).join("\n");
404
+ const after = lines.slice(insertIndex).join("\n");
405
+ return before + (before.endsWith("\n") ? "" : "\n") + newEntry + "\n\n" + after;
406
+ }
407
+ findSectionEnd(lines, startIndex) {
408
+ for (let i = startIndex; i < lines.length; i++) {
409
+ if (lines[i].startsWith("## [")) {
410
+ return i;
411
+ }
412
+ }
413
+ return lines.length;
414
+ }
415
+ /**
416
+ * Write changelog to file
417
+ */
418
+ write(content) {
419
+ writeFileSync(this.filePath, content, "utf-8");
420
+ }
421
+ /**
422
+ * Get the file path
423
+ */
424
+ getFilePath() {
425
+ return this.filePath;
426
+ }
427
+ };
428
+
429
+ // src/index.ts
430
+ var program = new Command();
431
+ program.name("tst-changelog").description("AI-powered changelog generator using OpenRouter").version("0.1.0").option("-c, --config <path>", "Path to config file").option("-d, --dry-run", "Preview without modifying files").option("-v, --verbose", "Enable verbose output").action(run);
432
+ async function run(options) {
433
+ const verbose = options.verbose ?? false;
434
+ try {
435
+ if (verbose) console.log("Loading configuration...");
436
+ const config = loadConfig(options.config);
437
+ if (verbose) console.log("Config loaded:", JSON.stringify(config, null, 2));
438
+ const git = new GitService(config.git);
439
+ const ai = new AIService(config.ai);
440
+ const changelog = new ChangelogService(config.changelog);
441
+ if (!await git.isGitRepo()) {
442
+ console.error("Error: Not a git repository");
443
+ process.exit(1);
444
+ }
445
+ if (verbose) console.log("Getting staged changes...");
446
+ const staged = await git.getStagedChanges();
447
+ if (staged.files.length === 0) {
448
+ console.log("No staged changes found. Stage some changes first.");
449
+ process.exit(0);
450
+ }
451
+ if (verbose) {
452
+ console.log(`Staged files: ${staged.files.join(", ")}`);
453
+ console.log(`Diff length: ${staged.diff.length} chars`);
454
+ }
455
+ if (verbose) console.log("Getting recent commits...");
456
+ const commits = await git.getUnmergedCommits();
457
+ if (verbose) console.log(`Found ${commits.length} unmerged commits`);
458
+ console.log("Generating changelog with AI...");
459
+ const generated = await ai.generateChangelog(commits, staged);
460
+ if (generated.sections.length === 0) {
461
+ console.log("No changelog entries generated.");
462
+ if (verbose) console.log("Raw AI response:", generated.raw);
463
+ process.exit(0);
464
+ }
465
+ if (verbose) {
466
+ console.log("Generated sections:");
467
+ for (const section of generated.sections) {
468
+ console.log(` ${section.type}:`);
469
+ for (const item of section.items) {
470
+ console.log(` - ${item}`);
471
+ }
472
+ }
473
+ }
474
+ const newContent = changelog.update(generated);
475
+ if (options.dryRun) {
476
+ console.log("\n--- DRY RUN ---");
477
+ console.log("Would update changelog at:", changelog.getFilePath());
478
+ console.log("\n--- New entry ---");
479
+ console.log(changelog.formatEntry(generated));
480
+ console.log("--- End ---\n");
481
+ process.exit(0);
482
+ }
483
+ changelog.write(newContent);
484
+ console.log(`Updated: ${changelog.getFilePath()}`);
485
+ await git.stageFile(config.changelog.file);
486
+ console.log("Staged changelog file");
487
+ console.log("Done!");
488
+ } catch (error) {
489
+ console.error("Error:", error instanceof Error ? error.message : error);
490
+ if (verbose && error instanceof Error) {
491
+ console.error(error.stack);
492
+ }
493
+ process.exit(1);
494
+ }
495
+ }
496
+ program.parse();
497
+ export {
498
+ AIService,
499
+ ChangelogService,
500
+ GitService,
501
+ loadConfig
502
+ };
503
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/config.ts","../src/git.ts","../src/ai.ts","../src/changelog.ts"],"sourcesContent":["import { Command } from 'commander';\nimport { loadConfig } from './config.js';\nimport { GitService } from './git.js';\nimport { AIService } from './ai.js';\nimport { ChangelogService } from './changelog.js';\nimport type { CLIOptions } from './types.js';\n\nconst program = new Command();\n\nprogram\n .name('tst-changelog')\n .description('AI-powered changelog generator using OpenRouter')\n .version('0.1.0')\n .option('-c, --config <path>', 'Path to config file')\n .option('-d, --dry-run', 'Preview without modifying files')\n .option('-v, --verbose', 'Enable verbose output')\n .action(run);\n\nasync function run(options: CLIOptions): Promise<void> {\n const verbose = options.verbose ?? false;\n\n try {\n // Load configuration\n if (verbose) console.log('Loading configuration...');\n const config = loadConfig(options.config);\n if (verbose) console.log('Config loaded:', JSON.stringify(config, null, 2));\n\n // Initialize services\n const git = new GitService(config.git);\n const ai = new AIService(config.ai);\n const changelog = new ChangelogService(config.changelog);\n\n // Check if we're in a git repo\n if (!(await git.isGitRepo())) {\n console.error('Error: Not a git repository');\n process.exit(1);\n }\n\n // Get staged changes\n if (verbose) console.log('Getting staged changes...');\n const staged = await git.getStagedChanges();\n\n if (staged.files.length === 0) {\n console.log('No staged changes found. Stage some changes first.');\n process.exit(0);\n }\n\n if (verbose) {\n console.log(`Staged files: ${staged.files.join(', ')}`);\n console.log(`Diff length: ${staged.diff.length} chars`);\n }\n\n // Get recent commits for context\n if (verbose) console.log('Getting recent commits...');\n const commits = await git.getUnmergedCommits();\n if (verbose) console.log(`Found ${commits.length} unmerged commits`);\n\n // Generate changelog using AI\n console.log('Generating changelog with AI...');\n const generated = await ai.generateChangelog(commits, staged);\n\n if (generated.sections.length === 0) {\n console.log('No changelog entries generated.');\n if (verbose) console.log('Raw AI response:', generated.raw);\n process.exit(0);\n }\n\n if (verbose) {\n console.log('Generated sections:');\n for (const section of generated.sections) {\n console.log(` ${section.type}:`);\n for (const item of section.items) {\n console.log(` - ${item}`);\n }\n }\n }\n\n // Update changelog\n const newContent = changelog.update(generated);\n\n if (options.dryRun) {\n console.log('\\n--- DRY RUN ---');\n console.log('Would update changelog at:', changelog.getFilePath());\n console.log('\\n--- New entry ---');\n console.log(changelog.formatEntry(generated));\n console.log('--- End ---\\n');\n process.exit(0);\n }\n\n // Write and stage\n changelog.write(newContent);\n console.log(`Updated: ${changelog.getFilePath()}`);\n\n await git.stageFile(config.changelog.file);\n console.log('Staged changelog file');\n\n console.log('Done!');\n } catch (error) {\n console.error('Error:', error instanceof Error ? error.message : error);\n if (verbose && error instanceof Error) {\n console.error(error.stack);\n }\n process.exit(1);\n }\n}\n\nprogram.parse();\n\n// Export for programmatic usage\nexport { loadConfig } from './config.js';\nexport { GitService } from './git.js';\nexport { AIService } from './ai.js';\nexport { ChangelogService } from './changelog.js';\nexport * from './types.js';\n","import { readFileSync, existsSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { parse } from 'yaml';\nimport type { Config } from './types.js';\n\nconst DEFAULT_CONFIG: Config = {\n ai: {\n provider: 'openrouter',\n model: 'anthropic/claude-3-haiku',\n token: '',\n },\n changelog: {\n file: 'CHANGELOG.md',\n format: 'keepachangelog',\n includeDate: true,\n groupBy: 'type',\n },\n git: {\n baseBranch: 'main',\n analyzeDepth: 50,\n },\n};\n\n/**\n * Resolve environment variables in config values\n * Supports ${ENV_VAR} syntax\n */\nfunction resolveEnvVars(value: string): string {\n return value.replace(/\\$\\{([^}]+)\\}/g, (_, envVar) => {\n const envValue = process.env[envVar];\n if (!envValue) {\n throw new Error(`Environment variable ${envVar} is not set`);\n }\n return envValue;\n });\n}\n\n/**\n * Recursively resolve env vars in object\n */\nfunction resolveConfigEnvVars<T>(obj: T): T {\n if (typeof obj === 'string') {\n return resolveEnvVars(obj) as T;\n }\n if (Array.isArray(obj)) {\n return obj.map(resolveConfigEnvVars) as T;\n }\n if (obj && typeof obj === 'object') {\n const resolved: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n resolved[key] = resolveConfigEnvVars(value);\n }\n return resolved as T;\n }\n return obj;\n}\n\n/**\n * Deep merge two objects\n */\nfunction deepMerge(target: Config, source: Partial<Config>): Config {\n return {\n ai: { ...target.ai, ...source.ai },\n changelog: { ...target.changelog, ...source.changelog },\n git: { ...target.git, ...source.git },\n };\n}\n\n/**\n * Load configuration from yaml file\n */\nexport function loadConfig(configPath?: string): Config {\n const defaultPaths = ['tst-changelog.yaml', 'tst-changelog.yml', '.tst-changelog.yaml'];\n\n let filePath: string | undefined;\n\n if (configPath) {\n filePath = resolve(process.cwd(), configPath);\n if (!existsSync(filePath)) {\n throw new Error(`Config file not found: ${filePath}`);\n }\n } else {\n for (const p of defaultPaths) {\n const fullPath = resolve(process.cwd(), p);\n if (existsSync(fullPath)) {\n filePath = fullPath;\n break;\n }\n }\n }\n\n if (!filePath) {\n console.warn('No config file found, using defaults');\n return resolveConfigEnvVars(DEFAULT_CONFIG);\n }\n\n const content = readFileSync(filePath, 'utf-8');\n const parsed = parse(content) as Partial<Config>;\n\n const merged = deepMerge(DEFAULT_CONFIG, parsed);\n return resolveConfigEnvVars(merged);\n}\n","import simpleGit, { SimpleGit } from 'simple-git';\nimport type { CommitInfo, StagedChanges, GitConfig } from './types.js';\n\nexport class GitService {\n private git: SimpleGit;\n private config: GitConfig;\n\n constructor(config: GitConfig, cwd?: string) {\n this.git = simpleGit(cwd);\n this.config = config;\n }\n\n /**\n * Get list of staged files\n */\n async getStagedFiles(): Promise<string[]> {\n const status = await this.git.status();\n return status.staged;\n }\n\n /**\n * Get diff of staged changes\n */\n async getStagedDiff(): Promise<string> {\n const diff = await this.git.diff(['--cached']);\n return diff;\n }\n\n /**\n * Get staged changes (files + diff)\n */\n async getStagedChanges(): Promise<StagedChanges> {\n const [files, diff] = await Promise.all([\n this.getStagedFiles(),\n this.getStagedDiff(),\n ]);\n return { files, diff };\n }\n\n /**\n * Get recent commits from the base branch\n */\n async getRecentCommits(count?: number): Promise<CommitInfo[]> {\n const limit = count ?? this.config.analyzeDepth;\n const log = await this.git.log({\n maxCount: limit,\n format: {\n hash: '%H',\n message: '%s',\n author: '%an',\n date: '%aI',\n body: '%b',\n },\n });\n\n return log.all.map((commit) => ({\n hash: commit.hash,\n message: commit.message,\n author: commit.author,\n date: commit.date,\n body: commit.body?.trim() || undefined,\n }));\n }\n\n /**\n * Get commits not yet in base branch (for feature branches)\n */\n async getUnmergedCommits(): Promise<CommitInfo[]> {\n try {\n const log = await this.git.log({\n from: this.config.baseBranch,\n to: 'HEAD',\n format: {\n hash: '%H',\n message: '%s',\n author: '%an',\n date: '%aI',\n body: '%b',\n },\n });\n\n return log.all.map((commit) => ({\n hash: commit.hash,\n message: commit.message,\n author: commit.author,\n date: commit.date,\n body: commit.body?.trim() || undefined,\n }));\n } catch {\n // If base branch doesn't exist, return empty\n return [];\n }\n }\n\n /**\n * Get current branch name\n */\n async getCurrentBranch(): Promise<string> {\n const branch = await this.git.revparse(['--abbrev-ref', 'HEAD']);\n return branch.trim();\n }\n\n /**\n * Stage a file\n */\n async stageFile(filePath: string): Promise<void> {\n await this.git.add(filePath);\n }\n\n /**\n * Check if we're in a git repository\n */\n async isGitRepo(): Promise<boolean> {\n try {\n await this.git.revparse(['--git-dir']);\n return true;\n } catch {\n return false;\n }\n }\n}\n","import type { AIConfig, CommitInfo, StagedChanges, GeneratedChangelog, ChangelogSection, ChangeType } from './types.js';\n\nconst OPENROUTER_API_URL = 'https://openrouter.ai/api/v1/chat/completions';\n\nconst SYSTEM_PROMPT = `You are a changelog generator. Your task is to analyze git commits and staged changes to generate changelog entries following the Keep a Changelog format.\n\nOutput Format:\nReturn ONLY a JSON object with the following structure:\n{\n \"sections\": [\n {\n \"type\": \"Added\" | \"Changed\" | \"Deprecated\" | \"Removed\" | \"Fixed\" | \"Security\",\n \"items\": [\"description 1\", \"description 2\"]\n }\n ]\n}\n\nGuidelines:\n- Use present tense (e.g., \"Add feature\" not \"Added feature\")\n- Be concise but descriptive\n- Group related changes together\n- Focus on user-facing changes\n- Ignore merge commits and trivial changes\n- Parse conventional commits (feat:, fix:, etc.) into appropriate sections:\n - feat: -> Added\n - fix: -> Fixed\n - docs:, style:, refactor:, perf:, test:, chore: -> Changed\n - BREAKING CHANGE: -> Changed (mention breaking)\n - deprecate: -> Deprecated\n - remove: -> Removed\n - security: -> Security`;\n\ninterface OpenRouterResponse {\n choices: Array<{\n message: {\n content: string;\n };\n }>;\n}\n\nexport class AIService {\n private config: AIConfig;\n\n constructor(config: AIConfig) {\n this.config = config;\n }\n\n /**\n * Generate changelog entries from commits and staged changes\n */\n async generateChangelog(\n commits: CommitInfo[],\n staged: StagedChanges\n ): Promise<GeneratedChangelog> {\n const userPrompt = this.buildPrompt(commits, staged);\n const response = await this.callOpenRouter(userPrompt);\n return this.parseResponse(response);\n }\n\n private buildPrompt(commits: CommitInfo[], staged: StagedChanges): string {\n const parts: string[] = [];\n\n if (commits.length > 0) {\n parts.push('## Recent Commits:');\n for (const commit of commits.slice(0, 20)) {\n parts.push(`- ${commit.message}`);\n if (commit.body) {\n parts.push(` ${commit.body}`);\n }\n }\n }\n\n if (staged.files.length > 0) {\n parts.push('\\n## Staged Files:');\n parts.push(staged.files.join('\\n'));\n }\n\n if (staged.diff) {\n // Limit diff size to avoid token limits\n const maxDiffLength = 4000;\n const truncatedDiff = staged.diff.length > maxDiffLength\n ? staged.diff.slice(0, maxDiffLength) + '\\n... (truncated)'\n : staged.diff;\n parts.push('\\n## Staged Diff:');\n parts.push('```diff');\n parts.push(truncatedDiff);\n parts.push('```');\n }\n\n parts.push('\\nGenerate changelog entries for these changes.');\n\n return parts.join('\\n');\n }\n\n private async callOpenRouter(prompt: string): Promise<string> {\n const response = await fetch(OPENROUTER_API_URL, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.token}`,\n 'HTTP-Referer': 'https://github.com/testudosrl/tst-libs',\n 'X-Title': 'tst-changelog',\n },\n body: JSON.stringify({\n model: this.config.model,\n messages: [\n { role: 'system', content: SYSTEM_PROMPT },\n { role: 'user', content: prompt },\n ],\n temperature: 0.3,\n max_tokens: 1000,\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`OpenRouter API error: ${response.status} - ${error}`);\n }\n\n const data = (await response.json()) as OpenRouterResponse;\n return data.choices[0]?.message?.content ?? '';\n }\n\n private parseResponse(response: string): GeneratedChangelog {\n try {\n // Extract JSON from response (handle markdown code blocks or raw JSON)\n let jsonStr = response;\n\n // Try markdown code block first\n const codeBlockMatch = response.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n if (codeBlockMatch) {\n jsonStr = codeBlockMatch[1];\n } else {\n // Try to find JSON object in the response\n const jsonObjectMatch = response.match(/\\{[\\s\\S]*\"sections\"[\\s\\S]*\\}/);\n if (jsonObjectMatch) {\n jsonStr = jsonObjectMatch[0];\n }\n }\n\n const parsed = JSON.parse(jsonStr.trim()) as { sections: ChangelogSection[] };\n\n // Validate and normalize sections\n const validTypes: ChangeType[] = ['Added', 'Changed', 'Deprecated', 'Removed', 'Fixed', 'Security'];\n const sections = parsed.sections\n .filter((s) => validTypes.includes(s.type))\n .map((s) => ({\n type: s.type,\n items: Array.isArray(s.items) ? s.items.filter((i) => typeof i === 'string') : [],\n }))\n .filter((s) => s.items.length > 0);\n\n return {\n raw: response,\n sections,\n };\n } catch (error) {\n console.error('Failed to parse AI response:', error);\n console.error('Raw response:', response);\n return {\n raw: response,\n sections: [],\n };\n }\n }\n}\n","import { readFileSync, writeFileSync, existsSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport type { ChangelogConfig, ChangelogSection, GeneratedChangelog } from './types.js';\n\nconst KEEPACHANGELOG_HEADER = `# Changelog\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n`;\n\nconst SECTION_ORDER = ['Added', 'Changed', 'Deprecated', 'Removed', 'Fixed', 'Security'] as const;\n\nexport class ChangelogService {\n private config: ChangelogConfig;\n private filePath: string;\n\n constructor(config: ChangelogConfig, cwd?: string) {\n this.config = config;\n this.filePath = resolve(cwd ?? process.cwd(), config.file);\n }\n\n /**\n * Read existing changelog content\n */\n read(): string | null {\n if (!existsSync(this.filePath)) {\n return null;\n }\n return readFileSync(this.filePath, 'utf-8');\n }\n\n /**\n * Generate new changelog entry\n */\n formatEntry(generated: GeneratedChangelog, version?: string): string {\n const date = this.config.includeDate\n ? new Date().toISOString().split('T')[0]\n : '';\n\n const versionStr = version ?? 'Unreleased';\n const headerLine = date ? `## [${versionStr}] - ${date}` : `## [${versionStr}]`;\n\n const sections = this.sortSections(generated.sections);\n const sectionLines = sections\n .map((section) => this.formatSection(section))\n .join('\\n\\n');\n\n return `${headerLine}\\n\\n${sectionLines}`;\n }\n\n private sortSections(sections: ChangelogSection[]): ChangelogSection[] {\n return [...sections].sort((a, b) => {\n const indexA = SECTION_ORDER.indexOf(a.type as typeof SECTION_ORDER[number]);\n const indexB = SECTION_ORDER.indexOf(b.type as typeof SECTION_ORDER[number]);\n return indexA - indexB;\n });\n }\n\n private formatSection(section: ChangelogSection): string {\n const items = section.items.map((item) => `- ${item}`).join('\\n');\n return `### ${section.type}\\n\\n${items}`;\n }\n\n /**\n * Update or create changelog with new entry\n */\n update(generated: GeneratedChangelog, version?: string): string {\n const newEntry = this.formatEntry(generated, version);\n const existing = this.read();\n\n if (!existing) {\n // Create new changelog\n return KEEPACHANGELOG_HEADER + newEntry + '\\n';\n }\n\n // Find where to insert new entry (after header, before first version)\n const lines = existing.split('\\n');\n let insertIndex = -1;\n\n // Look for ## [Unreleased] or first ## [ section\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n if (line.startsWith('## [Unreleased]')) {\n // Replace unreleased section\n const endIndex = this.findSectionEnd(lines, i + 1);\n const before = lines.slice(0, i).join('\\n');\n const after = lines.slice(endIndex).join('\\n');\n return before + (before.endsWith('\\n') ? '' : '\\n') + newEntry + '\\n\\n' + after;\n }\n if (line.startsWith('## [') && insertIndex === -1) {\n insertIndex = i;\n break;\n }\n }\n\n if (insertIndex === -1) {\n // No version sections found, append after header\n return existing.trimEnd() + '\\n\\n' + newEntry + '\\n';\n }\n\n // Insert before first version\n const before = lines.slice(0, insertIndex).join('\\n');\n const after = lines.slice(insertIndex).join('\\n');\n return before + (before.endsWith('\\n') ? '' : '\\n') + newEntry + '\\n\\n' + after;\n }\n\n private findSectionEnd(lines: string[], startIndex: number): number {\n for (let i = startIndex; i < lines.length; i++) {\n if (lines[i].startsWith('## [')) {\n return i;\n }\n }\n return lines.length;\n }\n\n /**\n * Write changelog to file\n */\n write(content: string): void {\n writeFileSync(this.filePath, content, 'utf-8');\n }\n\n /**\n * Get the file path\n */\n getFilePath(): string {\n return this.filePath;\n }\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;;;ACAxB,SAAS,cAAc,kBAAkB;AACzC,SAAS,eAAe;AACxB,SAAS,aAAa;AAGtB,IAAM,iBAAyB;AAAA,EAC7B,IAAI;AAAA,IACF,UAAU;AAAA,IACV,OAAO;AAAA,IACP,OAAO;AAAA,EACT;AAAA,EACA,WAAW;AAAA,IACT,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,aAAa;AAAA,IACb,SAAS;AAAA,EACX;AAAA,EACA,KAAK;AAAA,IACH,YAAY;AAAA,IACZ,cAAc;AAAA,EAChB;AACF;AAMA,SAAS,eAAe,OAAuB;AAC7C,SAAO,MAAM,QAAQ,kBAAkB,CAAC,GAAG,WAAW;AACpD,UAAM,WAAW,QAAQ,IAAI,MAAM;AACnC,QAAI,CAAC,UAAU;AACb,YAAM,IAAI,MAAM,wBAAwB,MAAM,aAAa;AAAA,IAC7D;AACA,WAAO;AAAA,EACT,CAAC;AACH;AAKA,SAAS,qBAAwB,KAAW;AAC1C,MAAI,OAAO,QAAQ,UAAU;AAC3B,WAAO,eAAe,GAAG;AAAA,EAC3B;AACA,MAAI,MAAM,QAAQ,GAAG,GAAG;AACtB,WAAO,IAAI,IAAI,oBAAoB;AAAA,EACrC;AACA,MAAI,OAAO,OAAO,QAAQ,UAAU;AAClC,UAAM,WAAoC,CAAC;AAC3C,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,GAAG,GAAG;AAC9C,eAAS,GAAG,IAAI,qBAAqB,KAAK;AAAA,IAC5C;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAKA,SAA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G;AAC1D,cAAQ,KAAK,CAAC;AAAA,IAChB;AAEA,QAAI,SAAS;AACX,cAAQ,IAAI,qBAAqB;AACjC,iBAAW,WAAW,UAAU,UAAU;AACxC,gBAAQ,IAAI,KAAK,QAAQ,IAAI,GAAG;AAChC,mBAAW,QAAQ,QAAQ,OAAO;AAChC,kBAAQ,IAAI,SAAS,IAAI,EAAE;AAAA,QAC7B;AAAA,MACF;AAAA,IACF;AAGA,UAAM,aAAa,UAAU,OAAO,SAAS;AAE7C,QAAI,QAAQ,QAAQ;AAClB,cAAQ,IAAI,mBAAmB;AAC/B,cAAQ,IAAI,8BAA8B,UAAU,YAAY,CAAC;AACjE,cAAQ,IAAI,qBAAqB;AACjC,cAAQ,IAAI,UAAU,YAAY,SAAS,CAAC;AAC5C,cAAQ,IAAI,eAAe;AAC3B,cAAQ,KAAK,CAAC;AAAA,IAChB;AAGA,cAAU,MAAM,UAAU;AAC1B,YAAQ,IAAI,YAAY,UAAU,YAAY,CAAC,EAAE;AAEjD,UAAM,IAAI,UAAU,OAAO,UAAU,IAAI;AACzC,YAAQ,IAAI,uBAAuB;AAEnC,YAAQ,IAAI,OAAO;AAAA,EACrB,SAAS,OAAO;AACd,YAAQ,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,KAAK;AACtE,QAAI,WAAW,iBAAiB,OAAO;AACrC,cAAQ,MAAM,MAAM,KAAK;AAAA,IAC3B;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;AAEA,QAAQ,MAAM;","names":["readFileSync","existsSync","resolve","before","after"]}
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "tst-changelog",
3
+ "version": "0.1.0",
4
+ "description": "AI-powered changelog generator using OpenRouter",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "bin": {
9
+ "tst-changelog": "./dist/index.js"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "import": "./dist/index.js",
14
+ "types": "./dist/index.d.ts"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "dependencies": {
21
+ "yaml": "^2.7.0",
22
+ "simple-git": "^3.27.0",
23
+ "commander": "^12.1.0"
24
+ },
25
+ "devDependencies": {
26
+ "typescript": "^5.7.3",
27
+ "tsup": "^8.3.5",
28
+ "@types/node": "^20.17.14"
29
+ },
30
+ "keywords": [
31
+ "changelog",
32
+ "ai",
33
+ "openrouter",
34
+ "git"
35
+ ],
36
+ "author": "Testudo SRL",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "https://github.com/TestudoSrl/tst-libs.git",
40
+ "directory": "packages/tst-changelog"
41
+ },
42
+ "homepage": "https://github.com/TestudoSrl/tst-libs/tree/main/packages/tst-changelog",
43
+ "bugs": {
44
+ "url": "https://github.com/TestudoSrl/tst-libs/issues"
45
+ },
46
+ "license": "MIT",
47
+ "scripts": {
48
+ "build": "tsup",
49
+ "dev": "tsup --watch",
50
+ "clean": "rm -rf dist",
51
+ "typecheck": "tsc --noEmit"
52
+ }
53
+ }