@self-review/core 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1292 @@
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
+ checkWritability: () => checkWritability,
34
+ computePayloadStats: () => computePayloadStats,
35
+ countTotalLines: () => countTotalLines,
36
+ createIgnoreFilter: () => createIgnoreFilter,
37
+ generateSyntheticDiffs: () => generateSyntheticDiffs,
38
+ generateUntrackedDiffs: () => generateUntrackedDiffs,
39
+ getGitDiffStats: () => getGitDiffStats,
40
+ getRepoRoot: () => getRepoRoot,
41
+ getRepoRootAsync: () => getRepoRootAsync,
42
+ getUntrackedFilesAsync: () => getUntrackedFilesAsync,
43
+ isPreviewableImage: () => isPreviewableImage,
44
+ isPreviewableSvg: () => isPreviewableSvg,
45
+ loadConfig: () => loadConfig,
46
+ parseDiff: () => parseDiff,
47
+ parseReviewXml: () => parseReviewXml,
48
+ parseReviewXmlString: () => parseReviewXmlString,
49
+ runGitDiff: () => runGitDiff,
50
+ runGitDiffAsync: () => runGitDiffAsync,
51
+ scanDirectory: () => scanDirectory,
52
+ scanFile: () => scanFile,
53
+ serializeReview: () => serializeReview,
54
+ validateGitAvailable: () => validateGitAvailable
55
+ });
56
+ module.exports = __toCommonJS(index_exports);
57
+
58
+ // src/diff-parser.ts
59
+ function parseDiff(rawDiff) {
60
+ if (!rawDiff.trim()) {
61
+ return [];
62
+ }
63
+ const lines = rawDiff.split("\n");
64
+ const files = [];
65
+ let currentFile = null;
66
+ let currentHunk = null;
67
+ let oldLineNumber = 0;
68
+ let newLineNumber = 0;
69
+ for (let i = 0; i < lines.length; i++) {
70
+ const line = lines[i];
71
+ if (line.startsWith("diff --git ")) {
72
+ if (currentHunk && currentHunk.header && currentFile) {
73
+ currentFile.hunks.push(currentHunk);
74
+ currentHunk = null;
75
+ }
76
+ if (currentFile && currentFile.oldPath !== void 0 && currentFile.newPath !== void 0) {
77
+ if (currentFile.isBinary || currentFile.hunks && currentFile.hunks.length > 0 || currentFile.changeType === "added") {
78
+ files.push(currentFile);
79
+ }
80
+ }
81
+ const gitPaths = parseGitDiffHeader(line);
82
+ currentFile = {
83
+ oldPath: gitPaths.oldPath,
84
+ newPath: gitPaths.newPath,
85
+ changeType: "modified",
86
+ isBinary: false,
87
+ hunks: []
88
+ };
89
+ currentHunk = null;
90
+ continue;
91
+ }
92
+ if (!currentFile) continue;
93
+ if (line.startsWith("new file mode")) {
94
+ currentFile.changeType = "added";
95
+ continue;
96
+ }
97
+ if (line.startsWith("deleted file mode")) {
98
+ currentFile.changeType = "deleted";
99
+ continue;
100
+ }
101
+ if (line.startsWith("rename from ")) {
102
+ currentFile.changeType = "renamed";
103
+ continue;
104
+ }
105
+ if (line.startsWith("--- ")) {
106
+ const path2 = line.substring(4);
107
+ currentFile.oldPath = path2 === "/dev/null" ? "" : stripPrefix(path2);
108
+ continue;
109
+ }
110
+ if (line.startsWith("+++ ")) {
111
+ const path2 = line.substring(4);
112
+ currentFile.newPath = path2 === "/dev/null" ? "" : stripPrefix(path2);
113
+ continue;
114
+ }
115
+ if (line.startsWith("Binary files ")) {
116
+ currentFile.isBinary = true;
117
+ continue;
118
+ }
119
+ if (line.startsWith("@@")) {
120
+ if (currentHunk && currentHunk.header) {
121
+ currentFile.hunks.push(currentHunk);
122
+ }
123
+ const match = line.match(
124
+ /@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/
125
+ );
126
+ if (match) {
127
+ const oldStart = parseInt(match[1], 10);
128
+ const oldLines = match[2] ? parseInt(match[2], 10) : 1;
129
+ const newStart = parseInt(match[3], 10);
130
+ const newLines = match[4] ? parseInt(match[4], 10) : 1;
131
+ const _context = match[5];
132
+ currentHunk = {
133
+ header: line,
134
+ oldStart,
135
+ oldLines,
136
+ newStart,
137
+ newLines,
138
+ lines: []
139
+ };
140
+ oldLineNumber = oldStart;
141
+ newLineNumber = newStart;
142
+ }
143
+ continue;
144
+ }
145
+ if (currentHunk && currentHunk.lines) {
146
+ if (line.startsWith("+")) {
147
+ currentHunk.lines.push({
148
+ type: "addition",
149
+ oldLineNumber: null,
150
+ newLineNumber,
151
+ content: line.substring(1)
152
+ });
153
+ newLineNumber++;
154
+ } else if (line.startsWith("-")) {
155
+ currentHunk.lines.push({
156
+ type: "deletion",
157
+ oldLineNumber,
158
+ newLineNumber: null,
159
+ content: line.substring(1)
160
+ });
161
+ oldLineNumber++;
162
+ } else if (line.startsWith(" ")) {
163
+ currentHunk.lines.push({
164
+ type: "context",
165
+ oldLineNumber,
166
+ newLineNumber,
167
+ content: line.substring(1)
168
+ });
169
+ oldLineNumber++;
170
+ newLineNumber++;
171
+ } else if (line.startsWith("\\")) {
172
+ continue;
173
+ } else {
174
+ if (currentHunk.lines.length > 0) {
175
+ currentHunk.lines.push({
176
+ type: "context",
177
+ oldLineNumber,
178
+ newLineNumber,
179
+ content: line
180
+ });
181
+ oldLineNumber++;
182
+ newLineNumber++;
183
+ }
184
+ }
185
+ }
186
+ }
187
+ if (currentHunk && currentHunk.header && currentFile) {
188
+ currentFile.hunks.push(currentHunk);
189
+ }
190
+ if (currentFile && currentFile.oldPath !== void 0 && currentFile.newPath !== void 0) {
191
+ if (currentFile.isBinary || currentFile.hunks && currentFile.hunks.length > 0 || currentFile.changeType === "added") {
192
+ files.push(currentFile);
193
+ }
194
+ }
195
+ return files;
196
+ }
197
+ function stripPrefix(path2) {
198
+ if (path2.length > 2 && path2[1] === "/") {
199
+ return path2.substring(2);
200
+ }
201
+ return path2;
202
+ }
203
+ function parseGitDiffHeader(line) {
204
+ const withoutPrefix = line.substring("diff --git ".length);
205
+ let bIdx = -1;
206
+ for (const prefix of [" b/", " w/", " i/", " c/", " o/"]) {
207
+ bIdx = withoutPrefix.indexOf(prefix);
208
+ if (bIdx !== -1) break;
209
+ }
210
+ if (bIdx === -1) {
211
+ return { oldPath: "", newPath: "" };
212
+ }
213
+ const oldPath = stripPrefix(withoutPrefix.substring(0, bIdx));
214
+ const newPath = stripPrefix(withoutPrefix.substring(bIdx + 1));
215
+ return { oldPath, newPath };
216
+ }
217
+
218
+ // src/xml-serializer.ts
219
+ var path = __toESM(require("path"), 1);
220
+ var fs = __toESM(require("fs"), 1);
221
+ var import_xmllint_wasm = require("xmllint-wasm");
222
+ var XSD_SCHEMA = `<?xml version="1.0" encoding="UTF-8"?>
223
+ <xs:schema
224
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
225
+ xmlns:sr="urn:self-review:v1"
226
+ targetNamespace="urn:self-review:v1"
227
+ elementFormDefault="qualified"
228
+ >
229
+
230
+ <xs:element name="review" type="sr:ReviewType">
231
+ <xs:annotation>
232
+ <xs:documentation>
233
+ Root element of a self-review output file. Contains one file element
234
+ per file in the git diff, including files with no comments.
235
+ </xs:documentation>
236
+ </xs:annotation>
237
+ </xs:element>
238
+
239
+ <xs:complexType name="ReviewType">
240
+ <xs:sequence>
241
+ <xs:element name="file" type="sr:FileType" minOccurs="0" maxOccurs="unbounded" />
242
+ </xs:sequence>
243
+ <xs:attribute name="timestamp" type="xs:dateTime" use="required">
244
+ <xs:annotation>
245
+ <xs:documentation>
246
+ ISO 8601 timestamp of when the review was completed (window closed).
247
+ </xs:documentation>
248
+ </xs:annotation>
249
+ </xs:attribute>
250
+ <xs:attribute name="git-diff-args" type="xs:string" use="optional">
251
+ <xs:annotation>
252
+ <xs:documentation>
253
+ The git diff arguments that were passed to self-review on the CLI.
254
+ Example: "--staged", "main..feature-branch", "HEAD~3".
255
+ Present only when reviewing a git diff.
256
+ </xs:documentation>
257
+ </xs:annotation>
258
+ </xs:attribute>
259
+ <xs:attribute name="repository" type="xs:string" use="optional">
260
+ <xs:annotation>
261
+ <xs:documentation>
262
+ Absolute path to the repository root where self-review was invoked.
263
+ Present only when reviewing a git diff.
264
+ </xs:documentation>
265
+ </xs:annotation>
266
+ </xs:attribute>
267
+ <xs:attribute name="source-path" type="xs:string" use="optional">
268
+ <xs:annotation>
269
+ <xs:documentation>
270
+ Absolute path to the directory being reviewed.
271
+ Present only when reviewing a directory (non-git mode).
272
+ </xs:documentation>
273
+ </xs:annotation>
274
+ </xs:attribute>
275
+ </xs:complexType>
276
+
277
+ <xs:complexType name="FileType">
278
+ <xs:annotation>
279
+ <xs:documentation>
280
+ Represents a single file in the diff. Files with no comments
281
+ appear as empty elements. The path is relative to the repository root.
282
+ </xs:documentation>
283
+ </xs:annotation>
284
+ <xs:sequence>
285
+ <xs:element name="comment" type="sr:CommentType" minOccurs="0" maxOccurs="unbounded" />
286
+ </xs:sequence>
287
+ <xs:attribute name="path" type="xs:string" use="required">
288
+ <xs:annotation>
289
+ <xs:documentation>
290
+ File path relative to the repository root. For renamed files,
291
+ this is the new path.
292
+ </xs:documentation>
293
+ </xs:annotation>
294
+ </xs:attribute>
295
+ <xs:attribute name="change-type" type="sr:ChangeTypeEnum" use="required">
296
+ <xs:annotation>
297
+ <xs:documentation>
298
+ The type of change: added, modified, deleted, or renamed.
299
+ </xs:documentation>
300
+ </xs:annotation>
301
+ </xs:attribute>
302
+ <xs:attribute name="viewed" type="xs:boolean" use="required">
303
+ <xs:annotation>
304
+ <xs:documentation>
305
+ Whether the reviewer marked this file as reviewed.
306
+ true = the reviewer looked at this file.
307
+ false = the reviewer did not mark this file as viewed.
308
+ This helps an AI agent distinguish "reviewed with no comments"
309
+ from "not yet reviewed."
310
+ </xs:documentation>
311
+ </xs:annotation>
312
+ </xs:attribute>
313
+ </xs:complexType>
314
+
315
+ <xs:complexType name="CommentType">
316
+ <xs:annotation>
317
+ <xs:documentation>
318
+ A review comment. Three forms:
319
+
320
+ 1. File-level comment: no line attributes present.
321
+ Applies to the file as a whole.
322
+
323
+ 2. Comment on new/added/context lines: new-line-start and
324
+ new-line-end are present. These reference line numbers in the
325
+ post-change version of the file.
326
+
327
+ 3. Comment on old/deleted lines: old-line-start and old-line-end
328
+ are present. These reference line numbers in the pre-change
329
+ version of the file.
330
+
331
+ For single-line comments, start and end are equal.
332
+ Exactly one pair (old or new) should be present for line-level
333
+ comments. Both pairs absent = file-level comment.
334
+ </xs:documentation>
335
+ </xs:annotation>
336
+ <xs:sequence>
337
+ <xs:element name="body" type="xs:string">
338
+ <xs:annotation>
339
+ <xs:documentation>
340
+ The comment text. May contain markdown formatting.
341
+ </xs:documentation>
342
+ </xs:annotation>
343
+ </xs:element>
344
+ <xs:element name="category" type="xs:string">
345
+ <xs:annotation>
346
+ <xs:documentation>
347
+ Required category tag for this comment (e.g., "bug", "style",
348
+ "nit", "question", "security"). Categories are defined in the
349
+ project-level .self-review.yaml configuration. Every comment
350
+ must have a category to help AI agents prioritize and triage
351
+ feedback.
352
+ </xs:documentation>
353
+ </xs:annotation>
354
+ </xs:element>
355
+ <xs:element name="suggestion" type="sr:SuggestionType" minOccurs="0">
356
+ <xs:annotation>
357
+ <xs:documentation>
358
+ Optional code replacement proposal. When present, the AI agent
359
+ should replace the original-code with the proposed-code at the
360
+ referenced line range.
361
+ </xs:documentation>
362
+ </xs:annotation>
363
+ </xs:element>
364
+ <xs:element name="attachment" type="sr:AttachmentType" minOccurs="0" maxOccurs="unbounded">
365
+ <xs:annotation>
366
+ <xs:documentation>
367
+ Optional image attachment. The path attribute references an image file
368
+ stored in the .self-review-assets/ directory alongside the XML output.
369
+ </xs:documentation>
370
+ </xs:annotation>
371
+ </xs:element>
372
+ </xs:sequence>
373
+ <xs:attribute name="old-line-start" type="xs:positiveInteger" use="optional">
374
+ <xs:annotation>
375
+ <xs:documentation>
376
+ Start line number in the pre-change (old) version of the file.
377
+ Use for comments on deleted lines.
378
+ </xs:documentation>
379
+ </xs:annotation>
380
+ </xs:attribute>
381
+ <xs:attribute name="old-line-end" type="xs:positiveInteger" use="optional">
382
+ <xs:annotation>
383
+ <xs:documentation>
384
+ End line number (inclusive) in the pre-change (old) version.
385
+ Must be >= old-line-start when both are present.
386
+ </xs:documentation>
387
+ </xs:annotation>
388
+ </xs:attribute>
389
+ <xs:attribute name="new-line-start" type="xs:positiveInteger" use="optional">
390
+ <xs:annotation>
391
+ <xs:documentation>
392
+ Start line number in the post-change (new) version of the file.
393
+ Use for comments on added or context (unchanged) lines.
394
+ </xs:documentation>
395
+ </xs:annotation>
396
+ </xs:attribute>
397
+ <xs:attribute name="new-line-end" type="xs:positiveInteger" use="optional">
398
+ <xs:annotation>
399
+ <xs:documentation>
400
+ End line number (inclusive) in the post-change (new) version.
401
+ Must be >= new-line-start when both are present.
402
+ </xs:documentation>
403
+ </xs:annotation>
404
+ </xs:attribute>
405
+ </xs:complexType>
406
+
407
+ <xs:complexType name="SuggestionType">
408
+ <xs:annotation>
409
+ <xs:documentation>
410
+ A code replacement proposal. The original-code is the literal text
411
+ currently at the referenced lines. The proposed-code is what the
412
+ reviewer suggests it should be replaced with. The AI agent can apply
413
+ this by performing a text substitution.
414
+ </xs:documentation>
415
+ </xs:annotation>
416
+ <xs:sequence>
417
+ <xs:element name="original-code" type="xs:string">
418
+ <xs:annotation>
419
+ <xs:documentation>
420
+ The existing code at the referenced line range, copied verbatim
421
+ from the diff. Used by the AI agent to locate the replacement
422
+ target via text matching.
423
+ </xs:documentation>
424
+ </xs:annotation>
425
+ </xs:element>
426
+ <xs:element name="proposed-code" type="xs:string">
427
+ <xs:annotation>
428
+ <xs:documentation>
429
+ The replacement code proposed by the reviewer. The AI agent
430
+ should substitute original-code with this text.
431
+ </xs:documentation>
432
+ </xs:annotation>
433
+ </xs:element>
434
+ </xs:sequence>
435
+ </xs:complexType>
436
+
437
+ <xs:complexType name="AttachmentType">
438
+ <xs:annotation>
439
+ <xs:documentation>
440
+ Reference to an image file attached to a review comment. The file is stored
441
+ alongside the XML output in the .self-review-assets/ directory.
442
+ </xs:documentation>
443
+ </xs:annotation>
444
+ <xs:attribute name="path" type="xs:string" use="required">
445
+ <xs:annotation>
446
+ <xs:documentation>Relative path from the XML file to the image file.</xs:documentation>
447
+ </xs:annotation>
448
+ </xs:attribute>
449
+ <xs:attribute name="media-type" type="xs:string" use="required">
450
+ <xs:annotation>
451
+ <xs:documentation>MIME type of the image (e.g., image/png, image/jpeg).</xs:documentation>
452
+ </xs:annotation>
453
+ </xs:attribute>
454
+ </xs:complexType>
455
+
456
+ <xs:simpleType name="ChangeTypeEnum">
457
+ <xs:annotation>
458
+ <xs:documentation>
459
+ The type of change a file underwent in the diff.
460
+ </xs:documentation>
461
+ </xs:annotation>
462
+ <xs:restriction base="xs:string">
463
+ <xs:enumeration value="added">
464
+ <xs:annotation>
465
+ <xs:documentation>New file that did not exist before.</xs:documentation>
466
+ </xs:annotation>
467
+ </xs:enumeration>
468
+ <xs:enumeration value="modified">
469
+ <xs:annotation>
470
+ <xs:documentation>Existing file with content changes.</xs:documentation>
471
+ </xs:annotation>
472
+ </xs:enumeration>
473
+ <xs:enumeration value="deleted">
474
+ <xs:annotation>
475
+ <xs:documentation>File was removed.</xs:documentation>
476
+ </xs:annotation>
477
+ </xs:enumeration>
478
+ <xs:enumeration value="renamed">
479
+ <xs:annotation>
480
+ <xs:documentation>File was moved or renamed, with or without content changes.</xs:documentation>
481
+ </xs:annotation>
482
+ </xs:enumeration>
483
+ </xs:restriction>
484
+ </xs:simpleType>
485
+
486
+ </xs:schema>`;
487
+ function extFromMediaType(mediaType) {
488
+ const map = {
489
+ "image/png": "png",
490
+ "image/jpeg": "jpg",
491
+ "image/webp": "webp",
492
+ "image/gif": "gif"
493
+ };
494
+ return map[mediaType] || "png";
495
+ }
496
+ function writeAttachments(state, outputFilePath) {
497
+ const assetDir = path.join(path.dirname(outputFilePath), ".self-review-assets");
498
+ let hasAttachments = false;
499
+ const updatedFiles = state.files.map((file) => ({
500
+ ...file,
501
+ comments: file.comments.map((comment) => {
502
+ if (!comment.attachments?.length) return comment;
503
+ const updatedAttachments = comment.attachments.map((att, index) => {
504
+ if (!att.data) return att;
505
+ hasAttachments = true;
506
+ const ext = extFromMediaType(att.mediaType);
507
+ const fileName = `${comment.id}-${index}.${ext}`;
508
+ const relativePath = `.self-review-assets/${fileName}`;
509
+ if (!fs.existsSync(assetDir)) {
510
+ fs.mkdirSync(assetDir, { recursive: true });
511
+ }
512
+ fs.writeFileSync(path.join(assetDir, fileName), Buffer.from(att.data));
513
+ return { ...att, fileName: relativePath, data: void 0 };
514
+ });
515
+ return { ...comment, attachments: updatedAttachments };
516
+ })
517
+ }));
518
+ if (hasAttachments) {
519
+ console.error(`[main] Wrote attachment files to ${assetDir}`);
520
+ }
521
+ return { ...state, files: updatedFiles };
522
+ }
523
+ async function serializeReview(state, outputFilePath) {
524
+ const processedState = writeAttachments(state, outputFilePath);
525
+ const xml = buildXml(processedState);
526
+ try {
527
+ const validationResult = await (0, import_xmllint_wasm.validateXML)({
528
+ xml: [{ fileName: "review.xml", contents: xml }],
529
+ schema: [{ fileName: "self-review-v1.xsd", contents: XSD_SCHEMA }]
530
+ });
531
+ if (!validationResult.valid) {
532
+ const errors = validationResult.errors || [];
533
+ console.error("XML validation failed:");
534
+ errors.forEach((err) => console.error(` ${err}`));
535
+ throw new Error("Generated XML does not conform to schema");
536
+ }
537
+ } catch (error) {
538
+ if (error instanceof Error && error.message === "Generated XML does not conform to schema") {
539
+ throw error;
540
+ }
541
+ if (error instanceof Error) {
542
+ console.error(`[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`);
543
+ } else {
544
+ console.error("[main] XML validation infrastructure failed - emitting XML without validation");
545
+ }
546
+ return xml;
547
+ }
548
+ return xml;
549
+ }
550
+ function buildSourceAttributes(state) {
551
+ const source = state.source;
552
+ if (source.type === "git") {
553
+ return ` git-diff-args="${escapeXml(source.gitDiffArgs)}" repository="${escapeXml(source.repository)}"`;
554
+ }
555
+ if (source.type === "directory" || source.type === "file") {
556
+ return ` source-path="${escapeXml(source.sourcePath)}"`;
557
+ }
558
+ return "";
559
+ }
560
+ function buildXml(state) {
561
+ const lines = [];
562
+ lines.push('<?xml version="1.0" encoding="UTF-8"?>');
563
+ const sourceAttrs = buildSourceAttributes(state);
564
+ lines.push(
565
+ `<review xmlns="urn:self-review:v1" timestamp="${escapeXml(state.timestamp)}"${sourceAttrs}>`
566
+ );
567
+ for (const file of state.files) {
568
+ lines.push(...buildFileXml(file));
569
+ }
570
+ lines.push("</review>");
571
+ return lines.join("\n");
572
+ }
573
+ function buildFileXml(file) {
574
+ const lines = [];
575
+ if (file.comments.length === 0) {
576
+ lines.push(
577
+ ` <file path="${escapeXml(file.path)}" change-type="${file.changeType}" viewed="${file.viewed}" />`
578
+ );
579
+ } else {
580
+ lines.push(
581
+ ` <file path="${escapeXml(file.path)}" change-type="${file.changeType}" viewed="${file.viewed}">`
582
+ );
583
+ for (const comment of file.comments) {
584
+ lines.push(...buildCommentXml(comment));
585
+ }
586
+ lines.push(" </file>");
587
+ }
588
+ return lines;
589
+ }
590
+ function buildCommentXml(comment) {
591
+ const lines = [];
592
+ const attrs = [];
593
+ if (comment.lineRange) {
594
+ if (comment.lineRange.side === "old") {
595
+ attrs.push(`old-line-start="${comment.lineRange.start}"`);
596
+ attrs.push(`old-line-end="${comment.lineRange.end}"`);
597
+ } else {
598
+ attrs.push(`new-line-start="${comment.lineRange.start}"`);
599
+ attrs.push(`new-line-end="${comment.lineRange.end}"`);
600
+ }
601
+ }
602
+ const attrStr = attrs.length > 0 ? " " + attrs.join(" ") : "";
603
+ lines.push(` <comment${attrStr}>`);
604
+ lines.push(` <body>${escapeXml(comment.body)}</body>`);
605
+ lines.push(` <category>${escapeXml(comment.category)}</category>`);
606
+ if (comment.suggestion) {
607
+ lines.push(" <suggestion>");
608
+ lines.push(
609
+ ` <original-code>${escapeXml(comment.suggestion.originalCode)}</original-code>`
610
+ );
611
+ lines.push(
612
+ ` <proposed-code>${escapeXml(comment.suggestion.proposedCode)}</proposed-code>`
613
+ );
614
+ lines.push(" </suggestion>");
615
+ }
616
+ if (comment.attachments?.length) {
617
+ for (const att of comment.attachments) {
618
+ lines.push(` <attachment path="${escapeXml(att.fileName)}" media-type="${escapeXml(att.mediaType)}" />`);
619
+ }
620
+ }
621
+ lines.push(" </comment>");
622
+ return lines;
623
+ }
624
+ function escapeXml(str) {
625
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
626
+ }
627
+
628
+ // src/xml-parser.ts
629
+ var import_fs = require("fs");
630
+ var import_fast_xml_parser = require("fast-xml-parser");
631
+ function parseReviewXml(xmlPath) {
632
+ try {
633
+ const xmlContent = (0, import_fs.readFileSync)(xmlPath, "utf-8");
634
+ return parseReviewXmlString(xmlContent);
635
+ } catch (error) {
636
+ if (error instanceof Error) {
637
+ console.error(`Error reading XML file: ${error.message}`);
638
+ } else {
639
+ console.error("Error reading XML file: unknown error");
640
+ }
641
+ process.exit(1);
642
+ }
643
+ }
644
+ function parseReviewXmlString(xmlContent) {
645
+ const parser = new import_fast_xml_parser.XMLParser({
646
+ ignoreAttributes: false,
647
+ attributeNamePrefix: "@_",
648
+ allowBooleanAttributes: true
649
+ });
650
+ try {
651
+ const result = parser.parse(xmlContent);
652
+ if (!result.review) {
653
+ throw new Error("Invalid XML: missing <review> root element");
654
+ }
655
+ const review = result.review;
656
+ const gitDiffArgs = review["@_git-diff-args"] || "";
657
+ const source = parseSource(review);
658
+ const comments = [];
659
+ const files = Array.isArray(review.file) ? review.file : review.file ? [review.file] : [];
660
+ for (const file of files) {
661
+ const filePath = file["@_path"];
662
+ if (!filePath) continue;
663
+ const fileComments = Array.isArray(file.comment) ? file.comment : file.comment ? [file.comment] : [];
664
+ for (const comment of fileComments) {
665
+ const reviewComment = {
666
+ id: generateId(),
667
+ filePath,
668
+ lineRange: parseLineRange(comment),
669
+ body: comment.body || "",
670
+ category: comment.category || "",
671
+ suggestion: parseSuggestion(comment)
672
+ };
673
+ const commentAttachments = Array.isArray(comment.attachment) ? comment.attachment : comment.attachment ? [comment.attachment] : [];
674
+ if (commentAttachments.length > 0) {
675
+ reviewComment.attachments = commentAttachments.map(
676
+ (att, i) => ({
677
+ id: `${reviewComment.id}-att-${i}`,
678
+ fileName: String(att["@_path"] || ""),
679
+ mediaType: String(att["@_media-type"] || "image/png")
680
+ })
681
+ );
682
+ }
683
+ comments.push(reviewComment);
684
+ }
685
+ }
686
+ return { comments, gitDiffArgs, source };
687
+ } catch (error) {
688
+ if (error instanceof Error) {
689
+ console.error(`Error parsing XML: ${error.message}`);
690
+ } else {
691
+ console.error("Error parsing XML: unknown error");
692
+ }
693
+ process.exit(1);
694
+ }
695
+ }
696
+ function parseSource(review) {
697
+ const sourcePath = review["@_source-path"];
698
+ if (sourcePath) {
699
+ return { type: "directory", sourcePath: String(sourcePath) };
700
+ }
701
+ const gitDiffArgs = review["@_git-diff-args"];
702
+ const repository = review["@_repository"];
703
+ if (gitDiffArgs !== void 0 || repository !== void 0) {
704
+ return {
705
+ type: "git",
706
+ gitDiffArgs: String(gitDiffArgs || ""),
707
+ repository: String(repository || "")
708
+ };
709
+ }
710
+ return { type: "welcome" };
711
+ }
712
+ function parseLineRange(comment) {
713
+ const hasOld = comment["@_old-line-start"] !== void 0 && comment["@_old-line-end"] !== void 0;
714
+ const hasNew = comment["@_new-line-start"] !== void 0 && comment["@_new-line-end"] !== void 0;
715
+ if (hasOld) {
716
+ return {
717
+ side: "old",
718
+ start: parseInt(String(comment["@_old-line-start"]), 10),
719
+ end: parseInt(String(comment["@_old-line-end"]), 10)
720
+ };
721
+ }
722
+ if (hasNew) {
723
+ return {
724
+ side: "new",
725
+ start: parseInt(String(comment["@_new-line-start"]), 10),
726
+ end: parseInt(String(comment["@_new-line-end"]), 10)
727
+ };
728
+ }
729
+ return null;
730
+ }
731
+ function parseSuggestion(comment) {
732
+ if (!comment.suggestion) {
733
+ return null;
734
+ }
735
+ const suggestion = comment.suggestion;
736
+ return {
737
+ originalCode: String(suggestion["original-code"] || ""),
738
+ proposedCode: String(suggestion["proposed-code"] || "")
739
+ };
740
+ }
741
+ function generateId() {
742
+ return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
743
+ }
744
+
745
+ // src/git.ts
746
+ var import_child_process = require("child_process");
747
+ var import_util = require("util");
748
+
749
+ // src/synthetic-diff.ts
750
+ var import_fs2 = require("fs");
751
+ function generateSyntheticDiffs(paths, rootDir) {
752
+ const diffs = [];
753
+ for (const filePath of paths) {
754
+ const fullPath = `${rootDir}/${filePath}`;
755
+ let content;
756
+ try {
757
+ content = (0, import_fs2.readFileSync)(fullPath);
758
+ } catch {
759
+ continue;
760
+ }
761
+ const sample = content.subarray(0, 8192);
762
+ const isBinary = sample.includes(0);
763
+ if (isBinary) {
764
+ diffs.push(
765
+ `diff --git a/${filePath} b/${filePath}
766
+ new file mode 100644
767
+ Binary files /dev/null and b/${filePath} differ`
768
+ );
769
+ continue;
770
+ }
771
+ const text = content.toString("utf-8");
772
+ const lines = text.split("\n");
773
+ if (lines.length > 0 && lines[lines.length - 1] === "") {
774
+ lines.pop();
775
+ }
776
+ const lineCount = lines.length;
777
+ const addedLines = lines.map((line) => `+${line}`).join("\n");
778
+ let diff = `diff --git a/${filePath} b/${filePath}
779
+ new file mode 100644
780
+ --- /dev/null
781
+ +++ b/${filePath}
782
+ @@ -0,0 +1,${lineCount} @@
783
+ ` + addedLines;
784
+ if (text.length > 0 && !text.endsWith("\n")) {
785
+ diff += "\n\";
786
+ }
787
+ diffs.push(diff);
788
+ }
789
+ return diffs.join("\n");
790
+ }
791
+
792
+ // src/git.ts
793
+ var execAsync = (0, import_util.promisify)(import_child_process.exec);
794
+ function runGitDiff(args) {
795
+ try {
796
+ try {
797
+ (0, import_child_process.execSync)("git --version", { stdio: "ignore" });
798
+ } catch {
799
+ console.error("Error: git is not installed or not in PATH");
800
+ process.exit(1);
801
+ }
802
+ try {
803
+ (0, import_child_process.execSync)("git rev-parse --git-dir", { stdio: "ignore" });
804
+ } catch {
805
+ console.error(
806
+ "Error: not a git repository (or any parent up to mount point)"
807
+ );
808
+ process.exit(1);
809
+ }
810
+ const result = (0, import_child_process.execSync)(`git diff ${args.join(" ")}`, {
811
+ encoding: "utf-8",
812
+ maxBuffer: 50 * 1024 * 1024
813
+ // 50MB buffer for large diffs
814
+ });
815
+ return result;
816
+ } catch (error) {
817
+ if (error instanceof Error) {
818
+ console.error(`Error running git diff: ${error.message}`);
819
+ } else {
820
+ console.error("Error running git diff: unknown error");
821
+ }
822
+ process.exit(1);
823
+ }
824
+ }
825
+ function getRepoRoot() {
826
+ try {
827
+ const result = (0, import_child_process.execSync)("git rev-parse --show-toplevel", {
828
+ encoding: "utf-8"
829
+ });
830
+ return result.trim();
831
+ } catch (error) {
832
+ if (error instanceof Error) {
833
+ console.error(`Error getting repository root: ${error.message}`);
834
+ } else {
835
+ console.error("Error getting repository root: unknown error");
836
+ }
837
+ process.exit(1);
838
+ }
839
+ }
840
+ function validateGitAvailable() {
841
+ try {
842
+ (0, import_child_process.execSync)("git --version", { stdio: "ignore" });
843
+ } catch {
844
+ console.error("Error: git is not installed or not in PATH");
845
+ process.exit(1);
846
+ }
847
+ try {
848
+ (0, import_child_process.execSync)("git rev-parse --git-dir", { stdio: "ignore" });
849
+ } catch {
850
+ console.error(
851
+ "Error: not a git repository (or any parent up to mount point)"
852
+ );
853
+ process.exit(1);
854
+ }
855
+ }
856
+ async function getRepoRootAsync(cwd) {
857
+ try {
858
+ const { stdout } = await execAsync("git rev-parse --show-toplevel", {
859
+ timeout: 1e4,
860
+ // 10 second timeout
861
+ cwd
862
+ });
863
+ return stdout.trim();
864
+ } catch (error) {
865
+ if (error instanceof Error) {
866
+ console.error(`Error getting repository root: ${error.message}`);
867
+ } else {
868
+ console.error("Error getting repository root: unknown error");
869
+ }
870
+ throw error;
871
+ }
872
+ }
873
+ async function runGitDiffAsync(args, cwd) {
874
+ try {
875
+ const { stdout } = await execAsync(`git diff ${args.join(" ")}`, {
876
+ maxBuffer: 50 * 1024 * 1024,
877
+ // 50MB buffer
878
+ timeout: 3e4,
879
+ // 30 second timeout
880
+ cwd
881
+ });
882
+ return stdout;
883
+ } catch (error) {
884
+ if (error instanceof Error) {
885
+ console.error(`Error running git diff: ${error.message}`);
886
+ } else {
887
+ console.error("Error running git diff: unknown error");
888
+ }
889
+ throw error;
890
+ }
891
+ }
892
+ async function getUntrackedFilesAsync(cwd) {
893
+ try {
894
+ const { stdout } = await execAsync(
895
+ "git ls-files --others --exclude-standard",
896
+ {
897
+ maxBuffer: 10 * 1024 * 1024,
898
+ timeout: 1e4,
899
+ cwd
900
+ }
901
+ );
902
+ return stdout.trim().split("\n").filter((line) => line.length > 0);
903
+ } catch (error) {
904
+ if (error instanceof Error) {
905
+ console.error(
906
+ `Warning: Failed to list untracked files: ${error.message}`
907
+ );
908
+ } else {
909
+ console.error("Warning: Failed to list untracked files: unknown error");
910
+ }
911
+ return [];
912
+ }
913
+ }
914
+ function generateUntrackedDiffs(paths, repoRoot) {
915
+ return generateSyntheticDiffs(paths, repoRoot);
916
+ }
917
+
918
+ // src/directory-scanner.ts
919
+ var import_promises = require("fs/promises");
920
+ var import_path = require("path");
921
+
922
+ // src/ignore-filter.ts
923
+ var import_ignore = __toESM(require("ignore"), 1);
924
+ function createIgnoreFilter(patterns) {
925
+ if (patterns.length === 0) return () => true;
926
+ const ig = (0, import_ignore.default)().add(patterns);
927
+ return (filePath) => !ig.ignores(filePath);
928
+ }
929
+
930
+ // src/directory-scanner.ts
931
+ async function scanDirectory(directoryPath, ignorePatterns = []) {
932
+ try {
933
+ const dirStat = await (0, import_promises.stat)(directoryPath);
934
+ if (!dirStat.isDirectory()) {
935
+ console.error(
936
+ `Error: "${directoryPath}" is not a directory`
937
+ );
938
+ return [];
939
+ }
940
+ } catch (error) {
941
+ if (error instanceof Error) {
942
+ console.error(
943
+ `Error accessing directory "${directoryPath}": ${error.message}`
944
+ );
945
+ } else {
946
+ console.error(
947
+ `Error accessing directory "${directoryPath}": unknown error`
948
+ );
949
+ }
950
+ return [];
951
+ }
952
+ const filePaths = [];
953
+ try {
954
+ const entries = await (0, import_promises.readdir)(directoryPath, {
955
+ recursive: true,
956
+ withFileTypes: true
957
+ });
958
+ for (const entry of entries) {
959
+ if (!entry.isFile()) {
960
+ continue;
961
+ }
962
+ const parentDir = entry.parentPath ?? entry.path;
963
+ const fullPath = (0, import_path.join)(parentDir, entry.name);
964
+ const relativePath = (0, import_path.relative)(directoryPath, fullPath);
965
+ filePaths.push(relativePath);
966
+ }
967
+ } catch (error) {
968
+ if (error instanceof Error) {
969
+ console.error(
970
+ `Error reading directory "${directoryPath}": ${error.message}`
971
+ );
972
+ } else {
973
+ console.error(
974
+ `Error reading directory "${directoryPath}": unknown error`
975
+ );
976
+ }
977
+ return [];
978
+ }
979
+ filePaths.sort();
980
+ const shouldKeep = createIgnoreFilter(ignorePatterns);
981
+ const filteredPaths = filePaths.filter((p) => shouldKeep(p));
982
+ if (filteredPaths.length === 0) {
983
+ return [];
984
+ }
985
+ const diffText = generateSyntheticDiffs(filteredPaths, directoryPath);
986
+ return parseDiff(diffText);
987
+ }
988
+ async function scanFile(filePath) {
989
+ try {
990
+ const fileStat = await (0, import_promises.stat)(filePath);
991
+ if (!fileStat.isFile()) {
992
+ console.error(`Error: "${filePath}" is not a file`);
993
+ return [];
994
+ }
995
+ } catch (error) {
996
+ if (error instanceof Error) {
997
+ console.error(`Error accessing file "${filePath}": ${error.message}`);
998
+ } else {
999
+ console.error(`Error accessing file "${filePath}": unknown error`);
1000
+ }
1001
+ return [];
1002
+ }
1003
+ const fileName = (0, import_path.basename)(filePath);
1004
+ const rootDir = (0, import_path.dirname)(filePath);
1005
+ const diffText = generateSyntheticDiffs([fileName], rootDir);
1006
+ return parseDiff(diffText);
1007
+ }
1008
+
1009
+ // src/config.ts
1010
+ var import_fs3 = require("fs");
1011
+ var import_path2 = require("path");
1012
+ var import_os = require("os");
1013
+ var import_yaml = require("yaml");
1014
+ var defaults = {
1015
+ theme: "system",
1016
+ diffView: "split",
1017
+ fontSize: 14,
1018
+ outputFormat: "xml",
1019
+ outputFile: "./review.xml",
1020
+ ignore: [
1021
+ ".git",
1022
+ "node_modules",
1023
+ "vendor",
1024
+ ".vendor",
1025
+ "__pycache__",
1026
+ ".venv",
1027
+ "venv",
1028
+ ".env",
1029
+ "dist",
1030
+ "build",
1031
+ ".next",
1032
+ ".nuxt",
1033
+ ".svelte-kit",
1034
+ "target",
1035
+ "*.min.js",
1036
+ "*.min.css",
1037
+ "package-lock.json",
1038
+ "yarn.lock",
1039
+ "pnpm-lock.yaml",
1040
+ "composer.lock",
1041
+ "Gemfile.lock",
1042
+ "Cargo.lock",
1043
+ "poetry.lock",
1044
+ "go.sum"
1045
+ ],
1046
+ categories: [
1047
+ {
1048
+ name: "question",
1049
+ description: "Clarification needed \u2014 not necessarily a problem",
1050
+ color: "#805ad5"
1051
+ },
1052
+ {
1053
+ name: "bug",
1054
+ description: "Likely defect or incorrect behavior",
1055
+ color: "#e53e3e"
1056
+ },
1057
+ {
1058
+ name: "security",
1059
+ description: "Security vulnerability or concern",
1060
+ color: "#dd6b20"
1061
+ },
1062
+ {
1063
+ name: "style",
1064
+ description: "Code style, naming, or formatting issue",
1065
+ color: "#3182ce"
1066
+ },
1067
+ {
1068
+ name: "task",
1069
+ description: "Action item or follow-up task",
1070
+ color: "#38a169"
1071
+ },
1072
+ {
1073
+ name: "nit",
1074
+ description: "Minor nitpick, low priority",
1075
+ color: "#718096"
1076
+ }
1077
+ ],
1078
+ defaultDiffArgs: "",
1079
+ showUntracked: true,
1080
+ wordWrap: true,
1081
+ maxFiles: 500,
1082
+ maxTotalLines: 1e5
1083
+ };
1084
+ function loadConfig() {
1085
+ let config = { ...defaults };
1086
+ const userConfigPath = (0, import_path2.join)(
1087
+ (0, import_os.homedir)(),
1088
+ ".config",
1089
+ "self-review",
1090
+ "config.yaml"
1091
+ );
1092
+ if ((0, import_fs3.existsSync)(userConfigPath)) {
1093
+ try {
1094
+ const userConfig = loadYamlConfig(userConfigPath);
1095
+ config = mergeConfig(config, userConfig);
1096
+ } catch (error) {
1097
+ console.error(
1098
+ `Warning: Failed to load user config from ${userConfigPath}: ${error}`
1099
+ );
1100
+ }
1101
+ }
1102
+ const projectConfigPath = (0, import_path2.join)(process.cwd(), ".self-review.yaml");
1103
+ if ((0, import_fs3.existsSync)(projectConfigPath)) {
1104
+ try {
1105
+ const projectConfig = loadYamlConfig(projectConfigPath);
1106
+ config = mergeConfig(config, projectConfig);
1107
+ } catch (error) {
1108
+ console.error(
1109
+ `Warning: Failed to load project config from ${projectConfigPath}: ${error}`
1110
+ );
1111
+ }
1112
+ }
1113
+ return config;
1114
+ }
1115
+ function loadYamlConfig(path2) {
1116
+ const content = (0, import_fs3.readFileSync)(path2, "utf-8");
1117
+ const raw = (0, import_yaml.parse)(content);
1118
+ if (!raw || typeof raw !== "object") {
1119
+ throw new Error("Invalid YAML format");
1120
+ }
1121
+ const config = {};
1122
+ if ("theme" in raw) {
1123
+ if (["light", "dark", "system"].includes(raw.theme)) {
1124
+ config.theme = raw.theme;
1125
+ } else {
1126
+ console.error(
1127
+ `Warning: Invalid theme value "${raw.theme}", using default`
1128
+ );
1129
+ }
1130
+ }
1131
+ if ("diff-view" in raw) {
1132
+ if (["split", "unified"].includes(raw["diff-view"])) {
1133
+ config.diffView = raw["diff-view"];
1134
+ } else {
1135
+ console.error(
1136
+ `Warning: Invalid diff-view value "${raw["diff-view"]}", using default`
1137
+ );
1138
+ }
1139
+ }
1140
+ if ("font-size" in raw && typeof raw["font-size"] === "number") {
1141
+ config.fontSize = raw["font-size"];
1142
+ }
1143
+ if ("output-format" in raw && typeof raw["output-format"] === "string") {
1144
+ config.outputFormat = raw["output-format"];
1145
+ }
1146
+ if ("ignore" in raw && Array.isArray(raw.ignore)) {
1147
+ config.ignore = raw.ignore.filter(
1148
+ (item) => typeof item === "string"
1149
+ );
1150
+ }
1151
+ if ("categories" in raw && Array.isArray(raw.categories)) {
1152
+ config.categories = raw.categories.filter(
1153
+ (cat) => cat !== null && typeof cat === "object" && typeof cat.name === "string" && typeof cat.description === "string" && typeof cat.color === "string"
1154
+ );
1155
+ }
1156
+ if ("default-diff-args" in raw && typeof raw["default-diff-args"] === "string") {
1157
+ config.defaultDiffArgs = raw["default-diff-args"];
1158
+ }
1159
+ if ("show-untracked" in raw && typeof raw["show-untracked"] === "boolean") {
1160
+ config.showUntracked = raw["show-untracked"];
1161
+ }
1162
+ if ("word-wrap" in raw && typeof raw["word-wrap"] === "boolean") {
1163
+ config.wordWrap = raw["word-wrap"];
1164
+ }
1165
+ if ("max-files" in raw && typeof raw["max-files"] === "number") {
1166
+ config.maxFiles = raw["max-files"] >= 0 ? raw["max-files"] : defaults.maxFiles;
1167
+ }
1168
+ if ("max-total-lines" in raw && typeof raw["max-total-lines"] === "number") {
1169
+ config.maxTotalLines = raw["max-total-lines"] >= 0 ? raw["max-total-lines"] : defaults.maxTotalLines;
1170
+ }
1171
+ if ("output-file" in raw && typeof raw["output-file"] === "string" && raw["output-file"].length > 0) {
1172
+ config.outputFile = raw["output-file"];
1173
+ }
1174
+ return config;
1175
+ }
1176
+ function mergeConfig(base, override) {
1177
+ return {
1178
+ ...base,
1179
+ ...override,
1180
+ // Arrays are replaced, not merged
1181
+ ignore: override.ignore !== void 0 ? override.ignore : base.ignore,
1182
+ categories: override.categories !== void 0 ? override.categories : base.categories
1183
+ };
1184
+ }
1185
+
1186
+ // src/payload-sizing.ts
1187
+ var import_child_process2 = require("child_process");
1188
+ var import_util2 = require("util");
1189
+ var execAsync2 = (0, import_util2.promisify)(import_child_process2.exec);
1190
+ function computePayloadStats(fileCount, totalLines, config) {
1191
+ const maxFiles = config.maxFiles;
1192
+ const maxTotalLines = config.maxTotalLines;
1193
+ const exceedsFiles = maxFiles > 0 && fileCount > maxFiles;
1194
+ const exceedsLines = maxTotalLines > 0 && totalLines > maxTotalLines;
1195
+ return {
1196
+ fileCount,
1197
+ totalLines,
1198
+ exceedsFiles,
1199
+ exceedsLines,
1200
+ exceedsAny: exceedsFiles || exceedsLines
1201
+ };
1202
+ }
1203
+ function countTotalLines(files) {
1204
+ let total = 0;
1205
+ for (const file of files) {
1206
+ for (const hunk of file.hunks) {
1207
+ total += hunk.lines.length;
1208
+ }
1209
+ }
1210
+ return total;
1211
+ }
1212
+ async function getGitDiffStats(args, repoRoot) {
1213
+ try {
1214
+ const { stdout } = await execAsync2(`git diff --numstat ${args.join(" ")}`, {
1215
+ maxBuffer: 10 * 1024 * 1024,
1216
+ timeout: 15e3,
1217
+ cwd: repoRoot
1218
+ });
1219
+ let fileCount = 0;
1220
+ let totalLines = 0;
1221
+ for (const line of stdout.trim().split("\n")) {
1222
+ if (!line) continue;
1223
+ const parts = line.split(" ");
1224
+ if (parts.length < 3) continue;
1225
+ fileCount++;
1226
+ const added = parts[0] === "-" ? 0 : parseInt(parts[0], 10);
1227
+ const removed = parts[1] === "-" ? 0 : parseInt(parts[1], 10);
1228
+ totalLines += (isNaN(added) ? 0 : added) + (isNaN(removed) ? 0 : removed);
1229
+ }
1230
+ return { fileCount, totalLines };
1231
+ } catch (error) {
1232
+ if (error instanceof Error) {
1233
+ console.error(`[payload-sizing] Failed to get git diff stats: ${error.message}`);
1234
+ } else {
1235
+ console.error("[payload-sizing] Failed to get git diff stats: unknown error");
1236
+ }
1237
+ return { fileCount: 0, totalLines: 0 };
1238
+ }
1239
+ }
1240
+
1241
+ // src/fs-utils.ts
1242
+ var import_fs4 = require("fs");
1243
+ var import_path3 = require("path");
1244
+ function checkWritability(filePath) {
1245
+ try {
1246
+ const dir = (0, import_path3.dirname)(filePath);
1247
+ (0, import_fs4.accessSync)(dir, import_fs4.constants.W_OK);
1248
+ return true;
1249
+ } catch {
1250
+ return false;
1251
+ }
1252
+ }
1253
+
1254
+ // src/file-type-utils.ts
1255
+ var RASTER_IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([".jpg", ".jpeg", ".png", ".gif", ".webp", ".ico", ".bmp"]);
1256
+ function getExtension(filePath) {
1257
+ const lastDot = filePath.lastIndexOf(".");
1258
+ if (lastDot === -1 || lastDot === filePath.length - 1) return "";
1259
+ return filePath.slice(lastDot).toLowerCase();
1260
+ }
1261
+ function isPreviewableImage(filePath) {
1262
+ return RASTER_IMAGE_EXTENSIONS.has(getExtension(filePath));
1263
+ }
1264
+ function isPreviewableSvg(filePath) {
1265
+ return getExtension(filePath) === ".svg";
1266
+ }
1267
+ // Annotate the CommonJS export names for ESM import in node:
1268
+ 0 && (module.exports = {
1269
+ checkWritability,
1270
+ computePayloadStats,
1271
+ countTotalLines,
1272
+ createIgnoreFilter,
1273
+ generateSyntheticDiffs,
1274
+ generateUntrackedDiffs,
1275
+ getGitDiffStats,
1276
+ getRepoRoot,
1277
+ getRepoRootAsync,
1278
+ getUntrackedFilesAsync,
1279
+ isPreviewableImage,
1280
+ isPreviewableSvg,
1281
+ loadConfig,
1282
+ parseDiff,
1283
+ parseReviewXml,
1284
+ parseReviewXmlString,
1285
+ runGitDiff,
1286
+ runGitDiffAsync,
1287
+ scanDirectory,
1288
+ scanFile,
1289
+ serializeReview,
1290
+ validateGitAvailable
1291
+ });
1292
+ //# sourceMappingURL=index.cjs.map