@mcarvin/smart-diff 1.0.4 → 1.0.5

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.mjs CHANGED
@@ -35,7 +35,7 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
35
35
 
36
36
  function resolveLlmBaseUrl() {
37
37
  var _a, _b, _c;
38
- return (_b = (_a = process.env.LLM_BASE_URL) === null || _a === void 0 ? void 0 : _a.trim()) !== null && _b !== void 0 ? _b : (_c = process.env.OPENAI_BASE_URL) === null || _c === void 0 ? void 0 : _c.trim();
38
+ return ((_b = (_a = process.env.LLM_BASE_URL) === null || _a === void 0 ? void 0 : _a.trim()) !== null && _b !== void 0 ? _b : (_c = process.env.OPENAI_BASE_URL) === null || _c === void 0 ? void 0 : _c.trim());
39
39
  }
40
40
  function parseHeaderJsonObject(raw) {
41
41
  const trimmed = raw === null || raw === void 0 ? void 0 : raw.trim();
@@ -43,12 +43,14 @@ function parseHeaderJsonObject(raw) {
43
43
  return {};
44
44
  try {
45
45
  const parsed = JSON.parse(trimmed);
46
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
46
+ if (typeof parsed !== "object" ||
47
+ parsed === null ||
48
+ Array.isArray(parsed)) {
47
49
  return {};
48
50
  }
49
51
  const out = {};
50
52
  for (const [key, value] of Object.entries(parsed)) {
51
- if (typeof value === 'string' && value.length > 0) {
53
+ if (typeof value === "string" && value.length > 0) {
52
54
  out[key] = value;
53
55
  }
54
56
  }
@@ -65,7 +67,7 @@ function parseLlmDefaultHeadersFromEnv() {
65
67
  return Object.keys(merged).length > 0 ? merged : undefined;
66
68
  }
67
69
  function findAuthorizationHeaderName(headers) {
68
- return Object.keys(headers).find((k) => k.toLowerCase() === 'authorization');
70
+ return Object.keys(headers).find((k) => k.toLowerCase() === "authorization");
69
71
  }
70
72
  function stripBearerPrefix(value) {
71
73
  var _a;
@@ -108,7 +110,7 @@ function resolveOpenAiLikeClientInit() {
108
110
  var _a, _b, _c, _d, _e;
109
111
  const baseURL = resolveLlmBaseUrl();
110
112
  const mergedHeaders = (_a = parseLlmDefaultHeadersFromEnv()) !== null && _a !== void 0 ? _a : {};
111
- const envApiKey = (_e = (_c = (_b = process.env.LLM_API_KEY) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : (_d = process.env.OPENAI_API_KEY) === null || _d === void 0 ? void 0 : _d.trim()) !== null && _e !== void 0 ? _e : '';
113
+ const envApiKey = (_e = (_c = (_b = process.env.LLM_API_KEY) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : (_d = process.env.OPENAI_API_KEY) === null || _d === void 0 ? void 0 : _d.trim()) !== null && _e !== void 0 ? _e : "";
112
114
  let defaultHeaders;
113
115
  let apiKey = envApiKey;
114
116
  if (apiKey.length === 0) {
@@ -116,12 +118,16 @@ function resolveOpenAiLikeClientInit() {
116
118
  if (split.apiKeyFromAuthHeader) {
117
119
  apiKey = split.apiKeyFromAuthHeader;
118
120
  }
119
- defaultHeaders = Object.keys(split.defaultHeaders).length > 0 ? split.defaultHeaders : undefined;
121
+ defaultHeaders =
122
+ Object.keys(split.defaultHeaders).length > 0
123
+ ? split.defaultHeaders
124
+ : undefined;
120
125
  }
121
126
  else {
122
- defaultHeaders = Object.keys(mergedHeaders).length > 0 ? mergedHeaders : undefined;
127
+ defaultHeaders =
128
+ Object.keys(mergedHeaders).length > 0 ? mergedHeaders : undefined;
123
129
  }
124
- return Object.assign(Object.assign({ apiKey: apiKey.length > 0 ? apiKey : 'unused' }, (baseURL ? { baseURL } : {})), (defaultHeaders ? { defaultHeaders } : {}));
130
+ return Object.assign(Object.assign({ apiKey: apiKey.length > 0 ? apiKey : "unused" }, (baseURL ? { baseURL } : {})), (defaultHeaders ? { defaultHeaders } : {}));
125
131
  }
126
132
  function createOpenAiLikeClient() {
127
133
  return __awaiter(this, void 0, void 0, function* () {
@@ -131,9 +137,22 @@ function createOpenAiLikeClient() {
131
137
  }
132
138
 
133
139
  const DEFAULT_LLM_MAX_DIFF_CHARS = 120000;
140
+ const DEFAULT_GIT_DIFF_SYSTEM_PROMPT = `You are a senior software engineer helping developers understand code and configuration changes from the git context they supplied.
141
+ You receive: commit subject lines (when available), changed file paths, and unified git patch(es)—either one range diff or concatenated per-commit patches, depending on how the diff was produced. Patches may be truncated mid-section with an explicit marker—do not infer changes beyond visible lines.
142
+ Explain what changed in terms of behavior, APIs, data, configuration, security, and operational risk. Tie claims to the patch when possible.
143
+ Produce a concise, developer-focused summary in Markdown.
144
+ Use sections that fit the change (for example: Highlights, Breaking or risky changes, API / contract changes, Data & schema, Configuration & infra, Security & auth, Tests & quality). Omit empty sections.
145
+ Group related changes; do not list every individual file. When multiple commits appear in the context, briefly separate notable themes by commit when helpful.
146
+ If the user message includes a Team line, use that exact team name in the summary title (for example: "## <Team> – Change summary" or similar).`;
147
+ const LLM_GATEWAY_REQUIRED_MESSAGE = "No LLM gateway configured. Set OPENAI_API_KEY or LLM_API_KEY, and/or LLM_BASE_URL or OPENAI_BASE_URL, " +
148
+ "and/or JSON in OPENAI_DEFAULT_HEADERS or LLM_DEFAULT_HEADERS. " +
149
+ "Alternatively pass openAiClientProvider to generateSummary or summarizeGitDiff.";
150
+
134
151
  function resolveLlmMaxDiffChars(cliOverride) {
135
152
  var _a;
136
- if (cliOverride !== undefined && Number.isFinite(cliOverride) && cliOverride > 0) {
153
+ if (cliOverride !== undefined &&
154
+ Number.isFinite(cliOverride) &&
155
+ cliOverride > 0) {
137
156
  return Math.trunc(cliOverride);
138
157
  }
139
158
  const raw = (_a = process.env.LLM_MAX_DIFF_CHARS) === null || _a === void 0 ? void 0 : _a.trim();
@@ -152,70 +171,67 @@ function truncateUnifiedDiffForLlm(diffText, maxChars) {
152
171
  const marker = `\n\n--- TRUNCATED: unified diff was ${diffText.length} characters; only the first ${maxChars} were sent. Narrow the ref range, adjust commit/path filters, or raise maxDiffChars / LLM_MAX_DIFF_CHARS only if your model context allows. ---\n`;
153
172
  return diffText.slice(0, maxChars) + marker;
154
173
  }
155
- const DEFAULT_GIT_DIFF_SYSTEM_PROMPT = `You are a senior software engineer helping developers understand code and configuration changes from the git context they supplied.
156
- You receive: commit subject lines (when available), changed file paths, and unified git patch(es)—either one range diff or concatenated per-commit patches, depending on how the diff was produced. Patches may be truncated mid-section with an explicit marker—do not infer changes beyond visible lines.
157
- Explain what changed in terms of behavior, APIs, data, configuration, security, and operational risk. Tie claims to the patch when possible.
158
- Produce a concise, developer-focused summary in Markdown.
159
- Use sections that fit the change (for example: Highlights, Breaking or risky changes, API / contract changes, Data & schema, Configuration & infra, Security & auth, Tests & quality). Omit empty sections.
160
- Group related changes; do not list every individual file. When multiple commits appear in the context, briefly separate notable themes by commit when helpful.
161
- If the user message includes a Team line, use that exact team name in the summary title (for example: "## <Team> – Change summary" or similar).`;
162
- const LLM_GATEWAY_REQUIRED_MESSAGE = 'No LLM gateway configured. Set OPENAI_API_KEY or LLM_API_KEY, and/or LLM_BASE_URL or OPENAI_BASE_URL, ' +
163
- 'and/or JSON in OPENAI_DEFAULT_HEADERS or LLM_DEFAULT_HEADERS. ' +
164
- 'Alternatively pass openAiClientProvider to generateSummary or summarizeGitDiff.';
165
- function generateSummary(diffText, fileNames, commits, flags, openAiClientProvider, diffSummary) {
174
+ function generateSummary(input) {
166
175
  return __awaiter(this, void 0, void 0, function* () {
167
176
  var _a, _b;
177
+ const { diffText, fileNames, commits, flags, openAiClientProvider, diffSummary, } = input;
168
178
  if (!shouldUseLlmGateway() && openAiClientProvider === undefined) {
169
179
  throw new Error(LLM_GATEWAY_REQUIRED_MESSAGE);
170
180
  }
171
181
  const maxDiffChars = resolveLlmMaxDiffChars(flags.maxDiffChars);
172
182
  const diffForLlm = truncateUnifiedDiffForLlm(diffText, maxDiffChars);
173
183
  const userContent = buildOpenAiUserContent(flags, commits, fileNames, diffForLlm, diffSummary);
174
- return callOpenAi(userContent, (_a = flags.model) !== null && _a !== void 0 ? _a : 'gpt-4o-mini', (_b = flags.systemPrompt) !== null && _b !== void 0 ? _b : DEFAULT_GIT_DIFF_SYSTEM_PROMPT, openAiClientProvider !== null && openAiClientProvider !== void 0 ? openAiClientProvider : (() => __awaiter(this, void 0, void 0, function* () { return createOpenAiLikeClient(); })));
184
+ return callOpenAi(userContent, (_a = flags.model) !== null && _a !== void 0 ? _a : "gpt-4o-mini", (_b = flags.systemPrompt) !== null && _b !== void 0 ? _b : DEFAULT_GIT_DIFF_SYSTEM_PROMPT, openAiClientProvider !== null && openAiClientProvider !== void 0 ? openAiClientProvider : (() => __awaiter(this, void 0, void 0, function* () { return createOpenAiLikeClient(); })));
175
185
  });
176
186
  }
177
187
  function formatRegexFilterLines(flags) {
178
188
  var _a, _b;
179
- const includes = ((_a = flags.commitMessageIncludeRegexes) !== null && _a !== void 0 ? _a : []).map((s) => s.trim()).filter(Boolean);
180
- const excludes = ((_b = flags.commitMessageExcludeRegexes) !== null && _b !== void 0 ? _b : []).map((s) => s.trim()).filter(Boolean);
189
+ const includes = ((_a = flags.commitMessageIncludeRegexes) !== null && _a !== void 0 ? _a : [])
190
+ .map((s) => s.trim())
191
+ .filter(Boolean);
192
+ const excludes = ((_b = flags.commitMessageExcludeRegexes) !== null && _b !== void 0 ? _b : [])
193
+ .map((s) => s.trim())
194
+ .filter(Boolean);
181
195
  const incLine = includes.length > 0
182
- ? `Commit message include regexes (OR): ${includes.map((r) => JSON.stringify(r)).join(', ')}\n`
183
- : '';
196
+ ? `Commit message include regexes (OR): ${includes.map((r) => JSON.stringify(r)).join(", ")}\n`
197
+ : "";
184
198
  const excLine = excludes.length > 0
185
- ? `Commit message exclude regexes: ${excludes.map((r) => JSON.stringify(r)).join(', ')}\n`
186
- : '';
199
+ ? `Commit message exclude regexes: ${excludes.map((r) => JSON.stringify(r)).join(", ")}\n`
200
+ : "";
187
201
  if (!incLine && !excLine) {
188
- return 'Commit message filters: none.\nGit context shape: single unified diff for the full ref range.\n';
202
+ return "Commit message filters: none.\nGit context shape: single unified diff for the full ref range.\n";
189
203
  }
190
204
  return (`${incLine}${excLine}` +
191
- 'Git context shape: concatenated per-commit unified patches for commits that pass the message filters.\n');
205
+ "Git context shape: concatenated per-commit unified patches for commits that pass the message filters.\n");
192
206
  }
193
207
  function buildOpenAiUserContent(flags, commits, fileNames, diffText, diffSummary) {
194
208
  var _a, _b;
195
209
  const from = flags.from;
196
- const to = (_a = flags.to) !== null && _a !== void 0 ? _a : 'HEAD';
210
+ const to = (_a = flags.to) !== null && _a !== void 0 ? _a : "HEAD";
197
211
  const team = (_b = flags.team) === null || _b === void 0 ? void 0 : _b.trim();
198
212
  const ts = new Date().toISOString();
199
- const teamLine = team ? `Team: ${team}\n` : '';
213
+ const teamLine = team ? `Team: ${team}\n` : "";
200
214
  const filterBlock = formatRegexFilterLines(flags);
201
215
  const commitBlock = commits.length > 0
202
- ? commits.map((c) => `- ${c.hash.slice(0, 7)} ${c.message.replace(/\r?\n/g, ' ')}`).join('\n')
203
- : '- (no commits in range after filtering)';
204
- const pathsBlock = fileNames.length > 0 ? fileNames.join('\n') : '(no paths in diff scope)';
216
+ ? commits
217
+ .map((c) => `- ${c.hash.slice(0, 7)} ${c.message.replace(/\r?\n/g, " ")}`)
218
+ .join("\n")
219
+ : "- (no commits in range after filtering)";
220
+ const pathsBlock = fileNames.length > 0 ? fileNames.join("\n") : "(no paths in diff scope)";
205
221
  const structuredDiffSection = diffSummary
206
222
  ? `=== Structured git context (JSON summary) ===\n${JSON.stringify(diffSummary, null, 2)}\n\n`
207
- : '';
223
+ : "";
208
224
  return (`${teamLine}` +
209
225
  `Date: ${ts}\n\n` +
210
226
  `Git refs: ${from}..${to}\n` +
211
227
  filterBlock +
212
- '\n' +
213
- '=== Included commits (subject lines) ===\n' +
228
+ "\n" +
229
+ "=== Included commits (subject lines) ===\n" +
214
230
  `${commitBlock}\n\n` +
215
- '=== Changed paths ===\n' +
231
+ "=== Changed paths ===\n" +
216
232
  `${pathsBlock}\n\n` +
217
233
  structuredDiffSection +
218
- '=== Git context (unified diff(s); patches may be truncated with an explicit marker) ===\n' +
234
+ "=== Git context (unified diff(s); patches may be truncated with an explicit marker) ===\n" +
219
235
  diffText);
220
236
  }
221
237
  function callOpenAi(userContent, model, systemPrompt, openAiClientProvider) {
@@ -229,11 +245,11 @@ function callOpenAi(userContent, model, systemPrompt, openAiClientProvider) {
229
245
  model,
230
246
  messages: [
231
247
  {
232
- role: 'system',
248
+ role: "system",
233
249
  content: systemPrompt,
234
250
  },
235
251
  {
236
- role: 'user',
252
+ role: "user",
237
253
  content: userContent,
238
254
  },
239
255
  ],
@@ -241,64 +257,25 @@ function callOpenAi(userContent, model, systemPrompt, openAiClientProvider) {
241
257
  max_tokens: maxTokens,
242
258
  });
243
259
  const typedResponse = response;
244
- const text = (_f = (_e = (_d = (_c = (_b = typedResponse.choices) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.message) === null || _d === void 0 ? void 0 : _d.content) === null || _e === void 0 ? void 0 : _e.trim()) !== null && _f !== void 0 ? _f : '';
245
- return text.length > 0 ? text : 'No summary generated by OpenAI.';
260
+ const text = (_f = (_e = (_d = (_c = (_b = typedResponse.choices) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.message) === null || _d === void 0 ? void 0 : _d.content) === null || _e === void 0 ? void 0 : _e.trim()) !== null && _f !== void 0 ? _f : "";
261
+ return text.length > 0 ? text : "No summary generated by OpenAI.";
246
262
  });
247
263
  }
248
264
 
249
- function createGitClient(cwd = process.cwd()) {
250
- return simpleGit(cwd);
251
- }
252
- function getCommits(git, from, to) {
253
- return __awaiter(this, void 0, void 0, function* () {
254
- const logResult = yield git.log({ from, to });
255
- return logResult.all;
256
- });
257
- }
258
- function compileRegex(pattern, label) {
259
- try {
260
- return new RegExp(pattern, 'i');
261
- }
262
- catch (_a) {
263
- throw new Error(`Invalid ${label} regular expression: ${JSON.stringify(pattern)}`);
264
- }
265
- }
266
- function commitMessagePassesFilters(message, includeRes, excludeRes) {
267
- for (const ex of excludeRes) {
268
- if (ex.test(message))
269
- return false;
270
- }
271
- if (includeRes.length > 0 && !includeRes.some((r) => r.test(message)))
272
- return false;
273
- return true;
274
- }
275
- function filterCommitsByMessageRegexes(commits, includePatterns, excludePatterns) {
276
- const includes = (includePatterns !== null && includePatterns !== void 0 ? includePatterns : []).map((p) => p.trim()).filter((p) => p.length > 0);
277
- const excludes = (excludePatterns !== null && excludePatterns !== void 0 ? excludePatterns : []).map((p) => p.trim()).filter((p) => p.length > 0);
278
- const includeRes = includes.map((p, i) => compileRegex(p, `commit message include pattern[${i}]`));
279
- const excludeRes = excludes.map((p, i) => compileRegex(p, `commit message exclude pattern[${i}]`));
280
- return commits.filter((c) => commitMessagePassesFilters(c.message, includeRes, excludeRes));
281
- }
282
- function getRepoRoot(git) {
283
- return __awaiter(this, void 0, void 0, function* () {
284
- const root = yield git.revparse(['--show-toplevel']);
285
- return root.trim();
286
- });
287
- }
288
265
  function normalizeRepoRelativePath(p) {
289
- const trimmed = p.trim().replace(/\\/g, '/');
290
- const noLeading = trimmed.replace(/^\/+/, '');
291
- const noTrailingSlash = noLeading.replace(/\/+$/, '');
292
- return noTrailingSlash.length > 0 ? noTrailingSlash : '.';
266
+ const trimmed = p.trim().replace(/\\/g, "/");
267
+ const noLeading = trimmed.replace(/^\/+/, "");
268
+ const noTrailingSlash = noLeading.replace(/\/+$/, "");
269
+ return noTrailingSlash.length > 0 ? noTrailingSlash : ".";
293
270
  }
294
271
  function assertPathUnderRepo(repoRoot, userPath) {
295
272
  const abs = resolve(repoRoot, userPath);
296
273
  const rel = relative(repoRoot, abs);
297
- if (rel === '..') {
274
+ if (rel === "..") {
298
275
  throw new Error(`Path escapes repository root: ${JSON.stringify(userPath)}`);
299
276
  }
300
277
  const segments = rel.split(/[/\\]/);
301
- if (segments.includes('..')) {
278
+ if (segments.includes("..")) {
302
279
  throw new Error(`Path escapes repository root: ${JSON.stringify(userPath)}`);
303
280
  }
304
281
  }
@@ -306,9 +283,13 @@ function buildDiffPathspecs(repoRoot, pathFilter) {
306
283
  var _a, _b, _c, _d;
307
284
  const includeRaw = (_b = (_a = pathFilter === null || pathFilter === void 0 ? void 0 : pathFilter.includeFolders) === null || _a === void 0 ? void 0 : _a.filter((p) => p.trim().length > 0)) !== null && _b !== void 0 ? _b : [];
308
285
  const excludeRaw = (_d = (_c = pathFilter === null || pathFilter === void 0 ? void 0 : pathFilter.excludeFolders) === null || _c === void 0 ? void 0 : _c.filter((p) => p.trim().length > 0)) !== null && _d !== void 0 ? _d : [];
309
- const includes = includeRaw.map(normalizeRepoRelativePath).filter((p) => p !== '.' && p !== '');
310
- const excludes = excludeRaw.map(normalizeRepoRelativePath).filter((p) => p !== '.' && p !== '');
311
- const toValidate = includes.length > 0 ? includes : ['.'];
286
+ const includes = includeRaw
287
+ .map(normalizeRepoRelativePath)
288
+ .filter((p) => p !== "." && p !== "");
289
+ const excludes = excludeRaw
290
+ .map(normalizeRepoRelativePath)
291
+ .filter((p) => p !== "." && p !== "");
292
+ const toValidate = includes.length > 0 ? includes : ["."];
312
293
  for (const inc of toValidate) {
313
294
  assertPathUnderRepo(repoRoot, inc);
314
295
  }
@@ -317,7 +298,7 @@ function buildDiffPathspecs(repoRoot, pathFilter) {
317
298
  }
318
299
  const specs = [];
319
300
  if (includes.length === 0) {
320
- specs.push('.');
301
+ specs.push(".");
321
302
  }
322
303
  else {
323
304
  for (const inc of includes) {
@@ -329,100 +310,73 @@ function buildDiffPathspecs(repoRoot, pathFilter) {
329
310
  }
330
311
  return specs;
331
312
  }
332
- function getDiffPathContext(git, pathFilter, repoRootOverride) {
333
- return __awaiter(this, void 0, void 0, function* () {
334
- const repoRoot = repoRootOverride !== null && repoRootOverride !== void 0 ? repoRootOverride : (yield getRepoRoot(git));
335
- const specs = buildDiffPathspecs(repoRoot, pathFilter);
336
- return { repoRoot, specs };
337
- });
338
- }
339
- function getDiff(git, from, to, commits, filterByCommits, pathFilter, repoRootOverride) {
340
- return __awaiter(this, void 0, void 0, function* () {
341
- const { specs } = yield getDiffPathContext(git, pathFilter, repoRootOverride);
342
- if (!filterByCommits) {
343
- return git.diff([`${from}..${to}`, '--', ...specs]);
344
- }
345
- const patches = yield Promise.all(commits.map((c) => git.diff([`${c.hash}^!`, '--', ...specs])));
346
- return patches.filter(Boolean).join('\n');
347
- });
313
+
314
+ function compileRegex(pattern, label) {
315
+ try {
316
+ return new RegExp(pattern, "i");
317
+ }
318
+ catch (_a) {
319
+ throw new Error(`Invalid ${label} regular expression: ${JSON.stringify(pattern)}`);
320
+ }
348
321
  }
349
- function getDiffSummary(git, from, to, commits, filterByCommits, pathFilter, repoRootOverride) {
350
- return __awaiter(this, void 0, void 0, function* () {
351
- const { specs } = yield getDiffPathContext(git, pathFilter, repoRootOverride);
352
- if (!filterByCommits) {
353
- const [numOutput, nameOutput] = yield Promise.all([
354
- git.diff(['--numstat', `${from}..${to}`, '--', ...specs]),
355
- git.diff(['--name-status', `${from}..${to}`, '--', ...specs]),
356
- ]);
357
- return buildDiffSummaryFromGitOutputs(nameOutput, numOutput);
358
- }
359
- const pairs = yield Promise.all(commits.map((c) => __awaiter(this, void 0, void 0, function* () {
360
- const range = `${c.hash}^!`;
361
- const [numOutput, nameOutput] = yield Promise.all([
362
- git.diff(['--numstat', range, '--', ...specs]),
363
- git.diff(['--name-status', range, '--', ...specs]),
364
- ]);
365
- return { numOutput, nameOutput };
366
- })));
367
- const nameJoined = pairs
368
- .map((p) => p.nameOutput)
369
- .filter(Boolean)
370
- .join('\n');
371
- const numJoined = pairs
372
- .map((p) => p.numOutput)
373
- .filter(Boolean)
374
- .join('\n');
375
- return buildDiffSummaryFromGitOutputs(nameJoined, numJoined);
376
- });
322
+ function commitMessagePassesFilters(message, includeRes, excludeRes) {
323
+ for (const ex of excludeRes) {
324
+ if (ex.test(message))
325
+ return false;
326
+ }
327
+ if (includeRes.length > 0 && !includeRes.some((r) => r.test(message)))
328
+ return false;
329
+ return true;
377
330
  }
378
- function getChangedFiles(git, from, to, commits, filterByCommits, pathFilter, repoRootOverride) {
379
- return __awaiter(this, void 0, void 0, function* () {
380
- const { specs } = yield getDiffPathContext(git, pathFilter, repoRootOverride);
381
- if (!filterByCommits) {
382
- const output = yield git.diff(['--name-only', `${from}..${to}`, '--', ...specs]);
383
- return output
384
- .split(/\r?\n/)
385
- .map((f) => f.trim())
386
- .filter(Boolean);
387
- }
388
- const fileSet = new Set();
389
- yield Promise.all(commits.map((c) => __awaiter(this, void 0, void 0, function* () {
390
- const output = yield git.show(['--name-only', '--pretty=format:', c.hash, '--', ...specs]);
391
- output
392
- .split(/\r?\n/)
393
- .map((f) => f.trim())
394
- .filter(Boolean)
395
- .forEach((f) => fileSet.add(f));
396
- })));
397
- return Array.from(fileSet);
398
- });
331
+ function filterCommitsByMessageRegexes(commits, includePatterns, excludePatterns) {
332
+ const includes = (includePatterns !== null && includePatterns !== void 0 ? includePatterns : [])
333
+ .map((p) => p.trim())
334
+ .filter((p) => p.length > 0);
335
+ const excludes = (excludePatterns !== null && excludePatterns !== void 0 ? excludePatterns : [])
336
+ .map((p) => p.trim())
337
+ .filter((p) => p.length > 0);
338
+ const includeRes = includes.map((p, i) => compileRegex(p, `commit message include pattern[${i}]`));
339
+ const excludeRes = excludes.map((p, i) => compileRegex(p, `commit message exclude pattern[${i}]`));
340
+ return commits.filter((c) => commitMessagePassesFilters(c.message, includeRes, excludeRes));
399
341
  }
342
+
400
343
  const GIT_STATUS_BY_FIRST_CHAR = {
401
- A: 'added',
402
- D: 'deleted',
403
- R: 'renamed',
404
- C: 'copied',
405
- T: 'type-changed',
406
- M: 'modified',
344
+ A: "added",
345
+ D: "deleted",
346
+ R: "renamed",
347
+ C: "copied",
348
+ T: "type-changed",
349
+ M: "modified",
407
350
  };
408
351
  function mapGitStatus(statusCode) {
409
352
  var _a;
410
- return (_a = GIT_STATUS_BY_FIRST_CHAR[statusCode.charAt(0)]) !== null && _a !== void 0 ? _a : 'unknown';
353
+ return (_a = GIT_STATUS_BY_FIRST_CHAR[statusCode.charAt(0)]) !== null && _a !== void 0 ? _a : "unknown";
411
354
  }
412
355
  function mergeStatus(existing, next) {
413
356
  if (existing === next)
414
357
  return existing;
415
- const precedence = ['deleted', 'added', 'renamed', 'copied', 'type-changed', 'modified', 'unknown'];
416
- return precedence.indexOf(existing) <= precedence.indexOf(next) ? existing : next;
358
+ const precedence = [
359
+ "deleted",
360
+ "added",
361
+ "renamed",
362
+ "copied",
363
+ "type-changed",
364
+ "modified",
365
+ "unknown",
366
+ ];
367
+ return precedence.indexOf(existing) <= precedence.indexOf(next)
368
+ ? existing
369
+ : next;
417
370
  }
371
+
418
372
  function parseNameStatusLine(line) {
419
373
  var _a;
420
- const parts = line.split('\t');
374
+ const parts = line.split("\t");
421
375
  let entry = null;
422
376
  if (parts.length >= 2) {
423
- const statusToken = (_a = parts[0]) !== null && _a !== void 0 ? _a : '';
377
+ const statusToken = (_a = parts[0]) !== null && _a !== void 0 ? _a : "";
424
378
  const status = mapGitStatus(statusToken);
425
- const isRenameOrCopy = statusToken.startsWith('R') || statusToken.startsWith('C');
379
+ const isRenameOrCopy = statusToken.startsWith("R") || statusToken.startsWith("C");
426
380
  if (isRenameOrCopy && parts.length >= 3) {
427
381
  const oldPath = parts[1];
428
382
  const newPath = parts[2];
@@ -468,6 +422,7 @@ function mergeNameEntriesByPath(entries) {
468
422
  }
469
423
  return byPath;
470
424
  }
425
+
471
426
  function numStatPathToLookupKey(pathField) {
472
427
  const brace = /^(.*)\{(.+) => (.+)\}$/.exec(pathField);
473
428
  if (!brace) {
@@ -479,14 +434,14 @@ function numStatPathToLookupKey(pathField) {
479
434
  }
480
435
  function parseNumStatLine(line) {
481
436
  var _a, _b;
482
- const parts = line.split('\t');
437
+ const parts = line.split("\t");
483
438
  if (parts.length < 3)
484
439
  return null;
485
- const addStr = (_a = parts[0]) !== null && _a !== void 0 ? _a : '';
486
- const delStr = (_b = parts[1]) !== null && _b !== void 0 ? _b : '';
487
- const pathField = parts.slice(2).join('\t');
488
- const additions = addStr !== '-' ? Number.parseInt(addStr, 10) || 0 : 0;
489
- const deletions = delStr !== '-' ? Number.parseInt(delStr, 10) || 0 : 0;
440
+ const addStr = (_a = parts[0]) !== null && _a !== void 0 ? _a : "";
441
+ const delStr = (_b = parts[1]) !== null && _b !== void 0 ? _b : "";
442
+ const pathField = parts.slice(2).join("\t");
443
+ const additions = addStr !== "-" ? Number.parseInt(addStr, 10) || 0 : 0;
444
+ const deletions = delStr !== "-" ? Number.parseInt(delStr, 10) || 0 : 0;
490
445
  const key = numStatPathToLookupKey(pathField);
491
446
  return { key, additions, deletions };
492
447
  }
@@ -500,56 +455,35 @@ function accumulateNumStat(numStatOutput, into) {
500
455
  if (!parsed)
501
456
  continue;
502
457
  const prev = (_a = into.get(parsed.key)) !== null && _a !== void 0 ? _a : { additions: 0, deletions: 0 };
503
- into.set(parsed.key, { additions: prev.additions + parsed.additions, deletions: prev.deletions + parsed.deletions });
504
- }
505
- }
506
- const STATUS_TO_SYNTHETIC_PREFIX = {
507
- added: 'A',
508
- deleted: 'D',
509
- renamed: 'R100',
510
- copied: 'C100',
511
- 'type-changed': 'T',
512
- modified: 'M',
513
- unknown: 'X',
514
- };
515
- function diffStatusToSyntheticPrefix(status) {
516
- return STATUS_TO_SYNTHETIC_PREFIX[status];
517
- }
518
- function buildSyntheticDiffLine(meta, counts) {
519
- const prefix = diffStatusToSyntheticPrefix(meta.status);
520
- if (meta.oldPath) {
521
- return `${prefix}\t${counts.additions}\t${counts.deletions}\t${meta.oldPath}\t${meta.path}`;
522
- }
523
- return `${prefix}\t${counts.additions}\t${counts.deletions}\t${meta.path}`;
524
- }
525
- function buildDiffSummaryFromGitOutputs(nameStatusOutput, numStatOutput) {
526
- var _a;
527
- const numMap = new Map();
528
- accumulateNumStat(numStatOutput, numMap);
529
- const mergedName = mergeNameEntriesByPath(parseNameStatusLines(nameStatusOutput));
530
- const syntheticLines = [];
531
- for (const [path, meta] of mergedName) {
532
- const counts = (_a = numMap.get(path)) !== null && _a !== void 0 ? _a : { additions: 0, deletions: 0 };
533
- syntheticLines.push(buildSyntheticDiffLine(meta, counts));
458
+ into.set(parsed.key, {
459
+ additions: prev.additions + parsed.additions,
460
+ deletions: prev.deletions + parsed.deletions,
461
+ });
534
462
  }
535
- return parseDiffSummary(syntheticLines.join('\n'));
536
463
  }
464
+
537
465
  function parseTabDiffSummaryLine(line) {
538
466
  var _a;
539
- const parts = line.split('\t');
467
+ const parts = line.split("\t");
540
468
  if (parts.length < 3)
541
469
  return null;
542
- const statusToken = (_a = parts.shift()) !== null && _a !== void 0 ? _a : '';
470
+ const statusToken = (_a = parts.shift()) !== null && _a !== void 0 ? _a : "";
543
471
  const status = mapGitStatus(statusToken);
544
472
  const add0 = parts[0];
545
473
  const del0 = parts[1];
546
- const additions = add0 && add0 !== '-' ? Number.parseInt(add0, 10) || 0 : 0;
547
- const deletions = del0 && del0 !== '-' ? Number.parseInt(del0, 10) || 0 : 0;
474
+ const additions = add0 && add0 !== "-" ? Number.parseInt(add0, 10) || 0 : 0;
475
+ const deletions = del0 && del0 !== "-" ? Number.parseInt(del0, 10) || 0 : 0;
548
476
  if (parts.length === 3) {
549
477
  return { status, additions, deletions, newPath: parts[2] };
550
478
  }
551
479
  if (parts.length === 4) {
552
- return { status, additions, deletions, oldPath: parts[2], newPath: parts[3] };
480
+ return {
481
+ status,
482
+ additions,
483
+ deletions,
484
+ oldPath: parts[2],
485
+ newPath: parts[3],
486
+ };
553
487
  }
554
488
  return null;
555
489
  }
@@ -595,11 +529,142 @@ function parseDiffSummary(diffOutput) {
595
529
  };
596
530
  }
597
531
 
532
+ const STATUS_TO_SYNTHETIC_PREFIX = {
533
+ added: "A",
534
+ deleted: "D",
535
+ renamed: "R100",
536
+ copied: "C100",
537
+ "type-changed": "T",
538
+ modified: "M",
539
+ unknown: "X",
540
+ };
541
+ function diffStatusToSyntheticPrefix(status) {
542
+ return STATUS_TO_SYNTHETIC_PREFIX[status];
543
+ }
544
+ function buildSyntheticDiffLine(meta, counts) {
545
+ const prefix = diffStatusToSyntheticPrefix(meta.status);
546
+ if (meta.oldPath) {
547
+ return `${prefix}\t${counts.additions}\t${counts.deletions}\t${meta.oldPath}\t${meta.path}`;
548
+ }
549
+ return `${prefix}\t${counts.additions}\t${counts.deletions}\t${meta.path}`;
550
+ }
551
+ function buildDiffSummaryFromGitOutputs(nameStatusOutput, numStatOutput) {
552
+ var _a;
553
+ const numMap = new Map();
554
+ accumulateNumStat(numStatOutput, numMap);
555
+ const mergedName = mergeNameEntriesByPath(parseNameStatusLines(nameStatusOutput));
556
+ const syntheticLines = [];
557
+ for (const [path, meta] of mergedName) {
558
+ const counts = (_a = numMap.get(path)) !== null && _a !== void 0 ? _a : { additions: 0, deletions: 0 };
559
+ syntheticLines.push(buildSyntheticDiffLine(meta, counts));
560
+ }
561
+ return parseDiffSummary(syntheticLines.join("\n"));
562
+ }
563
+
564
+ function createGitClient(cwd = process.cwd()) {
565
+ return simpleGit(cwd);
566
+ }
567
+ function getCommits(git, from, to) {
568
+ return __awaiter(this, void 0, void 0, function* () {
569
+ const logResult = yield git.log({ from, to });
570
+ return logResult.all;
571
+ });
572
+ }
573
+ function getRepoRoot(git) {
574
+ return __awaiter(this, void 0, void 0, function* () {
575
+ const root = yield git.revparse(["--show-toplevel"]);
576
+ return root.trim();
577
+ });
578
+ }
579
+ function getDiffPathContext(git, pathFilter, repoRootOverride) {
580
+ return __awaiter(this, void 0, void 0, function* () {
581
+ const repoRoot = repoRootOverride !== null && repoRootOverride !== void 0 ? repoRootOverride : (yield getRepoRoot(git));
582
+ const specs = buildDiffPathspecs(repoRoot, pathFilter);
583
+ return { repoRoot, specs };
584
+ });
585
+ }
586
+ function getDiff(git, query) {
587
+ return __awaiter(this, void 0, void 0, function* () {
588
+ const { from, to, commits, filterByCommits, pathFilter, repoRootOverride } = query;
589
+ const { specs } = yield getDiffPathContext(git, pathFilter, repoRootOverride);
590
+ if (!filterByCommits) {
591
+ return git.diff([`${from}..${to}`, "--", ...specs]);
592
+ }
593
+ const patches = yield Promise.all(commits.map((c) => git.diff([`${c.hash}^!`, "--", ...specs])));
594
+ return patches.filter(Boolean).join("\n");
595
+ });
596
+ }
597
+ function getDiffSummary(git, query) {
598
+ return __awaiter(this, void 0, void 0, function* () {
599
+ const { from, to, commits, filterByCommits, pathFilter, repoRootOverride } = query;
600
+ const { specs } = yield getDiffPathContext(git, pathFilter, repoRootOverride);
601
+ if (!filterByCommits) {
602
+ const [numOutput, nameOutput] = yield Promise.all([
603
+ git.diff(["--numstat", `${from}..${to}`, "--", ...specs]),
604
+ git.diff(["--name-status", `${from}..${to}`, "--", ...specs]),
605
+ ]);
606
+ return buildDiffSummaryFromGitOutputs(nameOutput, numOutput);
607
+ }
608
+ const pairs = yield Promise.all(commits.map((c) => __awaiter(this, void 0, void 0, function* () {
609
+ const range = `${c.hash}^!`;
610
+ const [numOutput, nameOutput] = yield Promise.all([
611
+ git.diff(["--numstat", range, "--", ...specs]),
612
+ git.diff(["--name-status", range, "--", ...specs]),
613
+ ]);
614
+ return { numOutput, nameOutput };
615
+ })));
616
+ const nameJoined = pairs
617
+ .map((p) => p.nameOutput)
618
+ .filter(Boolean)
619
+ .join("\n");
620
+ const numJoined = pairs
621
+ .map((p) => p.numOutput)
622
+ .filter(Boolean)
623
+ .join("\n");
624
+ return buildDiffSummaryFromGitOutputs(nameJoined, numJoined);
625
+ });
626
+ }
627
+ function getChangedFiles(git, query) {
628
+ return __awaiter(this, void 0, void 0, function* () {
629
+ const { from, to, commits, filterByCommits, pathFilter, repoRootOverride } = query;
630
+ const { specs } = yield getDiffPathContext(git, pathFilter, repoRootOverride);
631
+ if (!filterByCommits) {
632
+ const output = yield git.diff([
633
+ "--name-only",
634
+ `${from}..${to}`,
635
+ "--",
636
+ ...specs,
637
+ ]);
638
+ return output
639
+ .split(/\r?\n/)
640
+ .map((f) => f.trim())
641
+ .filter(Boolean);
642
+ }
643
+ const fileSet = new Set();
644
+ yield Promise.all(commits.map((c) => __awaiter(this, void 0, void 0, function* () {
645
+ const output = yield git.show([
646
+ "--name-only",
647
+ "--pretty=format:",
648
+ c.hash,
649
+ "--",
650
+ ...specs,
651
+ ]);
652
+ output
653
+ .split(/\r?\n/)
654
+ .map((f) => f.trim())
655
+ .filter(Boolean)
656
+ .forEach((f) => fileSet.add(f));
657
+ })));
658
+ return Array.from(fileSet);
659
+ });
660
+ }
661
+
598
662
  function hasNonEmptyTrimmed(arr) {
599
663
  return (arr !== null && arr !== void 0 ? arr : []).some((s) => s.trim().length > 0);
600
664
  }
601
665
  function shouldFilterByCommits(allCommits, filtered, opts) {
602
- if (hasNonEmptyTrimmed(opts.commitMessageIncludeRegexes) || hasNonEmptyTrimmed(opts.commitMessageExcludeRegexes)) {
666
+ if (hasNonEmptyTrimmed(opts.commitMessageIncludeRegexes) ||
667
+ hasNonEmptyTrimmed(opts.commitMessageExcludeRegexes)) {
603
668
  return true;
604
669
  }
605
670
  return filtered.length !== allCommits.length;
@@ -609,8 +674,9 @@ function summarizeGitDiff(options) {
609
674
  var _a, _b;
610
675
  const git = (_a = options.git) !== null && _a !== void 0 ? _a : createGitClient(options.cwd);
611
676
  const from = options.from;
612
- const to = (_b = options.to) !== null && _b !== void 0 ? _b : 'HEAD';
613
- const pathFilter = hasNonEmptyTrimmed(options.includeFolders) || hasNonEmptyTrimmed(options.excludeFolders)
677
+ const to = (_b = options.to) !== null && _b !== void 0 ? _b : "HEAD";
678
+ const pathFilter = hasNonEmptyTrimmed(options.includeFolders) ||
679
+ hasNonEmptyTrimmed(options.excludeFolders)
614
680
  ? {
615
681
  includeFolders: options.includeFolders,
616
682
  excludeFolders: options.excludeFolders,
@@ -619,10 +685,17 @@ function summarizeGitDiff(options) {
619
685
  const allCommits = yield getCommits(git, from, to);
620
686
  const filteredCommits = filterCommitsByMessageRegexes(allCommits, options.commitMessageIncludeRegexes, options.commitMessageExcludeRegexes);
621
687
  const filterByCommits = shouldFilterByCommits(allCommits, filteredCommits, options);
688
+ const rangeQuery = {
689
+ from,
690
+ to,
691
+ commits: filteredCommits,
692
+ filterByCommits,
693
+ pathFilter,
694
+ };
622
695
  const [diffText, fileNames, diffSummary] = yield Promise.all([
623
- getDiff(git, from, to, filteredCommits, filterByCommits, pathFilter),
624
- getChangedFiles(git, from, to, filteredCommits, filterByCommits, pathFilter),
625
- getDiffSummary(git, from, to, filteredCommits, filterByCommits, pathFilter),
696
+ getDiff(git, rangeQuery),
697
+ getChangedFiles(git, rangeQuery),
698
+ getDiffSummary(git, rangeQuery),
626
699
  ]);
627
700
  const summarizeFlags = {
628
701
  from,
@@ -634,7 +707,14 @@ function summarizeGitDiff(options) {
634
707
  commitMessageIncludeRegexes: options.commitMessageIncludeRegexes,
635
708
  commitMessageExcludeRegexes: options.commitMessageExcludeRegexes,
636
709
  };
637
- return generateSummary(diffText, fileNames, filteredCommits, summarizeFlags, options.openAiClientProvider, diffSummary);
710
+ return generateSummary({
711
+ diffText,
712
+ fileNames,
713
+ commits: filteredCommits,
714
+ flags: summarizeFlags,
715
+ openAiClientProvider: options.openAiClientProvider,
716
+ diffSummary,
717
+ });
638
718
  });
639
719
  }
640
720