import { constants } from 'node:fs' import { lstat, open, readlink } from 'node:fs/promises' import path from 'node:path' import { TextDecoder } from 'node:util' import { ClipboardInterruptedError, CommitMasterError } from './CommitMasterErrors.js' import { escapeDisplayedPath, escapeMarkdownHeadingPath, detectExtractableDocumentType, isOmittedBinaryContentPath, isSensitivePath, resolveAbsoluteBundlePath, } from './CommitMasterChangedFiles.js' import { MAX_DOCUMENT_SOURCE_BYTES, documentSourceTooLargePlaceholder, extractDocumentContent, } from './CommitMasterDocumentContent.js' import type { FileChange } from './CommitMasterTypes.js' export const MAX_BUNDLE_FILE_BYTES = 1024 * 1024 export const MAX_BUNDLE_BYTES = 10 * 1024 * 1024 const LANGUAGE_BY_SUFFIX: ReadonlyArray = [ ['.d.ts', 'ts'], ['.md', 'markdown'], ['.html', 'html'], ['.css', 'css'], ['.scss', 'scss'], ['.cjs', 'js'], ['.mjs', 'js'], ['.jsx', 'jsx'], ['.js', 'js'], ['.tsx', 'tsx'], ['.ts', 'ts'], ['.vue', 'vue'], ['.json', 'json'], ['.yaml', 'yaml'], ['.yml', 'yaml'], ['.xml', 'xml'], ['.svg', 'svg'], ['.zsh', 'bash'], ['.sh', 'bash'], ['.py', 'python'], ['.rb', 'ruby'], ['.php', 'php'], ['.go', 'go'], ['.rs', 'rust'], ['.java', 'java'], ['.kt', 'kotlin'], ['.swift', 'swift'], ['.sql', 'sql'], ['.graphql', 'graphql'], ['.gql', 'graphql'], ] const utf8Decoder = new TextDecoder('utf-8', { fatal: true }) interface BundleOptions { signal?: AbortSignal maxFileBytes?: number maxBundleBytes?: number } export interface BundleRepository { root: string name: string scopePath?: string changes: readonly FileChange[] } type FileContentResult = | { kind: 'content'; content: string; language: string } | { kind: 'placeholder'; content: string } export const detectFenceLanguage = (filePath: string): string => { const lowerPath = filePath.toLowerCase() return LANGUAGE_BY_SUFFIX.find(([suffix]) => lowerPath.endsWith(suffix))?.[1] ?? 'text' } export const omittedBinaryContentPlaceholder = (filePath: string): string => { const fileName = filePath.replaceAll('\\', '/').split('/').at(-1) ?? filePath return `[Binary file: ${escapeDisplayedPath(fileName)} - content omitted]` } export const createSafeFence = (content: string): string => { let longestRun = 0 for (const match of content.matchAll(/`+/g)) longestRun = Math.max(longestRun, match[0].length) return '`'.repeat(Math.max(3, longestRun + 1)) } const throwIfAborted = (signal?: AbortSignal): void => { if (signal?.aborted) throw new ClipboardInterruptedError({ cause: signal.reason }) } const decodeTextFile = (contents: Buffer): string | undefined => { for (const byte of contents) { if (byte < 9 || (byte > 13 && byte < 32)) return undefined } try { return utf8Decoder.decode(contents) } catch { return undefined } } export const fileReadPlaceholder = (error: unknown): string | undefined => { const code = (error as NodeJS.ErrnoException | undefined)?.code if (code === 'ENOENT' || code === 'ENOTDIR') return '[FILE NOT FOUND]' if ( code === 'EACCES' || code === 'EPERM' || code === 'EISDIR' || code === 'ELOOP' || code === 'EINVAL' || code === 'EBUSY' || code === 'ESTALE' ) { return '[FILE UNREADABLE]' } return undefined } /** * Ensures every path component below the bundle root is still a real directory. * This deliberately permits a final symbolic link because links are rendered as * their target text, never followed for content. */ const hasSafeBundleAncestors = async (bundleRoot: string, absolutePath: string): Promise => { const relativePath = path.relative(bundleRoot, absolutePath) if ( !relativePath || relativePath === '..' || relativePath.startsWith(`..${path.sep}`) || path.isAbsolute(relativePath) ) { return false } try { const rootMetadata = await lstat(bundleRoot) if (!rootMetadata.isDirectory() || rootMetadata.isSymbolicLink()) return false const components = relativePath.split(path.sep) let currentPath = bundleRoot for (const component of components.slice(0, -1)) { currentPath = path.join(currentPath, component) const metadata = await lstat(currentPath) if (!metadata.isDirectory() || metadata.isSymbolicLink()) return false } return true } catch { return false } } const readBoundedFile = async ( bundleRoot: string, absolutePath: string, maxFileBytes: number, signal?: AbortSignal ): Promise => { if (!(await hasSafeBundleAncestors(bundleRoot, absolutePath))) return '[FILE UNREADABLE]' const noFollow = process.platform === 'win32' ? 0 : constants.O_NOFOLLOW const handle = await open(absolutePath, constants.O_RDONLY | noFollow) try { // Validate again after opening, before any bytes are read. This catches // ancestor replacement between path validation and file acquisition. if (!(await hasSafeBundleAncestors(bundleRoot, absolutePath))) return '[FILE UNREADABLE]' const metadata = await handle.stat() if (!metadata.isFile()) return '[FILE UNREADABLE]' const currentPathMetadata = await lstat(absolutePath) if ( !currentPathMetadata.isFile() || currentPathMetadata.dev !== metadata.dev || currentPathMetadata.ino !== metadata.ino ) { return '[FILE UNREADABLE]' } if (metadata.size > maxFileBytes) return '[FILE TOO LARGE]' const sameOpenedFile = (latest: { isFile(): boolean; dev: number; ino: number }): boolean => latest.isFile() && latest.dev === metadata.dev && latest.ino === metadata.ino const readFromStart = async (knownSize: number): Promise => { const contents = Buffer.allocUnsafe(Math.min(knownSize, maxFileBytes) + 1) let offset = 0 while (offset < contents.length) { throwIfAborted(signal) const { bytesRead } = await handle.read(contents, offset, contents.length - offset, offset) if (bytesRead === 0) break offset += bytesRead } if (offset > maxFileBytes) return '[FILE TOO LARGE]' return contents.subarray(0, offset) } let contents = await readFromStart(metadata.size) if (contents === '[FILE TOO LARGE]') return contents const latest = await handle.stat() if (!sameOpenedFile(latest)) return '[FILE UNREADABLE]' if (latest.size > maxFileBytes) return '[FILE TOO LARGE]' if (latest.size > contents.length) { contents = await readFromStart(latest.size) if (contents === '[FILE TOO LARGE]') return contents const again = await handle.stat() if (!sameOpenedFile(again)) return '[FILE UNREADABLE]' if (again.size > maxFileBytes) return '[FILE TOO LARGE]' if (again.size > contents.length) return '[FILE UNREADABLE]' } if (!(await hasSafeBundleAncestors(bundleRoot, absolutePath))) return '[FILE UNREADABLE]' return contents } finally { await handle.close() } } const readBundleFileContent = async ( bundleRoot: string, absolutePath: string, change: FileChange, maxFileBytes: number, signal?: AbortSignal, sourceName = 'changed file' ): Promise => { if ( isSensitivePath(change.path) || (change.kind === 'renamed' && !!change.previousPath && isSensitivePath(change.previousPath)) ) { return { kind: 'placeholder', content: '[SENSITIVE FILE OMITTED]' } } if (change.kind === 'deleted') return { kind: 'placeholder', content: '[FILE DELETED]' } if (change.kind === 'renamed' && change.isContentUnchanged) { return { kind: 'placeholder', content: '[NO CHANGES IN FILE - RENAMED ONLY]' } } try { throwIfAborted(signal) if (!(await hasSafeBundleAncestors(bundleRoot, absolutePath))) { return { kind: 'placeholder', content: '[FILE UNREADABLE]' } } const metadata = await lstat(absolutePath) if (metadata.isSymbolicLink()) { const target = await readlink(absolutePath) return (await hasSafeBundleAncestors(bundleRoot, absolutePath)) ? { kind: 'content', content: target, language: 'text' } : { kind: 'placeholder', content: '[FILE UNREADABLE]' } } if (!metadata.isFile()) return { kind: 'placeholder', content: '[FILE UNREADABLE]' } const documentType = detectExtractableDocumentType(change.path) if (documentType) { const contents = await readBoundedFile( bundleRoot, absolutePath, MAX_DOCUMENT_SOURCE_BYTES, signal ) if (contents === '[FILE UNREADABLE]') return { kind: 'placeholder', content: contents } if (contents === '[FILE TOO LARGE]') { return { kind: 'placeholder', content: documentSourceTooLargePlaceholder(documentType) } } return extractDocumentContent(contents, documentType, { signal }) } if (isOmittedBinaryContentPath(change.path)) { return { kind: 'placeholder', content: omittedBinaryContentPlaceholder(change.path) } } const contents = await readBoundedFile(bundleRoot, absolutePath, maxFileBytes, signal) if (typeof contents === 'string') return { kind: 'placeholder', content: contents } const decoded = decodeTextFile(contents) return decoded === undefined ? { kind: 'placeholder', content: omittedBinaryContentPlaceholder(change.path) } : { kind: 'content', content: decoded, language: detectFenceLanguage(change.path) } } catch (error) { if (error instanceof ClipboardInterruptedError) throw error const placeholder = fileReadPlaceholder(error) if (placeholder) return { kind: 'placeholder', content: placeholder } throw new CommitMasterError(`Unable to read ${sourceName} "${change.path}".`, { cause: error }) } } const validateLimit = (value: number, name: string, maximum: number): number => { if (!Number.isSafeInteger(value) || value < 0 || value > maximum) { throw new CommitMasterError(`${name} must be between 0 and ${maximum} bytes.`) } return value } export const createMarkdownBundle = async ( bundleRoot: string, changes: readonly FileChange[], options: BundleOptions = {} ): Promise => { const maxFileBytes = validateLimit( options.maxFileBytes ?? MAX_BUNDLE_FILE_BYTES, 'Maximum file size', MAX_BUNDLE_FILE_BYTES ) const maxBundleBytes = validateLimit( options.maxBundleBytes ?? MAX_BUNDLE_BYTES, 'Maximum bundle size', MAX_BUNDLE_BYTES ) const repositoryHeader = `Repository: ${escapeDisplayedPath(bundleRoot)}` const ending = '\n\n------------------------------' let bundleBytes = Buffer.byteLength(repositoryHeader) + Buffer.byteLength(ending) const sections: string[] = [] for (const change of changes) { const section = await createBundleSection(bundleRoot, change, maxFileBytes, options.signal) bundleBytes = addBundleBytes(bundleBytes, '\n\n', section, maxBundleBytes) sections.push(section) } return `${repositoryHeader}\n\n${sections.join('\n\n')}${ending}` } /** Renders a filesystem bundle with the same safe file-content handling as gitbundle. */ export const createFolderMarkdownBundle = async ( folderRoot: string, files: readonly FileChange[], options: BundleOptions = {} ): Promise => { const maxFileBytes = validateLimit( options.maxFileBytes ?? MAX_BUNDLE_FILE_BYTES, 'Maximum file size', MAX_BUNDLE_FILE_BYTES ) const maxBundleBytes = validateLimit( options.maxBundleBytes ?? MAX_BUNDLE_BYTES, 'Maximum bundle size', MAX_BUNDLE_BYTES ) const folderHeader = `Folder: ${escapeDisplayedPath(folderRoot)}` const ending = '\n\n------------------------------' let bundleBytes = Buffer.byteLength(folderHeader) + Buffer.byteLength(ending) const sections: string[] = [] for (const file of files) { const section = await createBundleSection( folderRoot, file, maxFileBytes, options.signal, 'FILE', 'folder file' ) bundleBytes = addBundleBytes(bundleBytes, '\n\n', section, maxBundleBytes) sections.push(section) } return `${folderHeader}\n\n${sections.join('\n\n')}${ending}` } const addBundleBytes = ( currentBytes: number, separator: string, content: string, maxBundleBytes: number ): number => { const total = currentBytes + Buffer.byteLength(separator) + Buffer.byteLength(content) if (total > maxBundleBytes) { throw new CommitMasterError( 'Markdown bundle exceeds the 10 MiB safety limit. Reduce the number or size of files and try again.' ) } return total } const createBundleSection = async ( bundleRoot: string, change: FileChange, maxFileBytes: number, signal?: AbortSignal, headingKind?: string, sourceName?: string ): Promise => { throwIfAborted(signal) const absolutePath = resolveAbsoluteBundlePath(bundleRoot, change.path) const result = await readBundleFileContent( bundleRoot, absolutePath, change, maxFileBytes, signal, sourceName ) const content = result.content const language = result.kind === 'content' ? result.language : 'text' const fence = createSafeFence(content) const contentWithNewline = content.endsWith('\n') ? content : `${content}\n` const headingPath = createChangeHeadingPath(change) return `### [${headingKind ?? change.kind.toUpperCase()}] ${headingPath}\n\n${fence}${language}\n${contentWithNewline}${fence}` } const createChangeHeadingPath = (change: FileChange): string => { const currentPath = escapeMarkdownHeadingPath(change.path) if (change.kind !== 'renamed' || !change.previousPath) return currentPath return `${escapeMarkdownHeadingPath(change.previousPath)} -> ${currentPath}` } export const createCombinedMarkdownBundle = async ( repositories: readonly BundleRepository[], options: BundleOptions = {} ): Promise => { const maxFileBytes = validateLimit( options.maxFileBytes ?? MAX_BUNDLE_FILE_BYTES, 'Maximum file size', MAX_BUNDLE_FILE_BYTES ) const maxBundleBytes = validateLimit( options.maxBundleBytes ?? MAX_BUNDLE_BYTES, 'Maximum bundle size', MAX_BUNDLE_BYTES ) const fileCount = repositories.reduce((total, repository) => total + repository.changes.length, 0) const repositoryCount = new Set(repositories.map((repository) => repository.root)).size const scoped = repositories.some((repository) => repository.scopePath && repository.scopePath !== repository.root) const targetCount = scoped ? `\nDirectories: ${repositories.length}` : '' const header = `# Repository Bundle\n\nRepositories: ${repositoryCount}${targetCount}\nFiles: ${fileCount}` const ending = '\n\n------------------------------' let bundleBytes = Buffer.byteLength(header) + Buffer.byteLength(ending) const repositorySections: string[] = [] for (const repository of repositories) { throwIfAborted(options.signal) const scopePath = repository.scopePath ?? repository.root const rootDetail = scopePath === repository.root ? '' : `\nRepository: ${escapeDisplayedPath(repository.root)}` const heading = `## ${escapeMarkdownHeadingPath(repository.name)}\n\nPath: ${escapeDisplayedPath(scopePath)}${rootDetail}\nChanged files: ${repository.changes.length}` bundleBytes = addBundleBytes(bundleBytes, '\n\n', heading, maxBundleBytes) const fileSections: string[] = [] for (const change of repository.changes) { const fileSection = await createBundleSection( repository.root, change, maxFileBytes, options.signal ) bundleBytes = addBundleBytes(bundleBytes, '\n\n', fileSection, maxBundleBytes) fileSections.push(fileSection) } repositorySections.push(`${heading}\n\n${fileSections.join('\n\n')}`) } return `${header}\n\n${repositorySections.join('\n\n')}${ending}` }