@self-review/core 1.28.0 → 1.28.3

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 CHANGED
@@ -37,6 +37,7 @@ __export(index_exports, {
37
37
  generateSyntheticDiffs: () => generateSyntheticDiffs,
38
38
  generateUntrackedDiffs: () => generateUntrackedDiffs,
39
39
  getGitDiffStats: () => getGitDiffStats,
40
+ getLanguageFromPath: () => getLanguageFromPath,
40
41
  getRepoRoot: () => getRepoRoot,
41
42
  getRepoRootAsync: () => getRepoRootAsync,
42
43
  getUntrackedFilesAsync: () => getUntrackedFilesAsync,
@@ -1264,6 +1265,70 @@ function isPreviewableImage(filePath) {
1264
1265
  function isPreviewableSvg(filePath) {
1265
1266
  return getExtension(filePath) === ".svg";
1266
1267
  }
1268
+ function getLanguageFromPath(filePath) {
1269
+ const ext = filePath.split(".").pop()?.toLowerCase() || "";
1270
+ const langMap = {
1271
+ ts: "typescript",
1272
+ tsx: "tsx",
1273
+ js: "javascript",
1274
+ jsx: "jsx",
1275
+ py: "python",
1276
+ css: "css",
1277
+ json: "json",
1278
+ md: "markdown",
1279
+ sh: "bash",
1280
+ bash: "bash",
1281
+ yml: "yaml",
1282
+ yaml: "yaml",
1283
+ java: "java",
1284
+ go: "go",
1285
+ rs: "rust",
1286
+ sql: "sql",
1287
+ html: "markup",
1288
+ xml: "markup",
1289
+ rb: "ruby",
1290
+ php: "php",
1291
+ twig: "twig",
1292
+ c: "c",
1293
+ cpp: "cpp",
1294
+ h: "c",
1295
+ hpp: "cpp",
1296
+ // Config and data formats
1297
+ ini: "ini",
1298
+ toml: "toml",
1299
+ csv: "csv",
1300
+ diff: "diff",
1301
+ patch: "diff",
1302
+ // Web and infrastructure
1303
+ scss: "scss",
1304
+ sass: "sass",
1305
+ graphql: "graphql",
1306
+ gql: "graphql",
1307
+ conf: "nginx",
1308
+ // Database
1309
+ mongodb: "mongodb",
1310
+ // Tooling
1311
+ makefile: "makefile",
1312
+ mk: "makefile",
1313
+ mak: "makefile",
1314
+ vim: "vim",
1315
+ vimrc: "vim"
1316
+ };
1317
+ const filename = filePath.split("/").pop()?.toLowerCase() || "";
1318
+ if (filename === "dockerfile" || filename.startsWith("dockerfile.")) {
1319
+ return "docker";
1320
+ }
1321
+ if (filename === "makefile" || filename.startsWith("makefile.")) {
1322
+ return "makefile";
1323
+ }
1324
+ if (filename.startsWith(".git")) {
1325
+ return "git";
1326
+ }
1327
+ if (filename === ".vimrc" || filename.startsWith(".vim")) {
1328
+ return "vim";
1329
+ }
1330
+ return langMap[ext] || "plaintext";
1331
+ }
1267
1332
  // Annotate the CommonJS export names for ESM import in node:
1268
1333
  0 && (module.exports = {
1269
1334
  checkWritability,
@@ -1273,6 +1338,7 @@ function isPreviewableSvg(filePath) {
1273
1338
  generateSyntheticDiffs,
1274
1339
  generateUntrackedDiffs,
1275
1340
  getGitDiffStats,
1341
+ getLanguageFromPath,
1276
1342
  getRepoRoot,
1277
1343
  getRepoRootAsync,
1278
1344
  getUntrackedFilesAsync,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/diff-parser.ts","../src/xml-serializer.ts","../src/xml-parser.ts","../src/git.ts","../src/synthetic-diff.ts","../src/directory-scanner.ts","../src/ignore-filter.ts","../src/config.ts","../src/payload-sizing.ts","../src/fs-utils.ts","../src/file-type-utils.ts"],"sourcesContent":["// @self-review/core — Node.js API for diff parsing, git operations, XML serialization, and configuration\n\n// Types\nexport type {\n ChangeType,\n DiffLineType,\n DiffLine,\n DiffHunk,\n DiffFile,\n DiffSource,\n Suggestion,\n Attachment,\n LineRange,\n ReviewComment,\n FileReviewState,\n ReviewState,\n CategoryDef,\n AppConfig,\n DiffLoadPayload,\n ResumeLoadPayload,\n OutputPathInfo,\n ExpandContextRequest,\n ExpandContextResponse,\n FindInPageRequest,\n FindInPageResult,\n VersionUpdateInfo,\n PayloadStats,\n ImageLoadResult,\n} from './types';\n\n// Diff parsing\nexport { parseDiff } from './diff-parser';\n\n// XML I/O\nexport { serializeReview } from './xml-serializer';\nexport { parseReviewXml, parseReviewXmlString } from './xml-parser';\n\n// Git operations\nexport {\n runGitDiff,\n runGitDiffAsync,\n getRepoRoot,\n getRepoRootAsync,\n getUntrackedFilesAsync,\n validateGitAvailable,\n generateUntrackedDiffs,\n} from './git';\n\n// Synthetic diffs (for non-git files/directories)\nexport { generateSyntheticDiffs } from './synthetic-diff';\n\n// Directory/file scanning\nexport { scanDirectory, scanFile } from './directory-scanner';\n\n// Configuration\nexport { loadConfig } from './config';\n\n// Payload sizing\nexport { computePayloadStats, countTotalLines, getGitDiffStats } from './payload-sizing';\n\n// Ignore filter\nexport { createIgnoreFilter } from './ignore-filter';\n\n// File system utilities\nexport { checkWritability } from './fs-utils';\n\n// File type detection utilities\nexport { isPreviewableImage, isPreviewableSvg } from './file-type-utils';\n","// src/main/diff-parser.ts\n// Parse unified diff output into DiffFile[]\n\nimport { DiffFile, DiffHunk, ChangeType } from './types';\n\nexport function parseDiff(rawDiff: string): DiffFile[] {\n if (!rawDiff.trim()) {\n return [];\n }\n\n const lines = rawDiff.split('\\n');\n const files: DiffFile[] = [];\n let currentFile: Partial<DiffFile> | null = null;\n let currentHunk: Partial<DiffHunk> | null = null;\n let oldLineNumber = 0;\n let newLineNumber = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n // Start of a new file\n if (line.startsWith('diff --git ')) {\n // Flush the pending hunk into the current file before saving\n if (currentHunk && currentHunk.header && currentFile) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n currentHunk = null;\n }\n\n // Save previous file if exists and has actual changes\n if (\n currentFile &&\n currentFile.oldPath !== undefined &&\n currentFile.newPath !== undefined\n ) {\n // Include files that have hunks, are binary, or are new (empty new files)\n if (\n currentFile.isBinary ||\n (currentFile.hunks && currentFile.hunks.length > 0) ||\n currentFile.changeType === 'added'\n ) {\n files.push(currentFile as DiffFile);\n }\n }\n\n // Extract paths from \"diff --git a/<old> b/<new>\" as fallback\n // for binary files that lack --- / +++ lines\n const gitPaths = parseGitDiffHeader(line);\n\n // Initialize new file\n currentFile = {\n oldPath: gitPaths.oldPath,\n newPath: gitPaths.newPath,\n changeType: 'modified' as ChangeType,\n isBinary: false,\n hunks: [],\n };\n currentHunk = null;\n continue;\n }\n\n if (!currentFile) continue;\n\n // Detect file mode changes\n if (line.startsWith('new file mode')) {\n currentFile.changeType = 'added';\n continue;\n }\n\n if (line.startsWith('deleted file mode')) {\n currentFile.changeType = 'deleted';\n continue;\n }\n\n if (line.startsWith('rename from ')) {\n currentFile.changeType = 'renamed';\n continue;\n }\n\n // Parse old file path\n if (line.startsWith('--- ')) {\n const path = line.substring(4);\n currentFile.oldPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Parse new file path\n if (line.startsWith('+++ ')) {\n const path = line.substring(4);\n currentFile.newPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Detect binary files\n if (line.startsWith('Binary files ')) {\n currentFile.isBinary = true;\n continue;\n }\n\n // Parse hunk header\n if (line.startsWith('@@')) {\n // Save previous hunk if exists\n if (currentHunk && currentHunk.header) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n\n // Parse hunk header: @@ -oldStart,oldLines +newStart,newLines @@ context\n const match = line.match(\n /@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@(.*)$/\n );\n if (match) {\n const oldStart = parseInt(match[1], 10);\n const oldLines = match[2] ? parseInt(match[2], 10) : 1;\n const newStart = parseInt(match[3], 10);\n const newLines = match[4] ? parseInt(match[4], 10) : 1;\n const _context = match[5];\n\n currentHunk = {\n header: line,\n oldStart,\n oldLines,\n newStart,\n newLines,\n lines: [],\n };\n\n oldLineNumber = oldStart;\n newLineNumber = newStart;\n }\n continue;\n }\n\n // Parse diff lines (must have a current hunk)\n if (currentHunk && currentHunk.lines) {\n if (line.startsWith('+')) {\n // Addition\n currentHunk.lines.push({\n type: 'addition',\n oldLineNumber: null,\n newLineNumber: newLineNumber,\n content: line.substring(1),\n });\n newLineNumber++;\n } else if (line.startsWith('-')) {\n // Deletion\n currentHunk.lines.push({\n type: 'deletion',\n oldLineNumber: oldLineNumber,\n newLineNumber: null,\n content: line.substring(1),\n });\n oldLineNumber++;\n } else if (line.startsWith(' ')) {\n // Context line\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content: line.substring(1),\n });\n oldLineNumber++;\n newLineNumber++;\n } else if (line.startsWith('\\\\')) {\n // \"\\" - ignore\n continue;\n } else {\n // Some other line (could be empty or malformed), treat as context\n if (currentHunk.lines.length > 0) {\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content: line,\n });\n oldLineNumber++;\n newLineNumber++;\n }\n }\n }\n }\n\n // Save the last hunk and file\n if (currentHunk && currentHunk.header && currentFile) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n if (\n currentFile &&\n currentFile.oldPath !== undefined &&\n currentFile.newPath !== undefined\n ) {\n // Include files that have hunks, are binary, or are new (empty new files)\n if (\n currentFile.isBinary ||\n (currentFile.hunks && currentFile.hunks.length > 0) ||\n currentFile.changeType === 'added'\n ) {\n files.push(currentFile as DiffFile);\n }\n }\n\n return files;\n}\n\nfunction stripPrefix(path: string): string {\n // Remove single-character prefix (a/, b/, c/, i/, w/, etc.)\n // Git uses a/b by default, but mnemonicPrefix uses c/i/w/o\n if (path.length > 2 && path[1] === '/') {\n return path.substring(2);\n }\n return path;\n}\n\nfunction parseGitDiffHeader(line: string): {\n oldPath: string;\n newPath: string;\n} {\n // Format: \"diff --git a/<old> b/<new>\"\n // With diff.mnemonicPrefix, git uses i/ w/ c/ o/ instead of a/ b/.\n // Paths may contain spaces, so we find the \" X/\" separator where X is a\n // single-letter prefix.\n const withoutPrefix = line.substring('diff --git '.length);\n\n // Find \" X/\" — the boundary between old and new paths.\n // Try common prefixes: b/ (default), w/ i/ c/ o/ (mnemonic)\n let bIdx = -1;\n for (const prefix of [' b/', ' w/', ' i/', ' c/', ' o/']) {\n bIdx = withoutPrefix.indexOf(prefix);\n if (bIdx !== -1) break;\n }\n\n if (bIdx === -1) {\n return { oldPath: '', newPath: '' };\n }\n\n const oldPath = stripPrefix(withoutPrefix.substring(0, bIdx));\n const newPath = stripPrefix(withoutPrefix.substring(bIdx + 1));\n return { oldPath, newPath };\n}\n","// src/main/xml-serializer.ts\n// Serialize ReviewState to XML and validate against XSD\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { ReviewState, FileReviewState, ReviewComment } from './types';\nimport { validateXML } from 'xmllint-wasm';\n\n// Embed the XSD schema for validation\nconst XSD_SCHEMA = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xs:schema\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:sr=\"urn:self-review:v1\"\n targetNamespace=\"urn:self-review:v1\"\n elementFormDefault=\"qualified\"\n>\n\n <xs:element name=\"review\" type=\"sr:ReviewType\">\n <xs:annotation>\n <xs:documentation>\n Root element of a self-review output file. Contains one file element\n per file in the git diff, including files with no comments.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n\n <xs:complexType name=\"ReviewType\">\n <xs:sequence>\n <xs:element name=\"file\" type=\"sr:FileType\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"timestamp\" type=\"xs:dateTime\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n ISO 8601 timestamp of when the review was completed (window closed).\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"git-diff-args\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The git diff arguments that were passed to self-review on the CLI.\n Example: \"--staged\", \"main..feature-branch\", \"HEAD~3\".\n Present only when reviewing a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"repository\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the repository root where self-review was invoked.\n Present only when reviewing a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"source-path\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the directory being reviewed.\n Present only when reviewing a directory (non-git mode).\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"FileType\">\n <xs:annotation>\n <xs:documentation>\n Represents a single file in the diff. Files with no comments\n appear as empty elements. The path is relative to the repository root.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"comment\" type=\"sr:CommentType\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n File path relative to the repository root. For renamed files,\n this is the new path.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"change-type\" type=\"sr:ChangeTypeEnum\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n The type of change: added, modified, deleted, or renamed.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"viewed\" type=\"xs:boolean\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n Whether the reviewer marked this file as reviewed.\n true = the reviewer looked at this file.\n false = the reviewer did not mark this file as viewed.\n This helps an AI agent distinguish \"reviewed with no comments\"\n from \"not yet reviewed.\"\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"CommentType\">\n <xs:annotation>\n <xs:documentation>\n A review comment. Three forms:\n\n 1. File-level comment: no line attributes present.\n Applies to the file as a whole.\n\n 2. Comment on new/added/context lines: new-line-start and\n new-line-end are present. These reference line numbers in the\n post-change version of the file.\n\n 3. Comment on old/deleted lines: old-line-start and old-line-end\n are present. These reference line numbers in the pre-change\n version of the file.\n\n For single-line comments, start and end are equal.\n Exactly one pair (old or new) should be present for line-level\n comments. Both pairs absent = file-level comment.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"body\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The comment text. May contain markdown formatting.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"category\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n Required category tag for this comment (e.g., \"bug\", \"style\",\n \"nit\", \"question\", \"security\"). Categories are defined in the\n project-level .self-review.yaml configuration. Every comment\n must have a category to help AI agents prioritize and triage\n feedback.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"suggestion\" type=\"sr:SuggestionType\" minOccurs=\"0\">\n <xs:annotation>\n <xs:documentation>\n Optional code replacement proposal. When present, the AI agent\n should replace the original-code with the proposed-code at the\n referenced line range.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"attachment\" type=\"sr:AttachmentType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional image attachment. The path attribute references an image file\n stored in the .self-review-assets/ directory alongside the XML output.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"old-line-start\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Start line number in the pre-change (old) version of the file.\n Use for comments on deleted lines.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"old-line-end\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n End line number (inclusive) in the pre-change (old) version.\n Must be >= old-line-start when both are present.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"new-line-start\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Start line number in the post-change (new) version of the file.\n Use for comments on added or context (unchanged) lines.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"new-line-end\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n End line number (inclusive) in the post-change (new) version.\n Must be >= new-line-start when both are present.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"SuggestionType\">\n <xs:annotation>\n <xs:documentation>\n A code replacement proposal. The original-code is the literal text\n currently at the referenced lines. The proposed-code is what the\n reviewer suggests it should be replaced with. The AI agent can apply\n this by performing a text substitution.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"original-code\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The existing code at the referenced line range, copied verbatim\n from the diff. Used by the AI agent to locate the replacement\n target via text matching.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"proposed-code\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The replacement code proposed by the reviewer. The AI agent\n should substitute original-code with this text.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n\n <xs:complexType name=\"AttachmentType\">\n <xs:annotation>\n <xs:documentation>\n Reference to an image file attached to a review comment. The file is stored\n alongside the XML output in the .self-review-assets/ directory.\n </xs:documentation>\n </xs:annotation>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>Relative path from the XML file to the image file.</xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"media-type\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>MIME type of the image (e.g., image/png, image/jpeg).</xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:simpleType name=\"ChangeTypeEnum\">\n <xs:annotation>\n <xs:documentation>\n The type of change a file underwent in the diff.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"added\">\n <xs:annotation>\n <xs:documentation>New file that did not exist before.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"modified\">\n <xs:annotation>\n <xs:documentation>Existing file with content changes.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"deleted\">\n <xs:annotation>\n <xs:documentation>File was removed.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"renamed\">\n <xs:annotation>\n <xs:documentation>File was moved or renamed, with or without content changes.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n</xs:schema>`;\n\nfunction extFromMediaType(mediaType: string): string {\n const map: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n };\n return map[mediaType] || 'png';\n}\n\nfunction writeAttachments(state: ReviewState, outputFilePath: string): ReviewState {\n const assetDir = path.join(path.dirname(outputFilePath), '.self-review-assets');\n let hasAttachments = false;\n\n const updatedFiles = state.files.map(file => ({\n ...file,\n comments: file.comments.map(comment => {\n if (!comment.attachments?.length) return comment;\n\n const updatedAttachments = comment.attachments.map((att, index) => {\n if (!att.data) return att;\n hasAttachments = true;\n\n const ext = extFromMediaType(att.mediaType);\n const fileName = `${comment.id}-${index}.${ext}`;\n const relativePath = `.self-review-assets/${fileName}`;\n\n if (!fs.existsSync(assetDir)) {\n fs.mkdirSync(assetDir, { recursive: true });\n }\n fs.writeFileSync(path.join(assetDir, fileName), Buffer.from(att.data));\n\n return { ...att, fileName: relativePath, data: undefined };\n });\n\n return { ...comment, attachments: updatedAttachments };\n }),\n }));\n\n if (hasAttachments) {\n console.error(`[main] Wrote attachment files to ${assetDir}`);\n }\n\n return { ...state, files: updatedFiles };\n}\n\nexport async function serializeReview(state: ReviewState, outputFilePath: string): Promise<string> {\n const processedState = writeAttachments(state, outputFilePath);\n const xml = buildXml(processedState);\n\n // Validate the XML against the XSD\n try {\n const validationResult = await validateXML({\n xml: [{ fileName: 'review.xml', contents: xml }],\n schema: [{ fileName: 'self-review-v1.xsd', contents: XSD_SCHEMA }],\n });\n\n if (!validationResult.valid) {\n const errors = validationResult.errors || [];\n console.error('XML validation failed:');\n errors.forEach((err: unknown) => console.error(` ${err}`));\n throw new Error('Generated XML does not conform to schema');\n }\n } catch (error) {\n // Re-throw if it's a schema validation failure (our own throw above)\n if (error instanceof Error && error.message === 'Generated XML does not conform to schema') {\n throw error;\n }\n // Infrastructure failure (e.g. WASM load): log warning and return XML anyway\n if (error instanceof Error) {\n console.error(`[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`);\n } else {\n console.error('[main] XML validation infrastructure failed - emitting XML without validation');\n }\n return xml;\n }\n\n return xml;\n}\n\nfunction buildSourceAttributes(state: ReviewState): string {\n const source = state.source;\n if (source.type === 'git') {\n return ` git-diff-args=\"${escapeXml(source.gitDiffArgs)}\" repository=\"${escapeXml(source.repository)}\"`;\n }\n if (source.type === 'directory' || source.type === 'file') {\n return ` source-path=\"${escapeXml(source.sourcePath)}\"`;\n }\n // welcome mode: no source attributes\n return '';\n}\n\nfunction buildXml(state: ReviewState): string {\n const lines: string[] = [];\n\n // XML declaration\n lines.push('<?xml version=\"1.0\" encoding=\"UTF-8\"?>');\n\n // Root element with namespace\n const sourceAttrs = buildSourceAttributes(state);\n lines.push(\n `<review xmlns=\"urn:self-review:v1\" timestamp=\"${escapeXml(state.timestamp)}\"${sourceAttrs}>`\n );\n\n // Files\n for (const file of state.files) {\n lines.push(...buildFileXml(file));\n }\n\n // Close root element\n lines.push('</review>');\n\n return lines.join('\\n');\n}\n\nfunction buildFileXml(file: FileReviewState): string[] {\n const lines: string[] = [];\n\n if (file.comments.length === 0) {\n // Self-closing tag for files with no comments\n lines.push(\n ` <file path=\"${escapeXml(file.path)}\" change-type=\"${file.changeType}\" viewed=\"${file.viewed}\" />`\n );\n } else {\n // Opening tag\n lines.push(\n ` <file path=\"${escapeXml(file.path)}\" change-type=\"${file.changeType}\" viewed=\"${file.viewed}\">`\n );\n\n // Comments\n for (const comment of file.comments) {\n lines.push(...buildCommentXml(comment));\n }\n\n // Closing tag\n lines.push(' </file>');\n }\n\n return lines;\n}\n\nfunction buildCommentXml(comment: ReviewComment): string[] {\n const lines: string[] = [];\n const attrs: string[] = [];\n\n // Add line attributes\n if (comment.lineRange) {\n if (comment.lineRange.side === 'old') {\n attrs.push(`old-line-start=\"${comment.lineRange.start}\"`);\n attrs.push(`old-line-end=\"${comment.lineRange.end}\"`);\n } else {\n attrs.push(`new-line-start=\"${comment.lineRange.start}\"`);\n attrs.push(`new-line-end=\"${comment.lineRange.end}\"`);\n }\n }\n\n const attrStr = attrs.length > 0 ? ' ' + attrs.join(' ') : '';\n\n // Opening tag\n lines.push(` <comment${attrStr}>`);\n\n // Body (preserve whitespace and newlines)\n lines.push(` <body>${escapeXml(comment.body)}</body>`);\n\n // Category (required)\n lines.push(` <category>${escapeXml(comment.category)}</category>`);\n\n // Suggestion\n if (comment.suggestion) {\n lines.push(' <suggestion>');\n lines.push(\n ` <original-code>${escapeXml(comment.suggestion.originalCode)}</original-code>`\n );\n lines.push(\n ` <proposed-code>${escapeXml(comment.suggestion.proposedCode)}</proposed-code>`\n );\n lines.push(' </suggestion>');\n }\n\n // Attachments\n if (comment.attachments?.length) {\n for (const att of comment.attachments) {\n lines.push(` <attachment path=\"${escapeXml(att.fileName)}\" media-type=\"${escapeXml(att.mediaType)}\" />`);\n }\n }\n\n // Closing tag\n lines.push(' </comment>');\n\n return lines;\n}\n\nfunction escapeXml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\n}\n","// src/main/xml-parser.ts\n// Parse XML review file back into ReviewComment[]\n\nimport { readFileSync } from 'fs';\nimport { XMLParser } from 'fast-xml-parser';\nimport { ReviewComment, Suggestion, LineRange, DiffSource } from './types';\n\nexport interface ParsedReview {\n comments: ReviewComment[];\n gitDiffArgs: string;\n source: DiffSource;\n}\n\nexport function parseReviewXml(xmlPath: string): ParsedReview {\n try {\n const xmlContent = readFileSync(xmlPath, 'utf-8');\n return parseReviewXmlString(xmlContent);\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error reading XML file: ${error.message}`);\n } else {\n console.error('Error reading XML file: unknown error');\n }\n process.exit(1);\n }\n}\n\nexport function parseReviewXmlString(xmlContent: string): ParsedReview {\n const parser = new XMLParser({\n ignoreAttributes: false,\n attributeNamePrefix: '@_',\n allowBooleanAttributes: true,\n });\n\n try {\n const result = parser.parse(xmlContent);\n\n if (!result.review) {\n throw new Error('Invalid XML: missing <review> root element');\n }\n\n const review = result.review;\n const gitDiffArgs = review['@_git-diff-args'] || '';\n const source = parseSource(review);\n const comments: ReviewComment[] = [];\n\n // Handle files array\n const files = Array.isArray(review.file)\n ? review.file\n : review.file\n ? [review.file]\n : [];\n\n for (const file of files) {\n const filePath = file['@_path'];\n if (!filePath) continue;\n\n // Handle comments array\n const fileComments = Array.isArray(file.comment)\n ? file.comment\n : file.comment\n ? [file.comment]\n : [];\n\n for (const comment of fileComments) {\n const reviewComment: ReviewComment = {\n id: generateId(),\n filePath,\n lineRange: parseLineRange(comment),\n body: comment.body || '',\n category: comment.category || '',\n suggestion: parseSuggestion(comment),\n };\n\n // Parse attachments\n const commentAttachments = Array.isArray(comment.attachment)\n ? comment.attachment\n : comment.attachment\n ? [comment.attachment]\n : [];\n\n if (commentAttachments.length > 0) {\n reviewComment.attachments = commentAttachments.map(\n (att: Record<string, unknown>, i: number) => ({\n id: `${reviewComment.id}-att-${i}`,\n fileName: String(att['@_path'] || ''),\n mediaType: String(att['@_media-type'] || 'image/png'),\n })\n );\n }\n\n comments.push(reviewComment);\n }\n }\n\n return { comments, gitDiffArgs, source };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error parsing XML: ${error.message}`);\n } else {\n console.error('Error parsing XML: unknown error');\n }\n process.exit(1);\n }\n}\n\nfunction parseSource(review: Record<string, unknown>): DiffSource {\n const sourcePath = review['@_source-path'];\n if (sourcePath) {\n return { type: 'directory', sourcePath: String(sourcePath) };\n }\n\n const gitDiffArgs = review['@_git-diff-args'];\n const repository = review['@_repository'];\n if (gitDiffArgs !== undefined || repository !== undefined) {\n return {\n type: 'git',\n gitDiffArgs: String(gitDiffArgs || ''),\n repository: String(repository || ''),\n };\n }\n\n return { type: 'welcome' };\n}\n\nfunction parseLineRange(comment: Record<string, unknown>): LineRange | null {\n const hasOld =\n comment['@_old-line-start'] !== undefined &&\n comment['@_old-line-end'] !== undefined;\n const hasNew =\n comment['@_new-line-start'] !== undefined &&\n comment['@_new-line-end'] !== undefined;\n\n if (hasOld) {\n return {\n side: 'old',\n start: parseInt(String(comment['@_old-line-start']), 10),\n end: parseInt(String(comment['@_old-line-end']), 10),\n };\n }\n\n if (hasNew) {\n return {\n side: 'new',\n start: parseInt(String(comment['@_new-line-start']), 10),\n end: parseInt(String(comment['@_new-line-end']), 10),\n };\n }\n\n return null; // File-level comment\n}\n\nfunction parseSuggestion(comment: Record<string, unknown>): Suggestion | null {\n if (!comment.suggestion) {\n return null;\n }\n\n const suggestion = comment.suggestion as Record<string, unknown>;\n return {\n originalCode: String(suggestion['original-code'] || ''),\n proposedCode: String(suggestion['proposed-code'] || ''),\n };\n}\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n}\n","// src/main/git.ts\n// Git command execution\n\nimport { execSync, exec } from 'child_process';\nimport { promisify } from 'util';\nimport { generateSyntheticDiffs } from './synthetic-diff';\n\nconst execAsync = promisify(exec);\n\nexport function runGitDiff(args: string[]): string {\n try {\n // Check if git is available\n try {\n execSync('git --version', { stdio: 'ignore' });\n } catch {\n console.error('Error: git is not installed or not in PATH');\n process.exit(1);\n }\n\n // Check if we're in a git repository\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n } catch {\n console.error(\n 'Error: not a git repository (or any parent up to mount point)'\n );\n process.exit(1);\n }\n\n // Run git diff with the provided arguments\n const result = execSync(`git diff ${args.join(' ')}`, {\n encoding: 'utf-8',\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large diffs\n });\n\n return result;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n process.exit(1);\n }\n}\n\nexport function getRepoRoot(): string {\n try {\n const result = execSync('git rev-parse --show-toplevel', {\n encoding: 'utf-8',\n });\n return result.trim();\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n process.exit(1);\n }\n}\n\n/**\n * Lightweight sync validation - checks if git is available and we're in a repo.\n * Called BEFORE Electron initialization for early exit path.\n */\nexport function validateGitAvailable(): void {\n try {\n execSync('git --version', { stdio: 'ignore' });\n } catch {\n console.error('Error: git is not installed or not in PATH');\n process.exit(1);\n }\n\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n } catch {\n console.error(\n 'Error: not a git repository (or any parent up to mount point)'\n );\n process.exit(1);\n }\n}\n\n/**\n * Async version of getRepoRoot - called AFTER app.whenReady().\n */\nexport async function getRepoRootAsync(cwd?: string): Promise<string> {\n try {\n const { stdout } = await execAsync('git rev-parse --show-toplevel', {\n timeout: 10000, // 10 second timeout\n cwd,\n });\n return stdout.trim();\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Async version of runGitDiff - called AFTER app.whenReady().\n * Uses timeout to prevent hanging in CI environments.\n */\nexport async function runGitDiffAsync(args: string[], cwd?: string): Promise<string> {\n try {\n const { stdout } = await execAsync(`git diff ${args.join(' ')}`, {\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer\n timeout: 30000, // 30 second timeout\n cwd,\n });\n return stdout;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Get list of untracked files (respects .gitignore).\n */\nexport async function getUntrackedFilesAsync(cwd?: string): Promise<string[]> {\n try {\n const { stdout } = await execAsync(\n 'git ls-files --others --exclude-standard',\n {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 10000,\n cwd,\n }\n );\n return stdout\n .trim()\n .split('\\n')\n .filter(line => line.length > 0);\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Warning: Failed to list untracked files: ${error.message}`\n );\n } else {\n console.error('Warning: Failed to list untracked files: unknown error');\n }\n return [];\n }\n}\n\n/**\n * Generate synthetic unified diffs for untracked files so they can be\n * parsed by the existing diff parser.\n *\n * Delegates to the reusable generateSyntheticDiffs module.\n */\nexport function generateUntrackedDiffs(\n paths: string[],\n repoRoot: string\n): string {\n return generateSyntheticDiffs(paths, repoRoot);\n}\n","// src/main/synthetic-diff.ts\n// Generates synthetic unified diffs for files that aren't tracked by git.\n// Reusable by both git untracked file handling and directory-based scanning.\n\nimport { readFileSync } from 'fs';\n\n/**\n * Generate synthetic unified diffs for a list of file paths so they can be\n * parsed by the existing diff parser. Each file is treated as a new addition.\n *\n * @param paths - Relative file paths (e.g. \"src/foo.ts\")\n * @param rootDir - Absolute path to the root directory containing the files\n * @returns A unified diff string covering all provided files\n */\nexport function generateSyntheticDiffs(\n paths: string[],\n rootDir: string\n): string {\n const diffs: string[] = [];\n\n for (const filePath of paths) {\n const fullPath = `${rootDir}/${filePath}`;\n let content: Buffer;\n try {\n content = readFileSync(fullPath);\n } catch {\n // File may have been deleted between listing and reading\n continue;\n }\n\n // Detect binary files by checking for null bytes in the first 8KB\n const sample = content.subarray(0, 8192);\n const isBinary = sample.includes(0);\n\n if (isBinary) {\n diffs.push(\n `diff --git a/${filePath} b/${filePath}\\n` +\n `new file mode 100644\\n` +\n `Binary files /dev/null and b/${filePath} differ`\n );\n continue;\n }\n\n const text = content.toString('utf-8');\n const lines = text.split('\\n');\n\n // Remove trailing empty string from split if file ends with newline\n if (lines.length > 0 && lines[lines.length - 1] === '') {\n lines.pop();\n }\n\n const lineCount = lines.length;\n const addedLines = lines.map(line => `+${line}`).join('\\n');\n\n let diff =\n `diff --git a/${filePath} b/${filePath}\\n` +\n `new file mode 100644\\n` +\n `--- /dev/null\\n` +\n `+++ b/${filePath}\\n` +\n `@@ -0,0 +1,${lineCount} @@\\n` +\n addedLines;\n\n // Indicate missing newline at end of file\n if (text.length > 0 && !text.endsWith('\\n')) {\n diff += '\\n\\\';\n }\n\n diffs.push(diff);\n }\n\n return diffs.join('\\n');\n}\n","// src/main/directory-scanner.ts\n// Recursively scans a directory and produces DiffFile[] treating all files as new additions.\n\nimport { readdir, stat } from 'fs/promises';\nimport { join, relative, basename, dirname } from 'path';\nimport { DiffFile } from './types';\nimport { generateSyntheticDiffs } from './synthetic-diff';\nimport { parseDiff } from './diff-parser';\nimport { createIgnoreFilter } from './ignore-filter';\n\n/**\n * Recursively scan a directory and return DiffFile[] with every file\n * treated as a new addition (changeType: 'added').\n *\n * @param directoryPath - Absolute path to the directory to scan\n * @param ignorePatterns - Optional gitignore-compatible patterns to exclude files\n * @returns Parsed DiffFile array for all files in the directory\n */\nexport async function scanDirectory(\n directoryPath: string,\n ignorePatterns: string[] = []\n): Promise<DiffFile[]> {\n // Verify the path is a directory\n try {\n const dirStat = await stat(directoryPath);\n if (!dirStat.isDirectory()) {\n console.error(\n `Error: \"${directoryPath}\" is not a directory`\n );\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Error accessing directory \"${directoryPath}\": ${error.message}`\n );\n } else {\n console.error(\n `Error accessing directory \"${directoryPath}\": unknown error`\n );\n }\n return [];\n }\n\n const filePaths: string[] = [];\n\n try {\n const entries = await readdir(directoryPath, {\n recursive: true,\n withFileTypes: true,\n });\n\n for (const entry of entries) {\n if (!entry.isFile()) {\n continue;\n }\n\n // Build the full path from the entry's parentPath (or path) and name\n const parentDir = entry.parentPath ?? entry.path;\n const fullPath = join(parentDir, entry.name);\n const relativePath = relative(directoryPath, fullPath);\n filePaths.push(relativePath);\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Error reading directory \"${directoryPath}\": ${error.message}`\n );\n } else {\n console.error(\n `Error reading directory \"${directoryPath}\": unknown error`\n );\n }\n return [];\n }\n\n // Sort for deterministic output\n filePaths.sort();\n\n // Apply ignore patterns\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n const filteredPaths = filePaths.filter(p => shouldKeep(p));\n\n if (filteredPaths.length === 0) {\n return [];\n }\n\n const diffText = generateSyntheticDiffs(filteredPaths, directoryPath);\n return parseDiff(diffText);\n}\n\n/**\n * Scan a single file and return DiffFile[] with the file treated as a new addition.\n *\n * @param filePath - Absolute path to the file to scan\n * @returns Parsed DiffFile array (single element)\n */\nexport async function scanFile(filePath: string): Promise<DiffFile[]> {\n try {\n const fileStat = await stat(filePath);\n if (!fileStat.isFile()) {\n console.error(`Error: \"${filePath}\" is not a file`);\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error accessing file \"${filePath}\": ${error.message}`);\n } else {\n console.error(`Error accessing file \"${filePath}\": unknown error`);\n }\n return [];\n }\n\n const fileName = basename(filePath);\n const rootDir = dirname(filePath);\n const diffText = generateSyntheticDiffs([fileName], rootDir);\n return parseDiff(diffText);\n}\n","// src/main/ignore-filter.ts\n// Gitignore-compatible file path filtering using the `ignore` package.\n\nimport ignore from 'ignore';\n\n/**\n * Create a filter function from gitignore-compatible patterns.\n *\n * @param patterns - Array of gitignore-compatible glob patterns\n * @returns A predicate that returns `true` if the path should be kept (not ignored)\n */\nexport function createIgnoreFilter(\n patterns: string[]\n): (path: string) => boolean {\n if (patterns.length === 0) return () => true;\n const ig = ignore().add(patterns);\n return (filePath: string) => !ig.ignores(filePath);\n}\n","// src/main/config.ts\n// YAML configuration loading and merging\n\nimport { readFileSync, existsSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { parse as parseYaml } from 'yaml';\nimport { AppConfig } from './types';\n\nconst defaults: AppConfig = {\n theme: 'system',\n diffView: 'split',\n fontSize: 14,\n outputFormat: 'xml',\n outputFile: './review.xml',\n ignore: [\n '.git',\n 'node_modules',\n 'vendor',\n '.vendor',\n '__pycache__',\n '.venv',\n 'venv',\n '.env',\n 'dist',\n 'build',\n '.next',\n '.nuxt',\n '.svelte-kit',\n 'target',\n '*.min.js',\n '*.min.css',\n 'package-lock.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'composer.lock',\n 'Gemfile.lock',\n 'Cargo.lock',\n 'poetry.lock',\n 'go.sum',\n ],\n categories: [\n {\n name: 'question',\n description: 'Clarification needed — not necessarily a problem',\n color: '#805ad5',\n },\n {\n name: 'bug',\n description: 'Likely defect or incorrect behavior',\n color: '#e53e3e',\n },\n {\n name: 'security',\n description: 'Security vulnerability or concern',\n color: '#dd6b20',\n },\n {\n name: 'style',\n description: 'Code style, naming, or formatting issue',\n color: '#3182ce',\n },\n {\n name: 'task',\n description: 'Action item or follow-up task',\n color: '#38a169',\n },\n {\n name: 'nit',\n description: 'Minor nitpick, low priority',\n color: '#718096',\n },\n ],\n defaultDiffArgs: '',\n showUntracked: true,\n wordWrap: true,\n maxFiles: 500,\n maxTotalLines: 100000,\n};\n\nexport function loadConfig(): AppConfig {\n let config = { ...defaults };\n\n // Load user-level config\n const userConfigPath = join(\n homedir(),\n '.config',\n 'self-review',\n 'config.yaml'\n );\n if (existsSync(userConfigPath)) {\n try {\n const userConfig = loadYamlConfig(userConfigPath);\n config = mergeConfig(config, userConfig);\n } catch (error) {\n console.error(\n `Warning: Failed to load user config from ${userConfigPath}: ${error}`\n );\n }\n }\n\n // Load project-level config\n const projectConfigPath = join(process.cwd(), '.self-review.yaml');\n if (existsSync(projectConfigPath)) {\n try {\n const projectConfig = loadYamlConfig(projectConfigPath);\n config = mergeConfig(config, projectConfig);\n } catch (error) {\n console.error(\n `Warning: Failed to load project config from ${projectConfigPath}: ${error}`\n );\n }\n }\n\n return config;\n}\n\nfunction loadYamlConfig(path: string): Partial<AppConfig> {\n const content = readFileSync(path, 'utf-8');\n const raw = parseYaml(content);\n\n if (!raw || typeof raw !== 'object') {\n throw new Error('Invalid YAML format');\n }\n\n // Map kebab-case keys to camelCase\n const config: Partial<AppConfig> = {};\n\n if ('theme' in raw) {\n if (['light', 'dark', 'system'].includes(raw.theme)) {\n config.theme = raw.theme;\n } else {\n console.error(\n `Warning: Invalid theme value \"${raw.theme}\", using default`\n );\n }\n }\n\n if ('diff-view' in raw) {\n if (['split', 'unified'].includes(raw['diff-view'])) {\n config.diffView = raw['diff-view'];\n } else {\n console.error(\n `Warning: Invalid diff-view value \"${raw['diff-view']}\", using default`\n );\n }\n }\n\n if ('font-size' in raw && typeof raw['font-size'] === 'number') {\n config.fontSize = raw['font-size'];\n }\n\n if ('output-format' in raw && typeof raw['output-format'] === 'string') {\n config.outputFormat = raw['output-format'];\n }\n\n if ('ignore' in raw && Array.isArray(raw.ignore)) {\n config.ignore = raw.ignore.filter(\n (item: unknown) => typeof item === 'string'\n );\n }\n\n if ('categories' in raw && Array.isArray(raw.categories)) {\n config.categories = raw.categories.filter(\n (cat: unknown): cat is { name: string; description: string; color: string } =>\n cat !== null &&\n typeof cat === 'object' &&\n typeof (cat as Record<string, unknown>).name === 'string' &&\n typeof (cat as Record<string, unknown>).description === 'string' &&\n typeof (cat as Record<string, unknown>).color === 'string'\n );\n }\n\n if (\n 'default-diff-args' in raw &&\n typeof raw['default-diff-args'] === 'string'\n ) {\n config.defaultDiffArgs = raw['default-diff-args'];\n }\n\n if ('show-untracked' in raw && typeof raw['show-untracked'] === 'boolean') {\n config.showUntracked = raw['show-untracked'];\n }\n\n if ('word-wrap' in raw && typeof raw['word-wrap'] === 'boolean') {\n config.wordWrap = raw['word-wrap'];\n }\n\n if ('max-files' in raw && typeof raw['max-files'] === 'number') {\n config.maxFiles = raw['max-files'] >= 0 ? raw['max-files'] : defaults.maxFiles;\n }\n\n if ('max-total-lines' in raw && typeof raw['max-total-lines'] === 'number') {\n config.maxTotalLines = raw['max-total-lines'] >= 0 ? raw['max-total-lines'] : defaults.maxTotalLines;\n }\n\n if (\n 'output-file' in raw &&\n typeof raw['output-file'] === 'string' &&\n raw['output-file'].length > 0\n ) {\n config.outputFile = raw['output-file'];\n }\n\n return config;\n}\n\nfunction mergeConfig(base: AppConfig, override: Partial<AppConfig>): AppConfig {\n return {\n ...base,\n ...override,\n // Arrays are replaced, not merged\n ignore: override.ignore !== undefined ? override.ignore : base.ignore,\n categories:\n override.categories !== undefined ? override.categories : base.categories,\n };\n}\n","// src/main/payload-sizing.ts\n// Payload size estimation and threshold checking for large review guards.\n\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\nimport type { DiffFile, AppConfig, PayloadStats } from './types';\n\nconst execAsync = promisify(exec);\n\n/**\n * Compute payload statistics and check against configured thresholds.\n * A maxFiles or maxTotalLines value of 0 disables that guard.\n */\nexport function computePayloadStats(\n fileCount: number,\n totalLines: number,\n config: AppConfig\n): PayloadStats {\n const maxFiles = config.maxFiles;\n const maxTotalLines = config.maxTotalLines;\n const exceedsFiles = maxFiles > 0 && fileCount > maxFiles;\n const exceedsLines = maxTotalLines > 0 && totalLines > maxTotalLines;\n return {\n fileCount,\n totalLines,\n exceedsFiles,\n exceedsLines,\n exceedsAny: exceedsFiles || exceedsLines,\n };\n}\n\n/**\n * Count total diff lines across all files and hunks.\n */\nexport function countTotalLines(files: DiffFile[]): number {\n let total = 0;\n for (const file of files) {\n for (const hunk of file.hunks) {\n total += hunk.lines.length;\n }\n }\n return total;\n}\n\n/**\n * Get git diff stats cheaply using --numstat (avoids full diff parsing).\n * Each output line is \"added\\tremoved\\tfilename\".\n * Returns file count and total changed lines (added + removed).\n */\nexport async function getGitDiffStats(\n args: string[],\n repoRoot: string\n): Promise<{ fileCount: number; totalLines: number }> {\n try {\n const { stdout } = await execAsync(`git diff --numstat ${args.join(' ')}`, {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 15000,\n cwd: repoRoot,\n });\n\n let fileCount = 0;\n let totalLines = 0;\n\n for (const line of stdout.trim().split('\\n')) {\n if (!line) continue;\n const parts = line.split('\\t');\n if (parts.length < 3) continue;\n\n fileCount++;\n // Binary files show '-' for added/removed\n const added = parts[0] === '-' ? 0 : parseInt(parts[0], 10);\n const removed = parts[1] === '-' ? 0 : parseInt(parts[1], 10);\n totalLines += (isNaN(added) ? 0 : added) + (isNaN(removed) ? 0 : removed);\n }\n\n return { fileCount, totalLines };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`[payload-sizing] Failed to get git diff stats: ${error.message}`);\n } else {\n console.error('[payload-sizing] Failed to get git diff stats: unknown error');\n }\n // Return zeros so the guard does not block on failure\n return { fileCount: 0, totalLines: 0 };\n }\n}\n","// src/main/fs-utils.ts\n// Filesystem utility functions for the main process.\n\nimport { accessSync, constants as fsConstants } from 'fs';\nimport { dirname } from 'path';\n\n/**\n * Check if a file's parent directory is writable.\n * Returns true if the directory exists and the process has write permission,\n * false otherwise (including non-existent directories).\n */\nexport function checkWritability(filePath: string): boolean {\n try {\n const dir = dirname(filePath);\n accessSync(dir, fsConstants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n","const RASTER_IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.ico', '.bmp']);\n\nfunction getExtension(filePath: string): string {\n const lastDot = filePath.lastIndexOf('.');\n if (lastDot === -1 || lastDot === filePath.length - 1) return '';\n return filePath.slice(lastDot).toLowerCase();\n}\n\nexport function isPreviewableImage(filePath: string): boolean {\n return RASTER_IMAGE_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isPreviewableSvg(filePath: string): boolean {\n return getExtension(filePath) === '.svg';\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AC5D,qBAAe,MAAM,KAAK,IAAI,IAAI,UAAU,MAAM,OAAO,IAAI,IAAI;AAAA,IACnE;AAEA,WAAO,EAAE,WAAW,WAAW;AAAA,EACjC,SAAS,OAAO;AACd,QAAI,iBAAiB,OAAO;AAC1B,cAAQ,MAAM,kDAAkD,MAAM,OAAO,EAAE;AAAA,IACjF,OAAO;AACL,cAAQ,MAAM,8DAA8D;AAAA,IAC9E;AAEA,WAAO,EAAE,WAAW,GAAG,YAAY,EAAE;AAAA,EACvC;AACF;;;AClFA,IAAAC,aAAqD;AACrD,IAAAC,eAAwB;AAOjB,SAAS,iBAAiB,UAA2B;AAC1D,MAAI;AACF,UAAM,UAAM,sBAAQ,QAAQ;AAC5B,+BAAW,KAAK,WAAAC,UAAY,IAAI;AAChC,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;ACnBA,IAAM,0BAA0B,oBAAI,IAAI,CAAC,QAAQ,SAAS,QAAQ,QAAQ,SAAS,QAAQ,MAAM,CAAC;AAElG,SAAS,aAAa,UAA0B;AAC9C,QAAM,UAAU,SAAS,YAAY,GAAG;AACxC,MAAI,YAAY,MAAM,YAAY,SAAS,SAAS,EAAG,QAAO;AAC9D,SAAO,SAAS,MAAM,OAAO,EAAE,YAAY;AAC7C;AAEO,SAAS,mBAAmB,UAA2B;AAC5D,SAAO,wBAAwB,IAAI,aAAa,QAAQ,CAAC;AAC3D;AAEO,SAAS,iBAAiB,UAA2B;AAC1D,SAAO,aAAa,QAAQ,MAAM;AACpC;","names":["path","import_fs","ignore","import_fs","import_path","path","parseYaml","import_child_process","import_util","execAsync","import_fs","import_path","fsConstants"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/diff-parser.ts","../src/xml-serializer.ts","../src/xml-parser.ts","../src/git.ts","../src/synthetic-diff.ts","../src/directory-scanner.ts","../src/ignore-filter.ts","../src/config.ts","../src/payload-sizing.ts","../src/fs-utils.ts","../src/file-type-utils.ts"],"sourcesContent":["// @self-review/core — Node.js API for diff parsing, git operations, XML serialization, and configuration\n\n// Types\nexport type {\n ChangeType,\n DiffLineType,\n DiffLine,\n DiffHunk,\n DiffFile,\n DiffSource,\n Suggestion,\n Attachment,\n LineRange,\n ReviewComment,\n FileReviewState,\n ReviewState,\n CategoryDef,\n AppConfig,\n DiffLoadPayload,\n ResumeLoadPayload,\n OutputPathInfo,\n ExpandContextRequest,\n ExpandContextResponse,\n FindInPageRequest,\n FindInPageResult,\n VersionUpdateInfo,\n PayloadStats,\n ImageLoadResult,\n} from './types';\n\n// Diff parsing\nexport { parseDiff } from './diff-parser';\n\n// XML I/O\nexport { serializeReview } from './xml-serializer';\nexport { parseReviewXml, parseReviewXmlString } from './xml-parser';\n\n// Git operations\nexport {\n runGitDiff,\n runGitDiffAsync,\n getRepoRoot,\n getRepoRootAsync,\n getUntrackedFilesAsync,\n validateGitAvailable,\n generateUntrackedDiffs,\n} from './git';\n\n// Synthetic diffs (for non-git files/directories)\nexport { generateSyntheticDiffs } from './synthetic-diff';\n\n// Directory/file scanning\nexport { scanDirectory, scanFile } from './directory-scanner';\n\n// Configuration\nexport { loadConfig } from './config';\n\n// Payload sizing\nexport { computePayloadStats, countTotalLines, getGitDiffStats } from './payload-sizing';\n\n// Ignore filter\nexport { createIgnoreFilter } from './ignore-filter';\n\n// File system utilities\nexport { checkWritability } from './fs-utils';\n\n// File type detection utilities\nexport { isPreviewableImage, isPreviewableSvg, getLanguageFromPath } from './file-type-utils';\n","// src/main/diff-parser.ts\n// Parse unified diff output into DiffFile[]\n\nimport { DiffFile, DiffHunk, ChangeType } from './types';\n\nexport function parseDiff(rawDiff: string): DiffFile[] {\n if (!rawDiff.trim()) {\n return [];\n }\n\n const lines = rawDiff.split('\\n');\n const files: DiffFile[] = [];\n let currentFile: Partial<DiffFile> | null = null;\n let currentHunk: Partial<DiffHunk> | null = null;\n let oldLineNumber = 0;\n let newLineNumber = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n // Start of a new file\n if (line.startsWith('diff --git ')) {\n // Flush the pending hunk into the current file before saving\n if (currentHunk && currentHunk.header && currentFile) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n currentHunk = null;\n }\n\n // Save previous file if exists and has actual changes\n if (\n currentFile &&\n currentFile.oldPath !== undefined &&\n currentFile.newPath !== undefined\n ) {\n // Include files that have hunks, are binary, or are new (empty new files)\n if (\n currentFile.isBinary ||\n (currentFile.hunks && currentFile.hunks.length > 0) ||\n currentFile.changeType === 'added'\n ) {\n files.push(currentFile as DiffFile);\n }\n }\n\n // Extract paths from \"diff --git a/<old> b/<new>\" as fallback\n // for binary files that lack --- / +++ lines\n const gitPaths = parseGitDiffHeader(line);\n\n // Initialize new file\n currentFile = {\n oldPath: gitPaths.oldPath,\n newPath: gitPaths.newPath,\n changeType: 'modified' as ChangeType,\n isBinary: false,\n hunks: [],\n };\n currentHunk = null;\n continue;\n }\n\n if (!currentFile) continue;\n\n // Detect file mode changes\n if (line.startsWith('new file mode')) {\n currentFile.changeType = 'added';\n continue;\n }\n\n if (line.startsWith('deleted file mode')) {\n currentFile.changeType = 'deleted';\n continue;\n }\n\n if (line.startsWith('rename from ')) {\n currentFile.changeType = 'renamed';\n continue;\n }\n\n // Parse old file path\n if (line.startsWith('--- ')) {\n const path = line.substring(4);\n currentFile.oldPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Parse new file path\n if (line.startsWith('+++ ')) {\n const path = line.substring(4);\n currentFile.newPath = path === '/dev/null' ? '' : stripPrefix(path);\n continue;\n }\n\n // Detect binary files\n if (line.startsWith('Binary files ')) {\n currentFile.isBinary = true;\n continue;\n }\n\n // Parse hunk header\n if (line.startsWith('@@')) {\n // Save previous hunk if exists\n if (currentHunk && currentHunk.header) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n\n // Parse hunk header: @@ -oldStart,oldLines +newStart,newLines @@ context\n const match = line.match(\n /@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@(.*)$/\n );\n if (match) {\n const oldStart = parseInt(match[1], 10);\n const oldLines = match[2] ? parseInt(match[2], 10) : 1;\n const newStart = parseInt(match[3], 10);\n const newLines = match[4] ? parseInt(match[4], 10) : 1;\n const _context = match[5];\n\n currentHunk = {\n header: line,\n oldStart,\n oldLines,\n newStart,\n newLines,\n lines: [],\n };\n\n oldLineNumber = oldStart;\n newLineNumber = newStart;\n }\n continue;\n }\n\n // Parse diff lines (must have a current hunk)\n if (currentHunk && currentHunk.lines) {\n if (line.startsWith('+')) {\n // Addition\n currentHunk.lines.push({\n type: 'addition',\n oldLineNumber: null,\n newLineNumber: newLineNumber,\n content: line.substring(1),\n });\n newLineNumber++;\n } else if (line.startsWith('-')) {\n // Deletion\n currentHunk.lines.push({\n type: 'deletion',\n oldLineNumber: oldLineNumber,\n newLineNumber: null,\n content: line.substring(1),\n });\n oldLineNumber++;\n } else if (line.startsWith(' ')) {\n // Context line\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content: line.substring(1),\n });\n oldLineNumber++;\n newLineNumber++;\n } else if (line.startsWith('\\\\')) {\n // \"\\" - ignore\n continue;\n } else {\n // Some other line (could be empty or malformed), treat as context\n if (currentHunk.lines.length > 0) {\n currentHunk.lines.push({\n type: 'context',\n oldLineNumber: oldLineNumber,\n newLineNumber: newLineNumber,\n content: line,\n });\n oldLineNumber++;\n newLineNumber++;\n }\n }\n }\n }\n\n // Save the last hunk and file\n if (currentHunk && currentHunk.header && currentFile) {\n currentFile.hunks!.push(currentHunk as DiffHunk);\n }\n if (\n currentFile &&\n currentFile.oldPath !== undefined &&\n currentFile.newPath !== undefined\n ) {\n // Include files that have hunks, are binary, or are new (empty new files)\n if (\n currentFile.isBinary ||\n (currentFile.hunks && currentFile.hunks.length > 0) ||\n currentFile.changeType === 'added'\n ) {\n files.push(currentFile as DiffFile);\n }\n }\n\n return files;\n}\n\nfunction stripPrefix(path: string): string {\n // Remove single-character prefix (a/, b/, c/, i/, w/, etc.)\n // Git uses a/b by default, but mnemonicPrefix uses c/i/w/o\n if (path.length > 2 && path[1] === '/') {\n return path.substring(2);\n }\n return path;\n}\n\nfunction parseGitDiffHeader(line: string): {\n oldPath: string;\n newPath: string;\n} {\n // Format: \"diff --git a/<old> b/<new>\"\n // With diff.mnemonicPrefix, git uses i/ w/ c/ o/ instead of a/ b/.\n // Paths may contain spaces, so we find the \" X/\" separator where X is a\n // single-letter prefix.\n const withoutPrefix = line.substring('diff --git '.length);\n\n // Find \" X/\" — the boundary between old and new paths.\n // Try common prefixes: b/ (default), w/ i/ c/ o/ (mnemonic)\n let bIdx = -1;\n for (const prefix of [' b/', ' w/', ' i/', ' c/', ' o/']) {\n bIdx = withoutPrefix.indexOf(prefix);\n if (bIdx !== -1) break;\n }\n\n if (bIdx === -1) {\n return { oldPath: '', newPath: '' };\n }\n\n const oldPath = stripPrefix(withoutPrefix.substring(0, bIdx));\n const newPath = stripPrefix(withoutPrefix.substring(bIdx + 1));\n return { oldPath, newPath };\n}\n","// src/main/xml-serializer.ts\n// Serialize ReviewState to XML and validate against XSD\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { ReviewState, FileReviewState, ReviewComment } from './types';\nimport { validateXML } from 'xmllint-wasm';\n\n// Embed the XSD schema for validation\nconst XSD_SCHEMA = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xs:schema\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:sr=\"urn:self-review:v1\"\n targetNamespace=\"urn:self-review:v1\"\n elementFormDefault=\"qualified\"\n>\n\n <xs:element name=\"review\" type=\"sr:ReviewType\">\n <xs:annotation>\n <xs:documentation>\n Root element of a self-review output file. Contains one file element\n per file in the git diff, including files with no comments.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n\n <xs:complexType name=\"ReviewType\">\n <xs:sequence>\n <xs:element name=\"file\" type=\"sr:FileType\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"timestamp\" type=\"xs:dateTime\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n ISO 8601 timestamp of when the review was completed (window closed).\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"git-diff-args\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n The git diff arguments that were passed to self-review on the CLI.\n Example: \"--staged\", \"main..feature-branch\", \"HEAD~3\".\n Present only when reviewing a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"repository\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the repository root where self-review was invoked.\n Present only when reviewing a git diff.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"source-path\" type=\"xs:string\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Absolute path to the directory being reviewed.\n Present only when reviewing a directory (non-git mode).\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"FileType\">\n <xs:annotation>\n <xs:documentation>\n Represents a single file in the diff. Files with no comments\n appear as empty elements. The path is relative to the repository root.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"comment\" type=\"sr:CommentType\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n </xs:sequence>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n File path relative to the repository root. For renamed files,\n this is the new path.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"change-type\" type=\"sr:ChangeTypeEnum\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n The type of change: added, modified, deleted, or renamed.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"viewed\" type=\"xs:boolean\" use=\"required\">\n <xs:annotation>\n <xs:documentation>\n Whether the reviewer marked this file as reviewed.\n true = the reviewer looked at this file.\n false = the reviewer did not mark this file as viewed.\n This helps an AI agent distinguish \"reviewed with no comments\"\n from \"not yet reviewed.\"\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"CommentType\">\n <xs:annotation>\n <xs:documentation>\n A review comment. Three forms:\n\n 1. File-level comment: no line attributes present.\n Applies to the file as a whole.\n\n 2. Comment on new/added/context lines: new-line-start and\n new-line-end are present. These reference line numbers in the\n post-change version of the file.\n\n 3. Comment on old/deleted lines: old-line-start and old-line-end\n are present. These reference line numbers in the pre-change\n version of the file.\n\n For single-line comments, start and end are equal.\n Exactly one pair (old or new) should be present for line-level\n comments. Both pairs absent = file-level comment.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"body\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The comment text. May contain markdown formatting.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"category\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n Required category tag for this comment (e.g., \"bug\", \"style\",\n \"nit\", \"question\", \"security\"). Categories are defined in the\n project-level .self-review.yaml configuration. Every comment\n must have a category to help AI agents prioritize and triage\n feedback.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"suggestion\" type=\"sr:SuggestionType\" minOccurs=\"0\">\n <xs:annotation>\n <xs:documentation>\n Optional code replacement proposal. When present, the AI agent\n should replace the original-code with the proposed-code at the\n referenced line range.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"attachment\" type=\"sr:AttachmentType\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n <xs:annotation>\n <xs:documentation>\n Optional image attachment. The path attribute references an image file\n stored in the .self-review-assets/ directory alongside the XML output.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"old-line-start\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Start line number in the pre-change (old) version of the file.\n Use for comments on deleted lines.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"old-line-end\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n End line number (inclusive) in the pre-change (old) version.\n Must be >= old-line-start when both are present.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"new-line-start\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n Start line number in the post-change (new) version of the file.\n Use for comments on added or context (unchanged) lines.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"new-line-end\" type=\"xs:positiveInteger\" use=\"optional\">\n <xs:annotation>\n <xs:documentation>\n End line number (inclusive) in the post-change (new) version.\n Must be >= new-line-start when both are present.\n </xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:complexType name=\"SuggestionType\">\n <xs:annotation>\n <xs:documentation>\n A code replacement proposal. The original-code is the literal text\n currently at the referenced lines. The proposed-code is what the\n reviewer suggests it should be replaced with. The AI agent can apply\n this by performing a text substitution.\n </xs:documentation>\n </xs:annotation>\n <xs:sequence>\n <xs:element name=\"original-code\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The existing code at the referenced line range, copied verbatim\n from the diff. Used by the AI agent to locate the replacement\n target via text matching.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n <xs:element name=\"proposed-code\" type=\"xs:string\">\n <xs:annotation>\n <xs:documentation>\n The replacement code proposed by the reviewer. The AI agent\n should substitute original-code with this text.\n </xs:documentation>\n </xs:annotation>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n\n <xs:complexType name=\"AttachmentType\">\n <xs:annotation>\n <xs:documentation>\n Reference to an image file attached to a review comment. The file is stored\n alongside the XML output in the .self-review-assets/ directory.\n </xs:documentation>\n </xs:annotation>\n <xs:attribute name=\"path\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>Relative path from the XML file to the image file.</xs:documentation>\n </xs:annotation>\n </xs:attribute>\n <xs:attribute name=\"media-type\" type=\"xs:string\" use=\"required\">\n <xs:annotation>\n <xs:documentation>MIME type of the image (e.g., image/png, image/jpeg).</xs:documentation>\n </xs:annotation>\n </xs:attribute>\n </xs:complexType>\n\n <xs:simpleType name=\"ChangeTypeEnum\">\n <xs:annotation>\n <xs:documentation>\n The type of change a file underwent in the diff.\n </xs:documentation>\n </xs:annotation>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"added\">\n <xs:annotation>\n <xs:documentation>New file that did not exist before.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"modified\">\n <xs:annotation>\n <xs:documentation>Existing file with content changes.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"deleted\">\n <xs:annotation>\n <xs:documentation>File was removed.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n <xs:enumeration value=\"renamed\">\n <xs:annotation>\n <xs:documentation>File was moved or renamed, with or without content changes.</xs:documentation>\n </xs:annotation>\n </xs:enumeration>\n </xs:restriction>\n </xs:simpleType>\n\n</xs:schema>`;\n\nfunction extFromMediaType(mediaType: string): string {\n const map: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n };\n return map[mediaType] || 'png';\n}\n\nfunction writeAttachments(state: ReviewState, outputFilePath: string): ReviewState {\n const assetDir = path.join(path.dirname(outputFilePath), '.self-review-assets');\n let hasAttachments = false;\n\n const updatedFiles = state.files.map(file => ({\n ...file,\n comments: file.comments.map(comment => {\n if (!comment.attachments?.length) return comment;\n\n const updatedAttachments = comment.attachments.map((att, index) => {\n if (!att.data) return att;\n hasAttachments = true;\n\n const ext = extFromMediaType(att.mediaType);\n const fileName = `${comment.id}-${index}.${ext}`;\n const relativePath = `.self-review-assets/${fileName}`;\n\n if (!fs.existsSync(assetDir)) {\n fs.mkdirSync(assetDir, { recursive: true });\n }\n fs.writeFileSync(path.join(assetDir, fileName), Buffer.from(att.data));\n\n return { ...att, fileName: relativePath, data: undefined };\n });\n\n return { ...comment, attachments: updatedAttachments };\n }),\n }));\n\n if (hasAttachments) {\n console.error(`[main] Wrote attachment files to ${assetDir}`);\n }\n\n return { ...state, files: updatedFiles };\n}\n\nexport async function serializeReview(state: ReviewState, outputFilePath: string): Promise<string> {\n const processedState = writeAttachments(state, outputFilePath);\n const xml = buildXml(processedState);\n\n // Validate the XML against the XSD\n try {\n const validationResult = await validateXML({\n xml: [{ fileName: 'review.xml', contents: xml }],\n schema: [{ fileName: 'self-review-v1.xsd', contents: XSD_SCHEMA }],\n });\n\n if (!validationResult.valid) {\n const errors = validationResult.errors || [];\n console.error('XML validation failed:');\n errors.forEach((err: unknown) => console.error(` ${err}`));\n throw new Error('Generated XML does not conform to schema');\n }\n } catch (error) {\n // Re-throw if it's a schema validation failure (our own throw above)\n if (error instanceof Error && error.message === 'Generated XML does not conform to schema') {\n throw error;\n }\n // Infrastructure failure (e.g. WASM load): log warning and return XML anyway\n if (error instanceof Error) {\n console.error(`[main] XML validation infrastructure failed: ${error.message} - emitting XML without validation`);\n } else {\n console.error('[main] XML validation infrastructure failed - emitting XML without validation');\n }\n return xml;\n }\n\n return xml;\n}\n\nfunction buildSourceAttributes(state: ReviewState): string {\n const source = state.source;\n if (source.type === 'git') {\n return ` git-diff-args=\"${escapeXml(source.gitDiffArgs)}\" repository=\"${escapeXml(source.repository)}\"`;\n }\n if (source.type === 'directory' || source.type === 'file') {\n return ` source-path=\"${escapeXml(source.sourcePath)}\"`;\n }\n // welcome mode: no source attributes\n return '';\n}\n\nfunction buildXml(state: ReviewState): string {\n const lines: string[] = [];\n\n // XML declaration\n lines.push('<?xml version=\"1.0\" encoding=\"UTF-8\"?>');\n\n // Root element with namespace\n const sourceAttrs = buildSourceAttributes(state);\n lines.push(\n `<review xmlns=\"urn:self-review:v1\" timestamp=\"${escapeXml(state.timestamp)}\"${sourceAttrs}>`\n );\n\n // Files\n for (const file of state.files) {\n lines.push(...buildFileXml(file));\n }\n\n // Close root element\n lines.push('</review>');\n\n return lines.join('\\n');\n}\n\nfunction buildFileXml(file: FileReviewState): string[] {\n const lines: string[] = [];\n\n if (file.comments.length === 0) {\n // Self-closing tag for files with no comments\n lines.push(\n ` <file path=\"${escapeXml(file.path)}\" change-type=\"${file.changeType}\" viewed=\"${file.viewed}\" />`\n );\n } else {\n // Opening tag\n lines.push(\n ` <file path=\"${escapeXml(file.path)}\" change-type=\"${file.changeType}\" viewed=\"${file.viewed}\">`\n );\n\n // Comments\n for (const comment of file.comments) {\n lines.push(...buildCommentXml(comment));\n }\n\n // Closing tag\n lines.push(' </file>');\n }\n\n return lines;\n}\n\nfunction buildCommentXml(comment: ReviewComment): string[] {\n const lines: string[] = [];\n const attrs: string[] = [];\n\n // Add line attributes\n if (comment.lineRange) {\n if (comment.lineRange.side === 'old') {\n attrs.push(`old-line-start=\"${comment.lineRange.start}\"`);\n attrs.push(`old-line-end=\"${comment.lineRange.end}\"`);\n } else {\n attrs.push(`new-line-start=\"${comment.lineRange.start}\"`);\n attrs.push(`new-line-end=\"${comment.lineRange.end}\"`);\n }\n }\n\n const attrStr = attrs.length > 0 ? ' ' + attrs.join(' ') : '';\n\n // Opening tag\n lines.push(` <comment${attrStr}>`);\n\n // Body (preserve whitespace and newlines)\n lines.push(` <body>${escapeXml(comment.body)}</body>`);\n\n // Category (required)\n lines.push(` <category>${escapeXml(comment.category)}</category>`);\n\n // Suggestion\n if (comment.suggestion) {\n lines.push(' <suggestion>');\n lines.push(\n ` <original-code>${escapeXml(comment.suggestion.originalCode)}</original-code>`\n );\n lines.push(\n ` <proposed-code>${escapeXml(comment.suggestion.proposedCode)}</proposed-code>`\n );\n lines.push(' </suggestion>');\n }\n\n // Attachments\n if (comment.attachments?.length) {\n for (const att of comment.attachments) {\n lines.push(` <attachment path=\"${escapeXml(att.fileName)}\" media-type=\"${escapeXml(att.mediaType)}\" />`);\n }\n }\n\n // Closing tag\n lines.push(' </comment>');\n\n return lines;\n}\n\nfunction escapeXml(str: string): string {\n return str\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\n}\n","// src/main/xml-parser.ts\n// Parse XML review file back into ReviewComment[]\n\nimport { readFileSync } from 'fs';\nimport { XMLParser } from 'fast-xml-parser';\nimport { ReviewComment, Suggestion, LineRange, DiffSource } from './types';\n\nexport interface ParsedReview {\n comments: ReviewComment[];\n gitDiffArgs: string;\n source: DiffSource;\n}\n\nexport function parseReviewXml(xmlPath: string): ParsedReview {\n try {\n const xmlContent = readFileSync(xmlPath, 'utf-8');\n return parseReviewXmlString(xmlContent);\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error reading XML file: ${error.message}`);\n } else {\n console.error('Error reading XML file: unknown error');\n }\n process.exit(1);\n }\n}\n\nexport function parseReviewXmlString(xmlContent: string): ParsedReview {\n const parser = new XMLParser({\n ignoreAttributes: false,\n attributeNamePrefix: '@_',\n allowBooleanAttributes: true,\n });\n\n try {\n const result = parser.parse(xmlContent);\n\n if (!result.review) {\n throw new Error('Invalid XML: missing <review> root element');\n }\n\n const review = result.review;\n const gitDiffArgs = review['@_git-diff-args'] || '';\n const source = parseSource(review);\n const comments: ReviewComment[] = [];\n\n // Handle files array\n const files = Array.isArray(review.file)\n ? review.file\n : review.file\n ? [review.file]\n : [];\n\n for (const file of files) {\n const filePath = file['@_path'];\n if (!filePath) continue;\n\n // Handle comments array\n const fileComments = Array.isArray(file.comment)\n ? file.comment\n : file.comment\n ? [file.comment]\n : [];\n\n for (const comment of fileComments) {\n const reviewComment: ReviewComment = {\n id: generateId(),\n filePath,\n lineRange: parseLineRange(comment),\n body: comment.body || '',\n category: comment.category || '',\n suggestion: parseSuggestion(comment),\n };\n\n // Parse attachments\n const commentAttachments = Array.isArray(comment.attachment)\n ? comment.attachment\n : comment.attachment\n ? [comment.attachment]\n : [];\n\n if (commentAttachments.length > 0) {\n reviewComment.attachments = commentAttachments.map(\n (att: Record<string, unknown>, i: number) => ({\n id: `${reviewComment.id}-att-${i}`,\n fileName: String(att['@_path'] || ''),\n mediaType: String(att['@_media-type'] || 'image/png'),\n })\n );\n }\n\n comments.push(reviewComment);\n }\n }\n\n return { comments, gitDiffArgs, source };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error parsing XML: ${error.message}`);\n } else {\n console.error('Error parsing XML: unknown error');\n }\n process.exit(1);\n }\n}\n\nfunction parseSource(review: Record<string, unknown>): DiffSource {\n const sourcePath = review['@_source-path'];\n if (sourcePath) {\n return { type: 'directory', sourcePath: String(sourcePath) };\n }\n\n const gitDiffArgs = review['@_git-diff-args'];\n const repository = review['@_repository'];\n if (gitDiffArgs !== undefined || repository !== undefined) {\n return {\n type: 'git',\n gitDiffArgs: String(gitDiffArgs || ''),\n repository: String(repository || ''),\n };\n }\n\n return { type: 'welcome' };\n}\n\nfunction parseLineRange(comment: Record<string, unknown>): LineRange | null {\n const hasOld =\n comment['@_old-line-start'] !== undefined &&\n comment['@_old-line-end'] !== undefined;\n const hasNew =\n comment['@_new-line-start'] !== undefined &&\n comment['@_new-line-end'] !== undefined;\n\n if (hasOld) {\n return {\n side: 'old',\n start: parseInt(String(comment['@_old-line-start']), 10),\n end: parseInt(String(comment['@_old-line-end']), 10),\n };\n }\n\n if (hasNew) {\n return {\n side: 'new',\n start: parseInt(String(comment['@_new-line-start']), 10),\n end: parseInt(String(comment['@_new-line-end']), 10),\n };\n }\n\n return null; // File-level comment\n}\n\nfunction parseSuggestion(comment: Record<string, unknown>): Suggestion | null {\n if (!comment.suggestion) {\n return null;\n }\n\n const suggestion = comment.suggestion as Record<string, unknown>;\n return {\n originalCode: String(suggestion['original-code'] || ''),\n proposedCode: String(suggestion['proposed-code'] || ''),\n };\n}\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n}\n","// src/main/git.ts\n// Git command execution\n\nimport { execSync, exec } from 'child_process';\nimport { promisify } from 'util';\nimport { generateSyntheticDiffs } from './synthetic-diff';\n\nconst execAsync = promisify(exec);\n\nexport function runGitDiff(args: string[]): string {\n try {\n // Check if git is available\n try {\n execSync('git --version', { stdio: 'ignore' });\n } catch {\n console.error('Error: git is not installed or not in PATH');\n process.exit(1);\n }\n\n // Check if we're in a git repository\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n } catch {\n console.error(\n 'Error: not a git repository (or any parent up to mount point)'\n );\n process.exit(1);\n }\n\n // Run git diff with the provided arguments\n const result = execSync(`git diff ${args.join(' ')}`, {\n encoding: 'utf-8',\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large diffs\n });\n\n return result;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n process.exit(1);\n }\n}\n\nexport function getRepoRoot(): string {\n try {\n const result = execSync('git rev-parse --show-toplevel', {\n encoding: 'utf-8',\n });\n return result.trim();\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n process.exit(1);\n }\n}\n\n/**\n * Lightweight sync validation - checks if git is available and we're in a repo.\n * Called BEFORE Electron initialization for early exit path.\n */\nexport function validateGitAvailable(): void {\n try {\n execSync('git --version', { stdio: 'ignore' });\n } catch {\n console.error('Error: git is not installed or not in PATH');\n process.exit(1);\n }\n\n try {\n execSync('git rev-parse --git-dir', { stdio: 'ignore' });\n } catch {\n console.error(\n 'Error: not a git repository (or any parent up to mount point)'\n );\n process.exit(1);\n }\n}\n\n/**\n * Async version of getRepoRoot - called AFTER app.whenReady().\n */\nexport async function getRepoRootAsync(cwd?: string): Promise<string> {\n try {\n const { stdout } = await execAsync('git rev-parse --show-toplevel', {\n timeout: 10000, // 10 second timeout\n cwd,\n });\n return stdout.trim();\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error getting repository root: ${error.message}`);\n } else {\n console.error('Error getting repository root: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Async version of runGitDiff - called AFTER app.whenReady().\n * Uses timeout to prevent hanging in CI environments.\n */\nexport async function runGitDiffAsync(args: string[], cwd?: string): Promise<string> {\n try {\n const { stdout } = await execAsync(`git diff ${args.join(' ')}`, {\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer\n timeout: 30000, // 30 second timeout\n cwd,\n });\n return stdout;\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error running git diff: ${error.message}`);\n } else {\n console.error('Error running git diff: unknown error');\n }\n throw error;\n }\n}\n\n/**\n * Get list of untracked files (respects .gitignore).\n */\nexport async function getUntrackedFilesAsync(cwd?: string): Promise<string[]> {\n try {\n const { stdout } = await execAsync(\n 'git ls-files --others --exclude-standard',\n {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 10000,\n cwd,\n }\n );\n return stdout\n .trim()\n .split('\\n')\n .filter(line => line.length > 0);\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Warning: Failed to list untracked files: ${error.message}`\n );\n } else {\n console.error('Warning: Failed to list untracked files: unknown error');\n }\n return [];\n }\n}\n\n/**\n * Generate synthetic unified diffs for untracked files so they can be\n * parsed by the existing diff parser.\n *\n * Delegates to the reusable generateSyntheticDiffs module.\n */\nexport function generateUntrackedDiffs(\n paths: string[],\n repoRoot: string\n): string {\n return generateSyntheticDiffs(paths, repoRoot);\n}\n","// src/main/synthetic-diff.ts\n// Generates synthetic unified diffs for files that aren't tracked by git.\n// Reusable by both git untracked file handling and directory-based scanning.\n\nimport { readFileSync } from 'fs';\n\n/**\n * Generate synthetic unified diffs for a list of file paths so they can be\n * parsed by the existing diff parser. Each file is treated as a new addition.\n *\n * @param paths - Relative file paths (e.g. \"src/foo.ts\")\n * @param rootDir - Absolute path to the root directory containing the files\n * @returns A unified diff string covering all provided files\n */\nexport function generateSyntheticDiffs(\n paths: string[],\n rootDir: string\n): string {\n const diffs: string[] = [];\n\n for (const filePath of paths) {\n const fullPath = `${rootDir}/${filePath}`;\n let content: Buffer;\n try {\n content = readFileSync(fullPath);\n } catch {\n // File may have been deleted between listing and reading\n continue;\n }\n\n // Detect binary files by checking for null bytes in the first 8KB\n const sample = content.subarray(0, 8192);\n const isBinary = sample.includes(0);\n\n if (isBinary) {\n diffs.push(\n `diff --git a/${filePath} b/${filePath}\\n` +\n `new file mode 100644\\n` +\n `Binary files /dev/null and b/${filePath} differ`\n );\n continue;\n }\n\n const text = content.toString('utf-8');\n const lines = text.split('\\n');\n\n // Remove trailing empty string from split if file ends with newline\n if (lines.length > 0 && lines[lines.length - 1] === '') {\n lines.pop();\n }\n\n const lineCount = lines.length;\n const addedLines = lines.map(line => `+${line}`).join('\\n');\n\n let diff =\n `diff --git a/${filePath} b/${filePath}\\n` +\n `new file mode 100644\\n` +\n `--- /dev/null\\n` +\n `+++ b/${filePath}\\n` +\n `@@ -0,0 +1,${lineCount} @@\\n` +\n addedLines;\n\n // Indicate missing newline at end of file\n if (text.length > 0 && !text.endsWith('\\n')) {\n diff += '\\n\\\';\n }\n\n diffs.push(diff);\n }\n\n return diffs.join('\\n');\n}\n","// src/main/directory-scanner.ts\n// Recursively scans a directory and produces DiffFile[] treating all files as new additions.\n\nimport { readdir, stat } from 'fs/promises';\nimport { join, relative, basename, dirname } from 'path';\nimport { DiffFile } from './types';\nimport { generateSyntheticDiffs } from './synthetic-diff';\nimport { parseDiff } from './diff-parser';\nimport { createIgnoreFilter } from './ignore-filter';\n\n/**\n * Recursively scan a directory and return DiffFile[] with every file\n * treated as a new addition (changeType: 'added').\n *\n * @param directoryPath - Absolute path to the directory to scan\n * @param ignorePatterns - Optional gitignore-compatible patterns to exclude files\n * @returns Parsed DiffFile array for all files in the directory\n */\nexport async function scanDirectory(\n directoryPath: string,\n ignorePatterns: string[] = []\n): Promise<DiffFile[]> {\n // Verify the path is a directory\n try {\n const dirStat = await stat(directoryPath);\n if (!dirStat.isDirectory()) {\n console.error(\n `Error: \"${directoryPath}\" is not a directory`\n );\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Error accessing directory \"${directoryPath}\": ${error.message}`\n );\n } else {\n console.error(\n `Error accessing directory \"${directoryPath}\": unknown error`\n );\n }\n return [];\n }\n\n const filePaths: string[] = [];\n\n try {\n const entries = await readdir(directoryPath, {\n recursive: true,\n withFileTypes: true,\n });\n\n for (const entry of entries) {\n if (!entry.isFile()) {\n continue;\n }\n\n // Build the full path from the entry's parentPath (or path) and name\n const parentDir = entry.parentPath ?? entry.path;\n const fullPath = join(parentDir, entry.name);\n const relativePath = relative(directoryPath, fullPath);\n filePaths.push(relativePath);\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(\n `Error reading directory \"${directoryPath}\": ${error.message}`\n );\n } else {\n console.error(\n `Error reading directory \"${directoryPath}\": unknown error`\n );\n }\n return [];\n }\n\n // Sort for deterministic output\n filePaths.sort();\n\n // Apply ignore patterns\n const shouldKeep = createIgnoreFilter(ignorePatterns);\n const filteredPaths = filePaths.filter(p => shouldKeep(p));\n\n if (filteredPaths.length === 0) {\n return [];\n }\n\n const diffText = generateSyntheticDiffs(filteredPaths, directoryPath);\n return parseDiff(diffText);\n}\n\n/**\n * Scan a single file and return DiffFile[] with the file treated as a new addition.\n *\n * @param filePath - Absolute path to the file to scan\n * @returns Parsed DiffFile array (single element)\n */\nexport async function scanFile(filePath: string): Promise<DiffFile[]> {\n try {\n const fileStat = await stat(filePath);\n if (!fileStat.isFile()) {\n console.error(`Error: \"${filePath}\" is not a file`);\n return [];\n }\n } catch (error) {\n if (error instanceof Error) {\n console.error(`Error accessing file \"${filePath}\": ${error.message}`);\n } else {\n console.error(`Error accessing file \"${filePath}\": unknown error`);\n }\n return [];\n }\n\n const fileName = basename(filePath);\n const rootDir = dirname(filePath);\n const diffText = generateSyntheticDiffs([fileName], rootDir);\n return parseDiff(diffText);\n}\n","// src/main/ignore-filter.ts\n// Gitignore-compatible file path filtering using the `ignore` package.\n\nimport ignore from 'ignore';\n\n/**\n * Create a filter function from gitignore-compatible patterns.\n *\n * @param patterns - Array of gitignore-compatible glob patterns\n * @returns A predicate that returns `true` if the path should be kept (not ignored)\n */\nexport function createIgnoreFilter(\n patterns: string[]\n): (path: string) => boolean {\n if (patterns.length === 0) return () => true;\n const ig = ignore().add(patterns);\n return (filePath: string) => !ig.ignores(filePath);\n}\n","// src/main/config.ts\n// YAML configuration loading and merging\n\nimport { readFileSync, existsSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\nimport { parse as parseYaml } from 'yaml';\nimport { AppConfig } from './types';\n\nconst defaults: AppConfig = {\n theme: 'system',\n diffView: 'split',\n fontSize: 14,\n outputFormat: 'xml',\n outputFile: './review.xml',\n ignore: [\n '.git',\n 'node_modules',\n 'vendor',\n '.vendor',\n '__pycache__',\n '.venv',\n 'venv',\n '.env',\n 'dist',\n 'build',\n '.next',\n '.nuxt',\n '.svelte-kit',\n 'target',\n '*.min.js',\n '*.min.css',\n 'package-lock.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'composer.lock',\n 'Gemfile.lock',\n 'Cargo.lock',\n 'poetry.lock',\n 'go.sum',\n ],\n categories: [\n {\n name: 'question',\n description: 'Clarification needed — not necessarily a problem',\n color: '#805ad5',\n },\n {\n name: 'bug',\n description: 'Likely defect or incorrect behavior',\n color: '#e53e3e',\n },\n {\n name: 'security',\n description: 'Security vulnerability or concern',\n color: '#dd6b20',\n },\n {\n name: 'style',\n description: 'Code style, naming, or formatting issue',\n color: '#3182ce',\n },\n {\n name: 'task',\n description: 'Action item or follow-up task',\n color: '#38a169',\n },\n {\n name: 'nit',\n description: 'Minor nitpick, low priority',\n color: '#718096',\n },\n ],\n defaultDiffArgs: '',\n showUntracked: true,\n wordWrap: true,\n maxFiles: 500,\n maxTotalLines: 100000,\n};\n\nexport function loadConfig(): AppConfig {\n let config = { ...defaults };\n\n // Load user-level config\n const userConfigPath = join(\n homedir(),\n '.config',\n 'self-review',\n 'config.yaml'\n );\n if (existsSync(userConfigPath)) {\n try {\n const userConfig = loadYamlConfig(userConfigPath);\n config = mergeConfig(config, userConfig);\n } catch (error) {\n console.error(\n `Warning: Failed to load user config from ${userConfigPath}: ${error}`\n );\n }\n }\n\n // Load project-level config\n const projectConfigPath = join(process.cwd(), '.self-review.yaml');\n if (existsSync(projectConfigPath)) {\n try {\n const projectConfig = loadYamlConfig(projectConfigPath);\n config = mergeConfig(config, projectConfig);\n } catch (error) {\n console.error(\n `Warning: Failed to load project config from ${projectConfigPath}: ${error}`\n );\n }\n }\n\n return config;\n}\n\nfunction loadYamlConfig(path: string): Partial<AppConfig> {\n const content = readFileSync(path, 'utf-8');\n const raw = parseYaml(content);\n\n if (!raw || typeof raw !== 'object') {\n throw new Error('Invalid YAML format');\n }\n\n // Map kebab-case keys to camelCase\n const config: Partial<AppConfig> = {};\n\n if ('theme' in raw) {\n if (['light', 'dark', 'system'].includes(raw.theme)) {\n config.theme = raw.theme;\n } else {\n console.error(\n `Warning: Invalid theme value \"${raw.theme}\", using default`\n );\n }\n }\n\n if ('diff-view' in raw) {\n if (['split', 'unified'].includes(raw['diff-view'])) {\n config.diffView = raw['diff-view'];\n } else {\n console.error(\n `Warning: Invalid diff-view value \"${raw['diff-view']}\", using default`\n );\n }\n }\n\n if ('font-size' in raw && typeof raw['font-size'] === 'number') {\n config.fontSize = raw['font-size'];\n }\n\n if ('output-format' in raw && typeof raw['output-format'] === 'string') {\n config.outputFormat = raw['output-format'];\n }\n\n if ('ignore' in raw && Array.isArray(raw.ignore)) {\n config.ignore = raw.ignore.filter(\n (item: unknown) => typeof item === 'string'\n );\n }\n\n if ('categories' in raw && Array.isArray(raw.categories)) {\n config.categories = raw.categories.filter(\n (cat: unknown): cat is { name: string; description: string; color: string } =>\n cat !== null &&\n typeof cat === 'object' &&\n typeof (cat as Record<string, unknown>).name === 'string' &&\n typeof (cat as Record<string, unknown>).description === 'string' &&\n typeof (cat as Record<string, unknown>).color === 'string'\n );\n }\n\n if (\n 'default-diff-args' in raw &&\n typeof raw['default-diff-args'] === 'string'\n ) {\n config.defaultDiffArgs = raw['default-diff-args'];\n }\n\n if ('show-untracked' in raw && typeof raw['show-untracked'] === 'boolean') {\n config.showUntracked = raw['show-untracked'];\n }\n\n if ('word-wrap' in raw && typeof raw['word-wrap'] === 'boolean') {\n config.wordWrap = raw['word-wrap'];\n }\n\n if ('max-files' in raw && typeof raw['max-files'] === 'number') {\n config.maxFiles = raw['max-files'] >= 0 ? raw['max-files'] : defaults.maxFiles;\n }\n\n if ('max-total-lines' in raw && typeof raw['max-total-lines'] === 'number') {\n config.maxTotalLines = raw['max-total-lines'] >= 0 ? raw['max-total-lines'] : defaults.maxTotalLines;\n }\n\n if (\n 'output-file' in raw &&\n typeof raw['output-file'] === 'string' &&\n raw['output-file'].length > 0\n ) {\n config.outputFile = raw['output-file'];\n }\n\n return config;\n}\n\nfunction mergeConfig(base: AppConfig, override: Partial<AppConfig>): AppConfig {\n return {\n ...base,\n ...override,\n // Arrays are replaced, not merged\n ignore: override.ignore !== undefined ? override.ignore : base.ignore,\n categories:\n override.categories !== undefined ? override.categories : base.categories,\n };\n}\n","// src/main/payload-sizing.ts\n// Payload size estimation and threshold checking for large review guards.\n\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\nimport type { DiffFile, AppConfig, PayloadStats } from './types';\n\nconst execAsync = promisify(exec);\n\n/**\n * Compute payload statistics and check against configured thresholds.\n * A maxFiles or maxTotalLines value of 0 disables that guard.\n */\nexport function computePayloadStats(\n fileCount: number,\n totalLines: number,\n config: AppConfig\n): PayloadStats {\n const maxFiles = config.maxFiles;\n const maxTotalLines = config.maxTotalLines;\n const exceedsFiles = maxFiles > 0 && fileCount > maxFiles;\n const exceedsLines = maxTotalLines > 0 && totalLines > maxTotalLines;\n return {\n fileCount,\n totalLines,\n exceedsFiles,\n exceedsLines,\n exceedsAny: exceedsFiles || exceedsLines,\n };\n}\n\n/**\n * Count total diff lines across all files and hunks.\n */\nexport function countTotalLines(files: DiffFile[]): number {\n let total = 0;\n for (const file of files) {\n for (const hunk of file.hunks) {\n total += hunk.lines.length;\n }\n }\n return total;\n}\n\n/**\n * Get git diff stats cheaply using --numstat (avoids full diff parsing).\n * Each output line is \"added\\tremoved\\tfilename\".\n * Returns file count and total changed lines (added + removed).\n */\nexport async function getGitDiffStats(\n args: string[],\n repoRoot: string\n): Promise<{ fileCount: number; totalLines: number }> {\n try {\n const { stdout } = await execAsync(`git diff --numstat ${args.join(' ')}`, {\n maxBuffer: 10 * 1024 * 1024,\n timeout: 15000,\n cwd: repoRoot,\n });\n\n let fileCount = 0;\n let totalLines = 0;\n\n for (const line of stdout.trim().split('\\n')) {\n if (!line) continue;\n const parts = line.split('\\t');\n if (parts.length < 3) continue;\n\n fileCount++;\n // Binary files show '-' for added/removed\n const added = parts[0] === '-' ? 0 : parseInt(parts[0], 10);\n const removed = parts[1] === '-' ? 0 : parseInt(parts[1], 10);\n totalLines += (isNaN(added) ? 0 : added) + (isNaN(removed) ? 0 : removed);\n }\n\n return { fileCount, totalLines };\n } catch (error) {\n if (error instanceof Error) {\n console.error(`[payload-sizing] Failed to get git diff stats: ${error.message}`);\n } else {\n console.error('[payload-sizing] Failed to get git diff stats: unknown error');\n }\n // Return zeros so the guard does not block on failure\n return { fileCount: 0, totalLines: 0 };\n }\n}\n","// src/main/fs-utils.ts\n// Filesystem utility functions for the main process.\n\nimport { accessSync, constants as fsConstants } from 'fs';\nimport { dirname } from 'path';\n\n/**\n * Check if a file's parent directory is writable.\n * Returns true if the directory exists and the process has write permission,\n * false otherwise (including non-existent directories).\n */\nexport function checkWritability(filePath: string): boolean {\n try {\n const dir = dirname(filePath);\n accessSync(dir, fsConstants.W_OK);\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * File-type detection utilities.\n *\n * NOTE: This file is intentionally duplicated in packages/react/src/utils/file-type-utils.ts.\n * @self-review/core has Node-only dependencies, so @self-review/react cannot safely import\n * from this package. Both copies must be kept in sync.\n */\n\nconst RASTER_IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.ico', '.bmp']);\n\nfunction getExtension(filePath: string): string {\n const lastDot = filePath.lastIndexOf('.');\n if (lastDot === -1 || lastDot === filePath.length - 1) return '';\n return filePath.slice(lastDot).toLowerCase();\n}\n\nexport function isPreviewableImage(filePath: string): boolean {\n return RASTER_IMAGE_EXTENSIONS.has(getExtension(filePath));\n}\n\nexport function isPreviewableSvg(filePath: string): boolean {\n return getExtension(filePath) === '.svg';\n}\n\nexport function getLanguageFromPath(filePath: string): string {\n const ext = filePath.split('.').pop()?.toLowerCase() || '';\n const langMap: Record<string, string> = {\n ts: 'typescript',\n tsx: 'tsx',\n js: 'javascript',\n jsx: 'jsx',\n py: 'python',\n css: 'css',\n json: 'json',\n md: 'markdown',\n sh: 'bash',\n bash: 'bash',\n yml: 'yaml',\n yaml: 'yaml',\n java: 'java',\n go: 'go',\n rs: 'rust',\n sql: 'sql',\n html: 'markup',\n xml: 'markup',\n rb: 'ruby',\n php: 'php',\n twig: 'twig',\n c: 'c',\n cpp: 'cpp',\n h: 'c',\n hpp: 'cpp',\n // Config and data formats\n ini: 'ini',\n toml: 'toml',\n csv: 'csv',\n diff: 'diff',\n patch: 'diff',\n // Web and infrastructure\n scss: 'scss',\n sass: 'sass',\n graphql: 'graphql',\n gql: 'graphql',\n conf: 'nginx',\n // Database\n mongodb: 'mongodb',\n // Tooling\n makefile: 'makefile',\n mk: 'makefile',\n mak: 'makefile',\n vim: 'vim',\n vimrc: 'vim',\n };\n\n // Check for special filenames without extensions\n const filename = filePath.split('/').pop()?.toLowerCase() || '';\n if (filename === 'dockerfile' || filename.startsWith('dockerfile.')) {\n return 'docker';\n }\n if (filename === 'makefile' || filename.startsWith('makefile.')) {\n return 'makefile';\n }\n if (filename.startsWith('.git')) {\n return 'git';\n }\n if (filename === '.vimrc' || filename.startsWith('.vim')) {\n return 'vim';\n }\n\n return langMap[ext] || 'pl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UAAkC;AAAA,IACtC,IAAI;AAAA,IACJ,KAAK;AAAA,IACL,IAAI;AAAA,IACJ,KAAK;AAAA,IACL,IAAI;AAAA,IACJ,KAAK;AAAA,IACL,MAAM;AAAA,IACN,IAAI;AAAA,IACJ,IAAI;AAAA,IACJ,MAAM;AAAA,IACN,KAAK;AAAA,IACL,MAAM;AAAA,IACN,MAAM;AAAA,IACN,IAAI;AAAA,IACJ,IAAI;AAAA,IACJ,KAAK;AAAA,IACL,MAAM;AAAA,IACN,KAAK;AAAA,IACL,IAAI;AAAA,IACJ,KAAK;AAAA,IACL,MAAM;AAAA,IACN,GAAG;AAAA,IACH,KAAK;AAAA,IACL,GAAG;AAAA,IACH,KAAK;AAAA;AAAA,IAEL,KAAK;AAAA,IACL,MAAM;AAAA,IACN,KAAK;AAAA,IACL,MAAM;AAAA,IACN,OAAO;AAAA;AAAA,IAEP,MAAM;AAAA,IACN,MAAM;AAAA,IACN,SAAS;AAAA,IACT,KAAK;AAAA,IACL,MAAM;AAAA;AAAA,IAEN,SAAS;AAAA;AAAA,IAET,UAAU;AAAA,IACV,IAAI;AAAA,IACJ,KAAK;AAAA,IACL,KAAK;AAAA,IACL,OAAO;AAAA,EACT;AAGA,QAAM,WAAW,SAAS,MAAM,GAAG,EAAE,IAAI,GAAG,YAAY,KAAK;AAC7D,MAAI,aAAa,gBAAgB,SAAS,WAAW,aAAa,GAAG;AACnE,WAAO;AAAA,EACT;AACA,MAAI,aAAa,cAAc,SAAS,WAAW,WAAW,GAAG;AAC/D,WAAO;AAAA,EACT;AACA,MAAI,SAAS,WAAW,MAAM,GAAG;AAC/B,WAAO;AAAA,EACT;AACA,MAAI,aAAa,YAAY,SAAS,WAAW,MAAM,GAAG;AACxD,WAAO;AAAA,EACT;AAEA,SAAO,QAAQ,GAAG,KAAK;AACzB;","names":["path","import_fs","ignore","import_fs","import_path","path","parseYaml","import_child_process","import_util","execAsync","import_fs","import_path","fsConstants"]}
package/dist/index.d.cts CHANGED
@@ -1,144 +1,5 @@
1
- type ChangeType = 'added' | 'modified' | 'deleted' | 'renamed';
2
- type DiffLineType = 'context' | 'addition' | 'deletion';
3
- interface DiffLine {
4
- type: DiffLineType;
5
- oldLineNumber: number | null;
6
- newLineNumber: number | null;
7
- content: string;
8
- }
9
- interface DiffHunk {
10
- header: string;
11
- oldStart: number;
12
- oldLines: number;
13
- newStart: number;
14
- newLines: number;
15
- lines: DiffLine[];
16
- }
17
- interface DiffFile {
18
- oldPath: string;
19
- newPath: string;
20
- changeType: ChangeType;
21
- isBinary: boolean;
22
- hunks: DiffHunk[];
23
- isUntracked?: boolean;
24
- contentLoaded?: boolean;
25
- }
26
- type DiffSource = {
27
- type: 'git';
28
- gitDiffArgs: string;
29
- repository: string;
30
- } | {
31
- type: 'directory';
32
- sourcePath: string;
33
- } | {
34
- type: 'file';
35
- sourcePath: string;
36
- } | {
37
- type: 'welcome';
38
- } | {
39
- type: 'loading';
40
- };
41
- interface Suggestion {
42
- originalCode: string;
43
- proposedCode: string;
44
- }
45
- interface Attachment {
46
- id: string;
47
- fileName: string;
48
- mediaType: string;
49
- data?: ArrayBuffer;
50
- }
51
- interface LineRange {
52
- side: 'old' | 'new';
53
- start: number;
54
- end: number;
55
- }
56
- interface ReviewComment {
57
- id: string;
58
- filePath: string;
59
- lineRange: LineRange | null;
60
- body: string;
61
- category: string;
62
- suggestion: Suggestion | null;
63
- orphaned?: boolean;
64
- attachments?: Attachment[];
65
- }
66
- interface FileReviewState {
67
- path: string;
68
- changeType: ChangeType;
69
- viewed: boolean;
70
- comments: ReviewComment[];
71
- }
72
- interface ReviewState {
73
- timestamp: string;
74
- source: DiffSource;
75
- files: FileReviewState[];
76
- }
77
- interface CategoryDef {
78
- name: string;
79
- description: string;
80
- color: string;
81
- }
82
- interface AppConfig {
83
- theme: 'light' | 'dark' | 'system';
84
- diffView: 'split' | 'unified';
85
- fontSize: number;
86
- outputFormat: string;
87
- outputFile: string;
88
- ignore: string[];
89
- categories: CategoryDef[];
90
- defaultDiffArgs: string;
91
- showUntracked: boolean;
92
- wordWrap: boolean;
93
- maxFiles: number;
94
- maxTotalLines: number;
95
- }
96
- interface DiffLoadPayload {
97
- files: DiffFile[];
98
- source: DiffSource;
99
- isLargePayload?: boolean;
100
- }
101
- interface ResumeLoadPayload {
102
- comments: ReviewComment[];
103
- }
104
- interface OutputPathInfo {
105
- resolvedOutputPath: string;
106
- outputPathWritable: boolean;
107
- }
108
- interface ExpandContextRequest {
109
- filePath: string;
110
- contextLines: number;
111
- }
112
- interface ExpandContextResponse {
113
- hunks: DiffHunk[];
114
- totalLines: number;
115
- }
116
- interface FindInPageRequest {
117
- text: string;
118
- forward: boolean;
119
- findNext: boolean;
120
- }
121
- interface FindInPageResult {
122
- activeMatchOrdinal: number;
123
- matches: number;
124
- finalUpdate: boolean;
125
- }
126
- interface VersionUpdateInfo {
127
- latestVersion: string;
128
- releaseUrl: string;
129
- }
130
- type ImageLoadResult = {
131
- dataUri: string;
132
- } | {
133
- error: string;
134
- };
135
- interface PayloadStats {
136
- fileCount: number;
137
- totalLines: number;
138
- exceedsFiles: boolean;
139
- exceedsLines: boolean;
140
- exceedsAny: boolean;
141
- }
1
+ import { DiffFile, ReviewState, ReviewComment, DiffSource, AppConfig, PayloadStats } from '@self-review/types';
2
+ export { AppConfig, Attachment, CategoryDef, ChangeType, DiffFile, DiffHunk, DiffLine, DiffLineType, DiffLoadPayload, DiffSource, ExpandContextRequest, ExpandContextResponse, FileReviewState, FindInPageRequest, FindInPageResult, ImageLoadResult, LineRange, OutputPathInfo, PayloadStats, ResumeLoadPayload, ReviewComment, ReviewState, Suggestion, VersionUpdateInfo } from '@self-review/types';
142
3
 
143
4
  declare function parseDiff(rawDiff: string): DiffFile[];
144
5
 
@@ -243,7 +104,15 @@ declare function createIgnoreFilter(patterns: string[]): (path: string) => boole
243
104
  */
244
105
  declare function checkWritability(filePath: string): boolean;
245
106
 
107
+ /**
108
+ * File-type detection utilities.
109
+ *
110
+ * NOTE: This file is intentionally duplicated in packages/react/src/utils/file-type-utils.ts.
111
+ * @self-review/core has Node-only dependencies, so @self-review/react cannot safely import
112
+ * from this package. Both copies must be kept in sync.
113
+ */
246
114
  declare function isPreviewableImage(filePath: string): boolean;
247
115
  declare function isPreviewableSvg(filePath: string): boolean;
116
+ declare function getLanguageFromPath(filePath: string): string;
248
117
 
249
- export { type AppConfig, type Attachment, type CategoryDef, type ChangeType, type DiffFile, type DiffHunk, type DiffLine, type DiffLineType, type DiffLoadPayload, type DiffSource, type ExpandContextRequest, type ExpandContextResponse, type FileReviewState, type FindInPageRequest, type FindInPageResult, type ImageLoadResult, type LineRange, type OutputPathInfo, type PayloadStats, type ResumeLoadPayload, type ReviewComment, type ReviewState, type Suggestion, type VersionUpdateInfo, checkWritability, computePayloadStats, countTotalLines, createIgnoreFilter, generateSyntheticDiffs, generateUntrackedDiffs, getGitDiffStats, getRepoRoot, getRepoRootAsync, getUntrackedFilesAsync, isPreviewableImage, isPreviewableSvg, loadConfig, parseDiff, parseReviewXml, parseReviewXmlString, runGitDiff, runGitDiffAsync, scanDirectory, scanFile, serializeReview, validateGitAvailable };
118
+ export { checkWritability, computePayloadStats, countTotalLines, createIgnoreFilter, generateSyntheticDiffs, generateUntrackedDiffs, getGitDiffStats, getLanguageFromPath, getRepoRoot, getRepoRootAsync, getUntrackedFilesAsync, isPreviewableImage, isPreviewableSvg, loadConfig, parseDiff, parseReviewXml, parseReviewXmlString, runGitDiff, runGitDiffAsync, scanDirectory, scanFile, serializeReview, validateGitAvailable };