1
repomix --remote https://github.com/yamadashy/repomix --remote-branch main --include "src/**/*.ts,**/*.md" --ignore "**/*server.md,**/client/src" --compress --copy

This file is a merged representation of a subset of the codebase, containing specifically included files and files not matching ignore patterns, combined into a single document by Repomix.
The content has been processed where content has been compressed (code blocks are separated by ⋮---- delimiter).

<file_summary>
This section contains a summary of this file.

<purpose>
This file contains a packed representation of the entire repository's contents.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>

<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
  - File path as an attribute
  - Full contents of the file
</file_format>

<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
  original repository files, not this packed version.
- When processing this file, use the file path to distinguish
  between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
  the same level of security as you would the original repository.
- Pay special attention to the Repository Description. These contain important context and guidelines specific to this project.
- Pay special attention to the Repository Instruction. These contain important context and guidelines specific to this project.
</usage_guidelines>

<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Only files matching these patterns are included: src/**/*.ts, **/*.md
- Files matching these patterns are excluded: **/*server.md, **/client/src
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Content has been compressed - code blocks are separated by ⋮---- delimiter
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>

</file_summary>

<user_provided_header>
This repository contains the source code for the Repomix tool.
Repomix is designed to pack repository contents into a single file,
making it easier for AI systems to analyze and process the codebase.

Key Features:
- Configurable ignore patterns
- Custom header text support
- Efficient file processing and packing

Please refer to the README.md file for more detailed information on usage and configuration.

</user_provided_header>

<directory_structure>
.agents/
  rules/
    base.md
    browser-extension.md
    website.md
.claude/
  commands/
    claude-rule-update.md
    git-commit-push.md
    git-commit.md
    pr-create.md
    pr-review-request.md
    pr-review.md
.github/
  instructions/
    base.instructions.md
  releases/
    v0.1.x/
      v0.1.15.md
      v0.1.16.md
      v0.1.18.md
      v0.1.19.md
      v0.1.20.md
      v0.1.21.md
      v0.1.22.md
      v0.1.23.md
      v0.1.24.md
      v0.1.25.md
      v0.1.26.md
      v0.1.27.md
      v0.1.28.md
      v0.1.29.md
      v0.1.30.md
      v0.1.31.md
      v0.1.32.md
      v0.1.33.md
      v0.1.34.md
      v0.1.35.md
      v0.1.36.md
      v0.1.37.md
      v0.1.38.md
      v0.1.39.md
      v0.1.40.md
      v0.1.41.md
      v0.1.42.md
      v0.1.43.md
      v0.1.44.md
      v0.1.45.md
    v0.2.x/
      v0.2.1.md
      v0.2.10.md
      v0.2.11.md
      v0.2.12.md
      v0.2.15.md
      v0.2.16.md
      v0.2.17.md
      v0.2.2.md
      v0.2.20.md
      v0.2.21.md
      v0.2.22.md
      v0.2.23.md
      v0.2.24.md
      v0.2.25.md
      v0.2.26.md
      v0.2.28.md
      v0.2.29.md
      v0.2.3.md
      v0.2.30.md
      v0.2.32.md
      v0.2.33.md
      v0.2.34.md
      v0.2.35.md
      v0.2.36.md
      v0.2.4.md
      v0.2.40.md
      v0.2.41.md
      v0.2.5.md
      v0.2.6.md
      v0.2.7.md
      v0.2.8.md
    v0.3.x/
      v0.3.0.md
      v0.3.1.md
      v0.3.2.md
      v0.3.3.md
      v0.3.5.md
      v0.3.6.md
      v0.3.7.md
      v0.3.8.md
      v0.3.9.md
  pull_request_template.md
browser/
  CLAUDE.md
  README.md
src/
  cli/
    actions/
      defaultAction.ts
      initAction.ts
      mcpAction.ts
      migrationAction.ts
      remoteAction.ts
      versionAction.ts
    cliPrint.ts
    cliRun.ts
    cliSpinner.ts
    types.ts
  config/
    configLoad.ts
    configSchema.ts
    defaultIgnore.ts
    globalDirectory.ts
  core/
    file/
      workers/
        fileCollectWorker.ts
        fileProcessWorker.ts
      fileCollect.ts
      fileManipulate.ts
      filePathSort.ts
      fileProcess.ts
      fileProcessContent.ts
      fileRead.ts
      fileSearch.ts
      fileStdin.ts
      fileTreeGenerate.ts
      fileTypes.ts
      packageJsonParse.ts
      permissionCheck.ts
    git/
      gitCommand.ts
      gitDiffHandle.ts
      gitHubArchive.ts
      gitHubArchiveApi.ts
      gitRemoteHandle.ts
      gitRemoteParse.ts
      gitRepositoryHandle.ts
    metrics/
      workers/
        fileMetricsWorker.ts
        outputMetricsWorker.ts
        types.ts
      calculateAllFileMetrics.ts
      calculateMetrics.ts
      calculateOutputMetrics.ts
      TokenCounter.ts
    output/
      outputStyles/
        markdownStyle.ts
        plainStyle.ts
        xmlStyle.ts
      outputGenerate.ts
      outputGeneratorTypes.ts
      outputSort.ts
      outputStyleDecorate.ts
    packager/
      copyToClipboardIfEnabled.ts
      writeOutputToDisk.ts
    security/
      workers/
        securityCheckWorker.ts
      filterOutUntrustedFiles.ts
      securityCheck.ts
      validateFileSafety.ts
    treeSitter/
      parseStrategies/
        CssParseStrategy.ts
        DefaultParseStrategy.ts
        GoParseStrategy.ts
        ParseStrategy.ts
        PythonParseStrategy.ts
        TypeScriptParseStrategy.ts
        VueParseStrategy.ts
      queries/
        queryC.ts
        queryCpp.ts
        queryCSharp.ts
        queryCss.ts
        queryGo.ts
        queryJava.ts
        queryJavascript.ts
        queryPhp.ts
        queryPython.ts
        queryRuby.ts
        queryRust.ts
        querySolidity.ts
        querySwift.ts
        queryTypescript.ts
        queryVue.ts
        README.md
      ext2Lang.ts
      lang2Query.ts
      languageParser.ts
      loadLanguage.ts
      parseFile.ts
    packager.ts
  mcp/
    prompts/
      packRemoteRepositoryPrompts.ts
    tools/
      fileSystemReadDirectoryTool.ts
      fileSystemReadFileTool.ts
      grepRepomixOutputTool.ts
      mcpToolRuntime.ts
      packCodebaseTool.ts
      packRemoteRepositoryTool.ts
      readRepomixOutputTool.ts
    mcpServer.ts
  shared/
    constants.ts
    errorHandle.ts
    logger.ts
    patternUtils.ts
    processConcurrency.ts
    types.ts
  types/
    git-url-parse.d.ts
  index.ts
website/
  README.md
CLAUDE.md
CODE_OF_CONDUCT.md
CONTRIBUTING.md
llms-install.md
README.md
repomix-instruction.md
SECURITY.md
</directory_structure>

<files>
This section contains the contents of the repository's files.

<file path=".agents/rules/base.md">
---
description: Core project guidelines for the Repomix codebase. Apply these rules when working on any code, documentation, or configuration files within the Repomix project.
---

# Repomix Project Structure and Overview

This document provides a structural overview of the Repomix project, designed to aid AI code assistants (like Copilot) in understanding the codebase.

Please refer to `README.md` for a complete and up-to-date project overview, and `CONTRIBUTING.md` for implementation guidelines and contribution procedures.

## Project Overview

Repomix is a tool that packs the contents of a software repository into a single file, making it easier for AI systems to analyze and process the codebase. It supports various output formats (XML, Markdown, or plain text), ignores files based on configurable patterns, and performs security checks to exclude potentially sensitive information.

## Directory Structure

The project is organized into the following directories:

```
repomix/
├── browser/ # Browser extension source code.
├── src/ # Main source code
   ├── cli/ # Command-line interface logic (argument parsing, command handling, output)
   ├── config/ # Configuration loading, schema, and defaults
   ├── core/ # Core logic of Repomix
      ├── file/ # File handling (reading, processing, searching, tree structure generation, git commands)
      ├── metrics/ # Calculating code metrics (character count, token count)
      ├── output/ # Output generation (different styles, headers, etc.)
      ├── packager/ # Orchestrates file collection, processing, output, and clipboard operations.
      ├── security/ # Security checks to exclude sensitive files
      ├── mcp/ # MCP server integration (packaging codebases for AI analysis)
      ├── tokenCount/ # Token counting using Tiktoken
      └── treeSitter/ # Code parsing using Tree-sitter and language-specific queries
   └── shared/ # Shared utilities and types (error handling, logging, helper functions)
├── tests/ # Unit and integration tests (organized mirroring src/)
   ├── cli/
   ├── config/
   ├── core/
   ├── integration-tests/
   ├── shared/
   └── testing/
└── website/ # Documentation website (VitePress).
```



# Coding Guidelines
- Follow the Airbnb JavaScript Style Guide.
- Split files into smaller, focused units when appropriate:
  - Aim to keep code files under 250 lines. If a file exceeds 250 lines, split it into multiple files based on functionality.
- Add comments to clarify non-obvious logic. **Ensure all comments are written in English.**
- Provide corresponding unit tests for all new features.
- After implementation, verify changes by running:
  ```bash
  npm run lint  # Ensure code style compliance
  npm run test  # Verify all tests pass
  ```

## Commit Messages
- Follow the [Conventional Commits](https://www.conventionalcommits.org/) specification for all commit messages
- Always include a scope in your commit messages
- Format: `type(scope): Description`
  ```
  # Examples:
  feat(cli): Add new --no-progress flag
  fix(security): Handle special characters in file paths
  docs(website): Update installation guide
  style(website): Update GitHub sponsor button color
  refactor(core): Split packager into smaller modules
  test(cli): Add tests for new CLI options
  ```
- Types: feat, fix, docs, style, refactor, test, chore, etc.
- Scope should indicate the affected part of the codebase (cli, core, website, security, etc.)
- Description should be clear and concise in present tense
- Description must start with a capital letter

### Commit Body Guidelines
- Include context about what led to this commit
- Describe the conversation or problem that motivated the change
- This helps preserve the decision-making process for future reference

## Pull Request Guidelines
- All pull requests must follow the template:
  ```md
  <!-- Please include a summary of the changes -->

  ## Checklist

  - [ ] Run `npm run test`
  - [ ] Run `npm run lint`
  ```
- Include a clear summary of the changes at the top of the pull request description
- Reference any related issues using the format `#issue-number` 

## PR Review Guidelines
When reviewing pull requests, provide thoughtful feedback on:
- Code quality and best practices
- Potential bugs or issues
- Suggestions for improvements
- Overall architecture and design decisions

## Dependencies and Testing
- Inject dependencies through a deps object parameter for testability
- Example:
  ```typescript
  export const functionName = async (
    param1: Type1,
    param2: Type2,
    deps = {
      defaultFunction1,
      defaultFunction2,
    }
  ) => {
    // Use deps.defaultFunction1() instead of direct call
  };
  ```
- Mock dependencies by passing test doubles through deps object
- Use vi.mock() only when dependency injection is not feasible

## Generate Comprehensive Output
- Include all content without abbreviation, unless specified otherwise
- Optimize for handling large codebases while maintaining output quality

# GitHub Release Note Guidelines
When writing release notes, please follow these guidelines:

- When referencing issues or PRs, use the gh command to verify the content:
  ```bash
  gh issue view <issue-number>  # For checking issue content
  gh pr view <pr-number>        # For checking PR content
  ```
  This helps ensure accuracy in release note descriptions.

Please retrieve and reference the latest release notes from `.github/releases/` as they contain past release examples.

## Other Project-Specific Rules

For specialized areas of the codebase, please also refer to:

- **[browser-extension.md](.agents/rules/browser-extension.md)** - Guidelines for browser extension development (Chrome/Firefox/Edge compatibility, manifest files, content scripts)
- **[website.md](.agents/rules/website.md)** - Guidelines for documentation website (multi-language support, VitePress configuration, translation workflows)
</file>

<file path=".agents/rules/browser-extension.md">
---
description: Guidelines for developing the Repomix browser extension. Apply these rules when working on browser extension code, manifest files, content scripts, or internationalization. This includes Chrome/Firefox/Edge compatibility and GitHub integration features.
---

# Browser Extension Guidelines

This file provides guidance for working with the Repomix browser extension.

## Project Overview

Cross-browser extension (Chrome/Firefox/Edge) that adds Repomix integration to GitHub repository pages. Uses Manifest V3 with content scripts to inject a "Repomix" button directly into GitHub's UI.

## Directory Structure

```
browser/
├── app/                    # Extension source code
   ├── _locales/          # Internationalization files (11 languages)
   ├── images/            # Extension icons (16px to 128px)
   ├── manifest.json      # Extension manifest (Manifest V3)
   ├── scripts/           # TypeScript source files
      ├── background.ts  # Service worker (background script)
      └── content.ts     # Content script for GitHub integration
   └── styles/            # CSS styles for injected elements
├── dist/                  # Built extension files (generated)
├── promo/                 # Store promotional materials
└── tests/                 # Test files
```

## Development Commands

```bash
npm run dev chrome     # Development mode for Chrome
npm run build-all      # Build for all browsers
npm run lint          # TypeScript type checking
npm run test          # Run tests
npm run generate-icons # Generate icon set from SVG
```

## Internationalization

### Supported Languages (11 total)
English, Japanese, German, French, Spanish, Portuguese (Brazilian), Indonesian, Vietnamese, Korean, Chinese (Simplified/Traditional), Hindi.

### Adding New Languages
1. Create directory in `app/_locales/[language_code]/`
2. Add `messages.json` with required keys:
   - `appName`, `appDescription`, `buttonText`
3. Add `detailed-description.txt` for store descriptions
4. Test extension loads correctly with new locale
</file>

<file path=".agents/rules/website.md">
---
description: Guidelines for working with the Repomix documentation website. Apply these rules when modifying website content, adding translations, updating navigation, or implementing new documentation features.
---

# Website Documentation

## Supported Languages
The website documentation is available in the following languages:
- English (en)
- Japanese (日本語) (ja)
- Chinese Simplified (简体中文) (zh-cn)
- Chinese Traditional (繁體中文) (zh-tw)
- Korean (한국어) (ko)
- German (Deutsch) (de)
- French (Français) (fr)
- Spanish (Español) (es)
- Portuguese Brazilian (Português do Brasil) (pt-br)
- Indonesian (Bahasa Indonesia) (id)
- Vietnamese (Tiếng Việt) (vi)
- Hindi (हिन्दी) (hi)

All translations should be accurate and maintain consistent terminology across languages. When adding new features or documentation, please ensure that the English version is updated first, followed by translations in other languages.

## Navigation Configuration
When modifying website navigation or adding new pages:
1. Update the configuration files in `website/client/.vitepress/config/`.

Ensure all language configurations are synchronized to maintain consistency across the documentation.

## Adding New Languages
When adding support for a new language, follow these steps:

1. Create a configuration file (e.g., `configXx.ts`) in `website/client/.vitepress/config/` based on existing language configurations
2. Include proper sidebar navigation, labels, and search translations
3. Update the imports and locale entries in the main VitePress configuration (`config.ts`)
4. Add search configurations to `configShard.ts`
5. Update the supported languages list in this file
6. Create directory structure for content (e.g., `website/client/src/xx/`)
7. Create content files starting with main index page and guide index
8. Progressively translate remaining documentation pages
9. Test navigation and search functionality in the new language

When working on multiple languages simultaneously, approach one language at a time completely before moving to the next language to maintain quality and consistency.
</file>

<file path=".claude/commands/claude-rule-update.md">
Please update CLAUDE.md based on our conversation.
Follow any additional instructions if provided.
</file>

<file path=".claude/commands/git-commit-push.md">
Please commit and push your changes.

The commit message should follow the rules specified in CLAUDE.md.
</file>

<file path=".claude/commands/git-commit.md">
Please commit your changes.

The commit message should follow the rules specified in CLAUDE.md.
</file>

<file path=".claude/commands/pr-create.md">
Please create a PR following the template at `.github/pull_request_template.md`.
</file>

<file path=".claude/commands/pr-review-request.md">
Please request a review of this pull request from Gemini and Coderabbit.
</file>

<file path=".claude/commands/pr-review.md">
Please review the provided PR.

Even if there are no issues to point out, please leave a review comment on GitHub.

You can use the `gh` command for comments.
</file>

<file path=".github/instructions/base.instructions.md">
---
applyTo: '**'
---

Please make sure to check the rules written in `.agents/rules/base.md` as they contain important project-specific guidelines and instructions.
</file>

<file path=".github/releases/v0.1.x/v0.1.15.md">
It appears I've been fashionably late to the release notes soirée.  It's like we've been living under a rock from v0.1.1 to v0.1.14. But they, better late than never, as they say in the world of procrastinating developers.

## New Features

### Output Style Options
- Introducing the `output.style` configuration option:
  - `plain`: The classic output format.
  - `xml`: An XML-structured output for enhanced parsing.

This addition aims to provide more flexibility in how Repopack structures its output.

For those interested in the potential of XML tags in AI contexts:
https://docs.anthropic.com/en/docs/build-with-claude/prompt-engineering/use-xml-tags

## How to Use

Add `output.style` to your configuration and select either `plain` or `xml`. The choice is yours, based on your project needs.

---
Your feedback is the wind beneath Repopack's wings. Feel free to report bugs or request features.

Thank you for your continued support.
</file>

<file path=".github/releases/v0.1.x/v0.1.16.md">
Our CLI has learned the art of style. It's now fluent in both plain and XML.

## What's New

- Added `--style` option to CLI
  - Choose between `plain` and `xml` output styles
  - Usage: `repopack --style xml`

Happy packing!
</file>

<file path=".github/releases/v0.1.x/v0.1.18.md">
It's focusing on security improvements and output refinements. 

## Improvements
###  Security Enhancements: Exclude Suspicious Files
- Implemented a filter to exclude potentially sensitive files from the output. 
- This improvement prevents the inclusion of suspicious files, enhancing overall security.

## Fixes
### Prevent Recursive Output Issues
- Modified the `getFilePaths` function in `src/core/packager.ts` to exclude the output file from processing.
- This fix resolves a recursive issue where the output file was being included in itself.

## Changes
### XML Escaping Removal
- Removed XML escaping for file paths and contents in repository files.
- This change improves readability and AI comprehension of the generated output.

Note: This update assumes that input data (file paths, contents, etc.) does not contain characters that would break XML syntax. If there's a possibility of such characters, we may implement a more robust solution in the future, such as using CDATA sections for file contents.
</file>

<file path=".github/releases/v0.1.x/v0.1.19.md">
It's focusing on improved file filtering capabilities and overall performance enhancements. 

## New Features

### Support `include` (#22, #30)
- Introduced the `--include` CLI option for specifying files to include using glob patterns. 
- Added support for `include` patterns in the configuration file.

To pack specific files or directories using glob patterns:
```bash
repopack --include "src/**/*.ts,**/*.md"
```

Special thanks to @IsaacSante for their contributions.

## Improvements

### Performance Optimization
- Replaced the `ignore` package with `globby` for more efficient file filtering.
</file>

<file path=".github/releases/v0.1.x/v0.1.20.md">
## Changes

### gitignore Syntax Compliance
- Fixed handling of `.gitignore` and `.repopackignore` files to properly comply with gitignore syntax.
- This ensures more accurate and consistent file filtering based on your ignore patterns.

### Change File Filtering Logic
- Migrated custom ignore pattern processing from gitignore syntax to glob patterns. 

## Notes

- This update may affect which files are included/excluded in the packed output. We recommend reviewing your ignore patterns to ensure desired behavior.
- If you're using a custom configuration, make sure to update your `ignore.customPatterns` to use glob patterns instead of gitignore syntax.
</file>

<file path=".github/releases/v0.1.x/v0.1.21.md">
## Improvements

### Enhanced ignore files support (#34, #35)
- Updated the file filtering logic to consider `.gitignore`, `.repopackignore` files in all directories, not just the root.
- This change ensures that all ignore files, regardless of their location in the project structure, are properly respected during the file filtering process.

## Notes
- This update improves the handling of ignore files in your project structure. You may notice changes in which files are included or excluded if you have ignore files in subdirectories.
</file>

<file path=".github/releases/v0.1.x/v0.1.22.md">
This update brings a significant new feature that enhances the tool's utility for working with large language models.

## New Features

### Token Counting Support (#39)

Thanks to the fantastic contribution from @joshellington, Repopack now includes token counting functionality:

- Added token counts for individual files and the entire repository
- Updated CLI output to display token information in the summary and top files list

This feature is particularly useful for users working within context limits of large language models like GPT-4.

A huge thank you to @joshellington for this valuable contribution!
</file>

<file path=".github/releases/v0.1.x/v0.1.23.md">
This update introduces a new interactive configuration setup and includes several improvements to enhance user experience.

## New Features

### Interactive Configuration Setup (#45)

- Added a new `--init` command to Repopack
- Users can now interactively create a basic `repopack.config.json` file
- The setup prompts for:
  - Output file path
  - Output style (plain or XML)

<img width="633" alt="image" src="https://github.com/user-attachments/assets/e3a2bba3-053a-491c-ae42-36bd24cc4395">

This new feature simplifies the process of getting started with Repopack, especially for new users.

---

To update, simply run:
```bash
npm update -g repopack
```
</file>

<file path=".github/releases/v0.1.x/v0.1.24.md">
This update focuses on significant performance improvements through the implementation of parallel processing.

## What's New

### Parallel Processing (#50)

- Implemented parallel processing in key components of Repopack

---
To update, simply run:
```
npm update -g repopack
```

As always, we appreciate your feedback and contributions to make Repopack even better!
</file>

<file path=".github/releases/v0.1.x/v0.1.25.md">
This update introduces global configuration support, allowing for more consistent settings across projects.

## What's New

### Global Configuration Support (#51, #52)

- Added support for global configuration files
- Implemented `repopack --init --global` command to create a global config
- Global config locations:
  - Windows: `%LOCALAPPDATA%\Repopack\repopack.config.json`
  - macOS/Linux: `$XDG_CONFIG_HOME/repopack/repopack.config.json` or `~/.config/repopack/repopack.config.json`
- Local configs still take precedence when present

---
To update, simply run:
```
npm update -g repopack
```

As always, we appreciate your feedback and contributions to make Repopack even better!
</file>

<file path=".github/releases/v0.1.x/v0.1.26.md">
## Bug Fixes

- Fixed issue where Repopack could process its own output file (#53)

---

To update:

```
npm update -g repopack
```

Thank you for using Repopack!
</file>

<file path=".github/releases/v0.1.x/v0.1.27.md">
## Bug Fixes

### Fix `output.showLineNumbers` (#54)

- Resolved the issue where line numbers were not being added to processed content when `output.showLineNumbers` was enabled
  - Implemented padding for line numbers to ensure proper alignment

---

To update, simply run:
```
npm update -g repopack
```

As always, we appreciate your feedback and contributions to make Repopack even better!
</file>

<file path=".github/releases/v0.1.x/v0.1.28.md">
## Bug Fixes

### Fix concurrency issue in environments where CPU count is unavailable (#56, #57)

- Resolved the issue where Repopack would fail in environments where `os.cpus().length` returns 0 (e.g., some Termux on Android setups)

---

To update, simply run:
```
npm update -g repopack
```

As always, we appreciate your feedback and contributions to make Repopack even better!
</file>

<file path=".github/releases/v0.1.x/v0.1.29.md">
## Security Updates

### Update micromatch to address security vulnerability (#58)

- Updated `micromatch` from version 4.0.7 to 4.0.8
- This update includes a critical security fix for CVE-2024-4067

---

To update, simply run:
```
npm update -g repopack
```
</file>

<file path=".github/releases/v0.1.x/v0.1.30.md">
## Bug Fixes

### Simplify Python comment removal to preserve f-strings and other content (#55, #59)

- Changed the comment removal strategy for Python files to only remove single-line comments starting with '#'
  - Preserved all other content, including string literals, f-strings, and docstrings
  - Resolved the issue where f-strings and other important code elements were being incorrectly removed

---

To update, simply run:
```
npm update -g repopack
```

As always, we appreciate your feedback and contributions to make Repopack even better!
</file>

<file path=".github/releases/v0.1.x/v0.1.31.md">
This update introduces remote repository processing, allowing users to analyze any public Git repository without manual cloning.

## What's New

### Remote Repository Processing Support (#61)

- Added `--remote` option to process remote Git repositories
- Supports full URLs and GitHub shorthand format (e.g., `user/repo`)

#### Usage Examples

Process a GitHub repository:
```bash
repopack --remote https://github.com/user/repo.git
```

Use GitHub shorthand:
```bash
repopack --remote user/repo
```

Process a GitLab repository:
```bash
repopack --remote https://gitlab.com/user/repo.git
```

---
To update, simply run:
```
npm update -g repopack
```

As always, we appreciate your feedback and contributions to make Repopack even better!
</file>

<file path=".github/releases/v0.1.x/v0.1.32.md">
This release focuses on improving performance and user experience, particularly when processing large repositories.

## Bug Fixes
###  Fixed an issue where the application appeared to hang (#63, #65)

- Fixed an issue where the application appeared to hang during the security check process on large repositories.
- Reduced the impact on the event loop to prevent hanging when processing a large number of files.
- Implemented more frequent console updates during file processing and security checks.

---
To update, simply run:
```
npm update -g repopack
```

As always, we appreciate your feedback and contributions to make Repopack even better!
</file>

<file path=".github/releases/v0.1.x/v0.1.33.md">
This release  brings improvements to the `--init` process.

## Improvements

### Enhanced `repopack --init` Process (#67)

- Separated the creation processes for `repopack.config.json` and `.repopackignore` files, allowing users more granular control over their setup.

These improvements make it easier for new users to get started with Repopack and provide a smoother configuration experience for all users.

---

To update, simply run:
```
npm update -g repopack
```

As always, we appreciate your feedback and contributions to make Repopack even better!
</file>

<file path=".github/releases/v0.1.x/v0.1.34.md">
This release focuses on improving the default ignore patterns, particularly for subdirectories.

## Improvements

### Enhanced Default Ignore Patterns (#68)

- Fixed an issue where dependency directories in subdirectories (particularly `node_modules`) were not being ignored correctly.
- Updated default ignore patterns include more comprehensive patterns:
  - Included additional common dependency directories for various languages (e.g., `vendor`, `.bundle`, `.gradle`, `target`).

---

To update, run:
```
npm update -g repopack
```

As always, we appreciate your feedback and contributions to make Repopack even better!
</file>

<file path=".github/releases/v0.1.x/v0.1.35.md">
This release introduces experimental support for custom instruction files, allowing users to provide more detailed context and guidelines for AI analysis of their projects.

## What's New

### Custom Instruction File Support (#40, #46)

- Added `output.instructionFilePath` option to configuration
  - Updated output generators to include project instructions in the output

We are introducing this feature experimentally and plan to continuously evaluate and improve it based on user feedback and real-world usage. Your insights and experiences with this new feature will be invaluable as we refine and enhance it in future updates.

Note: Custom instructions are appended at the end of the output file for optimal AI processing

For more details, see:
https://github.com/yamadashy/repopack?tab=readme-ov-file#custom-instruction

## Internal Changes

### Handlebars Integration

- Integrated Handlebars templating engine for more flexible and maintainable output generation

---

To update, simply run:
```bash
npm update -g repopack
```

As always, we appreciate your contributions to make Repopack even better!
</file>

<file path=".github/releases/v0.1.x/v0.1.36.md">
This release introduces a new configuration option that allows users to control the security check feature, providing more flexibility in how Repopack handles sensitive information detection.

## What's New

### Configurable Security Check (#74, #75)

- Added new configuration option `security.enableSecurityCheck` (default: `true`)
  - Users can now disable the security check when needed, such as when working with cryptographic libraries or known false positives

## How to Use

To **disable** the security check, add the following to your `repopack.config.json`:

```json
{
  "security": {
    "enableSecurityCheck": false
  }
}
```

**Note:** Disabling the security check may expose sensitive information. Use this option with caution and only when necessary.

---

To update, simply run:
```bash
npm update -g repopack
```

As always, we appreciate your feedback and contributions to make Repopack even better! If you encounter any issues or have suggestions regarding this new feature, please let us know through our GitHub issues.
</file>

<file path=".github/releases/v0.1.x/v0.1.37.md">
This release introduces significant improvements to Python comment removal.

## Improvements

### Enhanced Python Comment Removal (#81, #60, #55)

- Improved handling of Python comments and docstrings
  - Better support for complex scenarios including nested quotes and multi-line strings

We'd like to extend our sincere thanks to @thecurz and @KrunchMuffin for their valuable contributions to this release!

---

To update, simply run:
```bash
npm update -g repopack
```

As always, we appreciate your feedback and contributions to make Repopack even better! If you encounter any issues or have suggestions regarding these new features, please let us know through our GitHub issues.
</file>

<file path=".github/releases/v0.1.x/v0.1.38.md">
This release introduces a new Markdown output style, providing users with an additional option for formatting their repository content.

## What's New

### Markdown Output Style (#86, #87)

- Added new 'markdown' output style option
  - Users can now generate output in Markdown format, alongside existing plain text and XML options

## How to Use

To use the new Markdown output style, use the `--style markdown` option:

```bash
repopack --style markdown
```

Or update your `repopack.config.json`:

```json
{
  "output": {
    "style": "markdown"
  }
}
```

---

To update, simply run:
```bash
npm update -g repopack
```

As always, we appreciate your feedback and contributions to make Repopack even better! If you encounter any issues or have suggestions regarding this new feature, please let us know through our GitHub issues.
</file>

<file path=".github/releases/v0.1.x/v0.1.39.md">
This release focuses on improving the stability of Repopack by enhancing error handling for tiktoken-related issues. 

## Improvements

### Enhanced Error Handling for Token Counting (#89, #91)

- Improved error handling for tiktoken-related issues in the token counting process
  - Added warning logs for files that fail token counting

## How to Update

To update to the latest version, simply run:

```bash
npm update -g repopack
```

---

We appreciate your feedback and contributions to make Repopack even better! If you encounter any issues or have suggestions, please let us know through our GitHub issues.
</file>

<file path=".github/releases/v0.1.x/v0.1.40.md">
This release introduces improvements to file handling and output formatting, enhancing Repopack's functionality and user experience.

## Improvements

### Enhanced Markdown Support (#86, #95)

- Improved code block formatting in Markdown output:
  - Added language identifiers to code blocks for better syntax highlighting
  - Extended support for various file extensions to improve language detection
- Dynamic output file extension:
  - The extension of the output file now changes based on the selected style (e.g., `.md` for Markdown, `.xml` for XML)
  - This behavior only applies when no specific output file path is provided by the user

### Enhanced Exclusion of Package Manager Lock Files (#90, #94)

- Improved exclusion of common package manager lock files:
  - npm: `package-lock.json`
  - Yarn: `yarn.lock`
  - pnpm: `pnpm-lock.yaml`
  - These files are now automatically excluded from the packed output, including those in subdirectories

## How to Update

To update to the latest version, run:

```bash
npm update -g repopack
```

---

We value your feedback and contributions in making Repopack better! If you encounter any issues or have suggestions, please share them through our GitHub issues.
</file>

<file path=".github/releases/v0.1.x/v0.1.41.md">
This release brings improvements to the initialization process and adds Homebrew installation support for macOS users.

## Improvements

### Improved Initialization Process (#96)

- Reordered prompts to ask for output style before file path
- Added Markdown as a new output style option during initialization

### Homebrew Installation Support (https://github.com/Homebrew/homebrew-core/pull/192391)

- Added Homebrew installation instructions for macOS users

## How to Update/Install

To update to the latest version, run:

```bash
npm install -g repopack
```

For macOS users, you can now install Repopack using Homebrew:

```bash
brew install repopack
```

---

We value your feedback and contributions in making Repopack better! If you encounter any issues or have suggestions, please share them through our GitHub issues.
</file>

<file path=".github/releases/v0.1.x/v0.1.42.md">
This release focuses on optimizing file processing and improving overall code efficiency.

## Improvements

### Optimize File Processing (#112, #122)

- Improved the efficiency of string parsing operations
- Enhanced whitespace handling for better performance

We'd like to extend our sincere thanks to @Mefisto04 for their valuable contributions to this release!

## How to Update

To update to the latest version, run:

```bash
npm update -g repopack
```

---

We value your feedback and contributions in making Repopack better! If you encounter any issues or have suggestions, please share them through our GitHub issues.
</file>

<file path=".github/releases/v0.1.x/v0.1.43.md">
This release addresses a bug fix related to configuration validation for the Markdown output style.

## Bug Fixes

### Fixed Configuration Validation for Markdown Style (#126)

- Resolved an issue where using 'markdown' in the configuration file would trigger an invalid configuration error

We'd like to extend our sincere thanks to @r-dh for identifying and fixing this issue!

## How to Update

To update to the latest version, run:

```bash
npm update -g repopack
```

---

We value your feedback and contributions in making Repopack better! If you encounter any issues or have suggestions, please share them through our GitHub issues.
</file>

<file path=".github/releases/v0.1.x/v0.1.44.md">
This release brings several enhancements, focusing on improved performance, streamlined output generation, better error handling, and added convenience for developers.  We've also addressed a few bugs and updated dependencies for better compatibility and security.

## Improvements

* **Streamlined Output Generation**:  The output generation process has been refactored for better maintainability and efficiency. This reduces code duplication and simplifies adding new output styles in the future. Thanks @iNerdStack!
* **Optimized File Searching**: Improved error handling and efficiency in the file searching process, providing more informative error messages and faster execution. Thanks @Mefisto04!
* **Enhanced Process Concurrency**: More accurate calculation of CPU cores to optimize concurrency during file processing, leading to faster packing times. Thanks @twlite!
* **Async Timeout for Sleep**: Replaced the previous sleep implementation with `setTimeout` to avoid blocking the event loop, enhancing responsiveness. Thanks @twlite!

## Bug Fixes

* **Markdown Configuration Validation**: Resolved an issue where using 'markdown' in the configuration file would trigger an invalid configuration error. Thanks @r-dh!

## Internal Changes

* **Brew Formula Auto-Update**: Homebrew formula will now be automatically updated with each tagged release, simplifying installation and updates for macOS users. Thanks @r-dh!

* **Corrected License Link in README**: Fixed a broken link to the license in the README file. Thanks @Kaushik080!

### How to Update

To update to the latest version, run:

```bash
npm update -g repopack
```

We appreciate all contributions and feedback from our community! If you encounter any issues or have suggestions, please open an issue on GitHub.
</file>

<file path=".github/releases/v0.1.x/v0.1.45.md">
This release adds important migration notices as we prepare to transition from Repopack to Repomix.

## Important: Project Renamed to Repomix

Due to legal considerations, this project has been renamed from "Repopack" to "Repomix". We are committed to ensuring a smooth transition for all users.

### How to Migrate

We strongly recommend migrating to the new package. Install Repomix using either:

```bash
npx repomix
```

or

```bash
npm install -g repomix
```

#### Optional: Uninstall Repopack
After confirming Repomix works for your needs, you can optionally uninstall Repopack:

```bash
npm uninstall -g repopack
```

---

Thank you for being part of the Repopack community. We look forward to continuing to serve you as Repomix! If you have any questions about the migration, please feel free to create an issue on our GitHub repository.
</file>

<file path=".github/releases/v0.2.x/v0.2.1.md">
This release introduces our rename from Repopack to Repomix, along with automated migration functionality to ensure a smooth transition for all users.

## Important: Project Renamed to Repomix

Due to legal considerations, this project has been renamed from "Repopack" to "Repomix". We are committed to ensuring a smooth transition for all users.

### What's New

#### Automated Migration Support (v0.2.1)
- Added functionality to automatically detect and migrate existing Repopack configurations
- Handles migration of:
  - Configuration files (`repopack.config.json`  `repomix.config.json`)
  - Ignore files (`.repopackignore`  `.repomixignore`)
  - Instruction files (`repopack-instruction.md`  `repomix-instruction.md`)
  - Both local and global configurations
- Preserves all user settings during migration

#### Project Rename Changes (v0.2.0)
- Updated all project files and references to use the new name
- Updated npm package name to `repomix`
- Updated documentation to reflect the new name
- Added support for legacy output file detection

### How to Migrate

We strongly recommend migrating to the new package. Install Repomix using either:

```bash
npx repomix
```

or

```bash
npm install -g repomix
```

The tool will automatically detect your existing Repopack configuration files and offer to migrate them to the new format.

#### Optional: Uninstall Repopack
After confirming Repomix works for your needs, you can optionally uninstall Repopack:

```bash
npm uninstall -g repopack
```

---

Thank you for being part of our community. We look forward to continuing to serve you as Repomix! If you have any questions about the migration, please feel free to create an issue on our GitHub repository.
</file>

<file path=".github/releases/v0.2.x/v0.2.10.md">
This release introduces Docker support, making Repomix more accessible and easier to use in containerized environments. It also includes an important breaking change regarding Node.js version support.

## What's New

### Docker Support 🐳 (#221, #222)
- Added official Docker support for running Repomix. 

You can now run Repomix using Docker:
```bash
docker run -v .:/app -it --rm ghcr.io/yamadashy/repomix
```

For more detailed Docker usage instructions and examples, please see our [Docker documentation](https://github.com/yamadashy/repomix?tab=readme-ov-file#docker-usage).

Thanks to @gaby for this valuable contribution that makes Repomix more accessible to containerized environments.

## Maintenance

### Node.js Version Support (#225)
- Dropped support for Node.js 16.x as it has reached End of Life.
  - **Required Action**: Please upgrade to Node.js 18.x or later

Thanks to @chenrui333 for helping maintain our Node.js compatibility:

## How to Update

To update to the latest version, run:
```bash
npm update -g repomix
```

----

As always, we appreciate your feedback and contributions to make Repomix even better! If you encounter any issues or have suggestions, please share them through our GitHub issues.
</file>

<file path=".github/releases/v0.2.x/v0.2.11.md">
This release focuses on enhancing usability, flexibility, and remote repository handling. We've aimed to make Repomix more intuitive, particularly for those working with remote repositories or using custom configurations.

## What's New

### Support Commit SHA in --remote-branch Option (#195, #212)
- The `--remote-branch` option now supports specific commit hashes, not just branch names or tags.
  - This allows users to checkout the remote repository to a specific state using a SHA, providing finer control over remote repository fetching.
 
For more details, please see [Remote Repository Processing](https://github.com/yamadashy/repomix?tab=readme-ov-file#remote-repository-processing) in the README.

Thank you to @tranquochuy645 for this valuable contribution!

## Bug Fixes

### Fixed an issue where instruction file is not found when using a custom config file (#231)
-   The instruction file path is now resolved relative to the current working directory (CWD) instead of the location of the config file.

## How to Update

To update to the latest version, run:

```bash
npm update -g repomix
```

or if you use Homebrew

```bash
brew upgrade repomix
```

or if you use docker  🐳

```bash
docker run -v .:/app -it --rm ghcr.io/yamadashy/repomix:0.2.11
```

---

We appreciate your feedback and contributions in making Repomix better! If you encounter any issues or have suggestions, please share them through our GitHub issues.
</file>

<file path=".github/releases/v0.2.x/v0.2.12.md">
This release introduces new CLI flags to provide users with more control over the structure and content of Repomix output.

## Features

### Added CLI Flags for Output Control (#236)

This release adds new CLI flags that allow users to control the output:
-   `--no-file-summary`: Disables the file summary section in the output.
-   `--no-directory-structure`: Disables the directory structure section in the output.
-   `--remove-comments`: Enables comment removal from supported file types.
-   `--remove-empty-lines`: Enables removal of empty lines from the output.

These flags provide more granular control over the output, and can be used to override configurations from the config file.

## How to Update

To update to the latest version, run:

```bash
npm update -g repomix
```

or if you use Homebrew

```bash
brew upgrade repomix
```

or if you use docker 🐳

```bash
docker run -v .:/app -it --rm ghcr.io/yamadashy/repomix:0.2.12
```

---
We appreciate your feedback and contributions to make Repomix even better!
</file>

<file path=".github/releases/v0.2.x/v0.2.15.md">
This release marks a significant milestone for Repomix with the launch of our official website and the opening of our community Discord server! While the code changes are relatively minor, this release introduces essential resources for users to learn more about Repomix and connect with other members.

## What's New

### Official Website Launched! 🌐

- We're excited to announce the launch of the official Repomix website!
  -  Visit [repomix.com](https://repomix.com/) to explore interactive demos.
  - The website provides a convenient way to try Repomix online and understand its features.

### Community Discord Server Opened! 💬

- Join our new community Discord server!
  -  We've created a dedicated space for users to connect, ask questions, share projects, and collaborate on new ideas.
  -  Join the server here: [https://discord.gg/wNYzTwZFku](https://discord.gg/wNYzTwZFku)
  -  This is our first time running a Discord server, so any feedback is welcome! If you're experienced with Discord, please share your best practices with us!

## Try It Out and Share Your Feedback

We encourage you to explore the new website and join our Discord server. Your feedback is invaluable as we continue to improve Repomix.

- Visit the website: [https://repomix.com/](https://repomix.com/)
- Join the Discord server: [https://discord.gg/wNYzTwZFku](https://discord.gg/wNYzTwZFku)

## Internal Changes

While this release is significant due to the website and Discord launch, the actual code changes are mostly internal and related to preparing for the website's launch.

---

Thank you for your continued support of Repomix! We look forward to seeing you on the website and in our Discord community!
</file>

<file path=".github/releases/v0.2.x/v0.2.16.md">
This release focuses on improving both CLI experience and web interface functionality, along with some important infrastructure updates.

## Updates

### Token counting configurable
- Enhanced token counting with configurable encoding (default: cl100k_base)
- Add config `tokenCount.encoding`

### CLI Improvements
- Added a subtle announcement about our web version in the CLI completion message
  - Helps users discover our online version at [repomix.com](https://repomix.com)
  - The frequency of this announcement will be adjusted based on user feedback
- Removed repository URL from output files for cleaner output

## Fixes
- Fixed an issue where output paths weren't properly ignored in certain scenarios
  - Special thanks to @massdo for identifying and fixing this issue

## Internal Changes
- Updated minimum Node.js engine requirement to >=18.20.0
  - Thanks to @massdo for implementing this update

---

To update to the latest version, run:
```bash
npm update -g repomix
```

As always, we appreciate your feedback and contributions! If you encounter any issues or have suggestions, please let us know through our [GitHub issues](https://github.com/yamadashy/repomix/issues).
</file>

<file path=".github/releases/v0.2.x/v0.2.17.md">
This release fixes Node.js compatibility issues and adds comprehensive documentation to the website.

## Bug Fixes 🐛 

### Enhanced Node.js Compatibility (#274, #277)

- Fixed an issue where Repomix wasn't working properly on Node.js 19
  - Downgraded cli-spinners dependency to ensure compatibility
  - Now using version 2.9.2 which has better version support
- Extended Node.js version support:
  - Minimum required version lowered from 18.20.0 to 18.0.0
  - This change enables support for the entire Node.js 18.x LTS series

## Documentation 📚

### New Website Documentation (#269, #271, #265)
- Added comprehensive documentation at [repomix.com/guide/](https://repomix.com/guide/)
  - Detailed installation and usage instructions
  - Advanced configuration examples
  - Best practices and tips

Special thanks to @mostypc123 for their first contribution to Repomix! 

## How to Update

To update to the latest version, run:

```bash
npm update -g repomix
```

We welcome community involvement and appreciate all contributions that help make Repomix better.

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.2.md">
This release adds a new clipboard copy feature and includes several internal improvements to our CI process.

## What's New

### Copy to Clipboard Feature (#152, #160)

- Added new `--copy` option to copy the output to system clipboard
- Output can now be both saved to file and copied to clipboard in one command
- Configurable through `repomix.config.json` using `output.copyToClipboard` option

We'd like to thank @vznh for implementing this feature in their first contribution to Repomix!

## Internal Changes

### CI Improvements

- Switched to official actionlint Docker image for more reliable CI checks (@szepeviktor in #156)
- Re-added Homebrew bump workflow for automated formula updates (@chenrui333 in #151)

## How to Use

Copy output to clipboard using CLI:
```bash
repomix --copy
```

Or configure it in `repomix.config.json`:
```json
{
  "output": {
    "copyToClipboard": true
  }
}
```

## How to Update

To update to the latest version, run:
```bash
npm install -g repomix
```

For macOS users:
```bash
brew upgrade repomix
```

---

We value your feedback and contributions in making Repomix better! If you encounter any issues or have suggestions, please share them through our GitHub issues.

📢 Join our community discussion and share your experience with Repomix: https://github.com/yamadashy/repomix/discussions/154
</file>

<file path=".github/releases/v0.2.x/v0.2.20.md">
This release includes important fixes for Git Worktree support and repository name validation, improving Repomix's compatibility and stability.

## Bug Fixes 🐛

### Git Worktree Support (#279)
- Fixed an issue where Repomix fails when processing repositories created using `git worktree`
  - Now correctly handles `.git` as a reference file in worktree repositories

Special thanks to @slavashvets for discovering and fixing this issue! 

### Repository Name Validation
- Fixed an issue where `--remote` option would fail when using GitHub shorthand names containing dots (e.g., `user/repo.name`)

## How to Update

To update to the latest version, run:

```bash
npm update -g repomix
```

We welcome community involvement and appreciate all contributions that help make Repomix better.

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.21.md">
This release introduces significant improvements to output formatting and documentation, featuring a new parsable style option for enhanced XML handling.

# What's New 🚀 

## Enhanced Output Style Control (#287)
- Added new `parsableStyle` option for better output handling:
  - Ensures output strictly follows the specification of the chosen format
  - Provides properly escaped XML output with fast-xml-parser
  - Dynamically adjusts markdown code block delimiters to avoid content conflicts
- Available via CLI flag `--parsable-style` or in configuration file

Special thanks to @atollk for their first contribution!

# Documentation 📚

## README Enhancements (#296)
- Updated Homebrew installation documentation to include Linux support

Special thanks to @chenrui333 for their continued contributions!

## Website Multi-Language Support (#293)
- Enhanced multi-language support in [repomix.com](https://repomix.com)

# How to Update

To update to the latest version, run:
```bash
npm update -g repomix
```


---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.22.md">
This release introduces significant improvements to large file handling and expands the Repomix ecosystem with new tools and community channels.

# Improvements ⚡ 

## Improved Large File Handling (#302)

- Added a file size limit check (50MB) to prevent memory issues
- Graceful error handling for large files with clear user guidance:

Special thanks to @slavashvets for their continued contributions!

# Ecosystem Growth 🤝 

## New VS Code Extension (#300)
A community-created VS Code extension "Repomix Runner" is now available:
- Run Repomix directly from VS Code
- Extension by @massdo: [View on VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=DorianMassoulier.repomix-runner)

Thank you @massdo for bringing Repomix to VS Code and expanding our tooling ecosystem!

## Official Social Media
- Launched official Repomix X (Twitter) account: [@repomix_ai](https://x.com/repomix_ai)
  - Follow for updates, tips, and community highlights

# How to Update

```bash
npm update -g repomix
```

---

Join our growing community on [Discord](https://discord.gg/BF8GxZHE2C) and follow us on [X](https://x.com/repomix_ai) for updates!
</file>

<file path=".github/releases/v0.2.x/v0.2.23.md">
This release adds significant performance improvements for large repositories, making Repomix faster and more efficient when needed.

# Improvements ⚡

## Parallel Processing Enhancement (#309)
- Implemented worker threads using [Piscina](https://github.com/piscinajs/piscina) for parallel processing

### Benchmark Results
- `yamadashy.repomix`: No significant change
  - Before: 868.73 millis
  - After: 671.26 millis
- `facebook/react`: 29x faster
  - Before: 123.31 secs
  - After: 4.19 secs
- `vercel/next.js`: 58x faster
  - Before: 17.85 mins
  - After: 17.27 secs

Note: While Repomix is not primarily designed for processing large repositories, and speed is not a primary goal, faster processing can provide a better user experience when working with larger codebases.

# How to Update

```bash
npm update -g repomix
```


---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.24.md">
This release significantly enhances configuration flexibility with comprehensive CLI flag support and expands default ignore patterns for better project scaffolding. 

# What's New 🚀

## CLI Flags Revolution (#324)
- New command-line configuration now available.

```
- `--no-gitignore`: Disable .gitignore file usage
- `--no-default-patterns`: Disable default patterns
- `--header-text <text>`: Custom text to include in the file header
- `--instruction-file-path <path>`: Path to a file containing detailed custom instructions
- `--include-empty-directories`: Include empty directories in the output
```

Special recognition to @massdo for driving ecosystem growth.

# Improvements ⚡

## Enhanced Ignore Patterns (#318, #322)
- Expanded default ignores for Rust projects:
  - `target/`, `Cargo.lock`, build artifacts
  - PHP, Ruby, Go, Elixir, Haskell: package manager lock files

To @boralg for helping curate Rust-specific patterns!

# How to Update
```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.25.md">
This release brings significant improvements to output formatting and introduces flexible remote repository handling capabilities along with enhanced logging features.

# Improvements ⚡

## Remote Repository Enhancement (#335)
- Added branch/tag parsing directly from repository URLs:
```bash
repomix --remote https://github.com/yamadashy/repomix/tree/0.1.x
```
Functions identically to:
```bash
repomix --remote https://github.com/yamadashy/repomix --remote-branch 0.1.x
```

Special thanks to @huy-trn for implementing this user-friendly feature!

## Enhanced Output Formatting (#328, #329, #330)
- Added "End of Codebase" marker for better clarity in output
- Improved output header accuracy:
  - Better representation of codebase scope
  - Clear indication when using `--include` or `--ignore` options

Special thanks to @gitkenan for adding the "End of Codebase" marker and reporting the header issue!

## Path Pattern Support (#337)
- Added support for special characters in paths:
  - Handles parentheses in include patterns (e.g., `src/(categories)/**/*`)
  - Improved escaping for `[]` and `{}`
  - Essential for Next.js route groups and similar frameworks

Thank you @matheuscoelhomalta for improving path pattern support!

# How to Update

```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.26.md">
This release brings feature enhancements, documentation improvements, and website updates, along with contributions from new community members.

# What's New 🚀

## Multiple Directory Support (#338)
- Added ability to process multiple directories at once

Special thanks to @rchatrath7 for implementing this feature!

## CLI Quiet Mode Option (#347)
- Added new `--quiet` option:
  - Disables all stdout output
  - Perfect for programmatic usage when using Repomix as a library

# Improvements ⚡

## Output Enhancement (#341, #348)
- Removed generation timestamp for cleaner output
- This change reduces API costs by approximately 20-40% when using OpenAI/Anthropic APIs by preventing cache misses

Special thanks to @PaperBoardOfficial for this improvement!

## Website Enhancements: Git URL Parsing Support (#343)
- Enhanced repository URL parsing capabilities:
  - Direct support for branch URLs (`/tree/branch`)
  - Direct support for commit URLs (`/commit/hash`)

For more details on remote repository features, see [Remote Repository Processing](https://github.com/yamadashy/repomix?tab=readme-ov-file#remote-repository-processing).

# Documentation 📚

## Documentation (#344, #345)
- Added [German translation](https://repomix.com/de/) for website
- Added local development instructions for website
- Updated supported AI model list (ChatGPT, DeepSeek, Perplexity, Gemini, Gemma, Llama, Grok, and more)
- Improved existing translations

Special thanks to @SpyC0der77 for keeping our documentation consistent!

# How to Update

```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.28.md">
This release brings advanced code analysis capabilities through Tree-sitter integration, along with contributions from community members.

# What's New 🚀

## Code Compression with Tree-sitter (#336)
- Added intelligent code compression feature for optimizing LLM prompts
  - Implemented language-specific Tree-sitter queries for accurate code parsing
  - Supports multiple languages including JavaScript/TypeScript, Python, Rust, Go, C/C++, C#, Ruby, Java, PHP, and Swift

> [!NOTE]
> This is an experimental feature that we'll be actively improving based on user feedback and real-world usage
> Known issue: https://github.com/yamadashy/repomix/issues/359

### Example
Using compression via CLI:
```bash
repomix --compress
```

Before:
```typescript
const calculateTotal = (items: ShoppingItem[]) => {
  let total = 0;
  for (const item of items) {
    total += item.price * item.quantity;
  }
  return total;
}
interface Item {
  name: string;
  price: number;
  quantity: number;
}
```

After compression:
```typescript
const calculateTotal = (items: ShoppingItem[]) => {
interface Item {
```

Special thanks to @huy-trn for the initial implementation of this feature! His groundwork with Tree-sitter integration laid the foundation for this powerful enhancement to Repomix. 

# How to Update

```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.29.md">
This release introduces a major new feature for file uploads, along with improvements to library usage and default ignore patterns.

# What's New 🚀

## Website: File Upload Support (#353, #310)
- Added support for uploading ZIP files directly through the web interface (https://repomix.com/)

<img width="962" alt="image" src="https://github.com/user-attachments/assets/58069431-7e45-487b-94df-c3eeb2ef8695" />

Special thanks to @PaperBoardOfficial for implementing this significant feature!

# Improvements ⚡

## Enhanced Default Ignore Patterns (#364)
- Improved subdirectory matching in default ignore patterns using `**/`

## Library Usage Enhancement (#363)
- Added additional exports to support using Repomix as a library

# How to Update

```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.3.md">
This release introduces enhanced security features and improved error handling, making Repomix more robust and user-friendly.

## Improvements

### Enhanced File System Permission Handling (#165)
- Added comprehensive permission checks for directory scanning
- Improved error messages with clear remediation steps, especially for macOS security restrictions
- Added detailed guidance in CLI output when permission issues are encountered

### Node.js 23 Support (#166)
- Added full support for Node.js 23

### Improved Error Handling and Validation (#167, #171)
- Implemented robust configuration validation system
- Added clear, actionable error messages for configuration issues
- Enhanced error recovery and reporting across core functionalities

## How to Update

To update to the latest version, run:
```bash
npm update -g repomix
```

---

We value your feedback and contributions in making Repomix better! If you encounter any issues or have suggestions, please share them through our GitHub issues.
</file>

<file path=".github/releases/v0.2.x/v0.2.30.md">
This release addresses a file system permission issue and adds support for more flexible configuration formats.

# Improvements ⚡

## Configuration Flexibility (#346, #366)
- Added support for JSON5 in configuration files
  - More flexible and developer-friendly configuration format
  - Allows comments and trailing commas

# Bug Fixes 🐛
## File System Handling (#372, #374)
- Removed unnecessary write permission check on source directories

# How to Update

```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.32.md">
The code compression feature introduced in [v0.2.28](https://github.com/yamadashy/repomix/releases/tag/v0.2.28) has been enhanced! 🚀 

# Improvements ⚡

## Enhanced Code Compression (#380)
- Now includes comments and import statements in compression output:
  - Preserves both single-line and multi-line comments
  - Keeps import/require statements for better code context
- Complete type definition support for TypeScript, Python, and Go:
  - Full inclusion of interface and type definitions
- Enhanced function signature preservation:
  - Captures complete function signatures including arguments spanning multiple lines
  - Ensures accurate preservation of all function parameters


### Example
Using compression via CLI:
```bash
repomix --compress
```

Before:
```typescript
import { ShoppingItem } from './shopping-item';

/**
 * Calculate the total price of shopping items
 */
const calculateTotal = (
  items: ShoppingItem[]
) => {
  let total = 0;
  for (const item of items) {
    total += item.price * item.quantity;
  }
  return total;
}

// Shopping item interface
interface Item {
  name: string;
  price: number;
  quantity: number;
}
```

After compression:
```typescript
import { ShoppingItem } from './shopping-item';
⋮----
/**
 * Calculate the total price of shopping items
 */
const calculateTotal = (
  items: ShoppingItem[]
) => {
⋮----
// Shopping item interface
interface Item {
  name: string;
  price: number;
  quantity: number;
}
```


# How to Update

```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.33.md">
This release addresses two important issues to improve code handling and file output capabilities.

# Bug Fixes 🐛

## TypeScript Import Handling for Compressed Output (#382)
- Fixed an issue where named imports were partially excluded when using compress mode
  - Now properly preserves all import statements including named imports like `import { Component } from 'module'`

## Directory Structure Support for Output Files (#378, #383)
- Fixes related issue (#378) where nested output paths would fail, especially with remote repositories
  - Now automatically creates parent directories when writing to nested output paths

# How to Update

```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.34.md">
This release fixes an important configuration issue affecting negative boolean options in Repomix.

## Bug Fixes 🐛

### Configuration Handling Fix (#385, #389)
- Fixed an issue where setting `false` values in the config file for certain options (like `"fileSummary": false`) was not being respected
- Properly handles all `--no-*` style CLI options when specified in the config file
- Affected options include:
  - `fileSummary`
  - `directoryStructure`
  - `gitignore`
  - `defaultPatterns`
  - `securityCheck`

Special thanks to @mapleroyal for reporting this issue!

## How to Update

```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our [GitHub issues](https://github.com/yamadashy/repomix/issues) or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.35.md">
This release adds folder upload capability to the website, improves gitignore handling, and includes documentation updates.

## What's New 🚀

### Website Folder Upload (#387, #377)
* Added folder upload option to the https://repomix.com
  * Supports drag & drop or folder browser selection

Thank you @PaperBoardOfficial for implementing folder upload on our website!

## Improvements ⚡️

### Enhanced Gitignore Support (#391, #375)
* Now uses the contents of `.git/info/exclude` when `useGitignore` is set to true
* Allows for local-only file exclusions without modifying the shared `.gitignore`
* Fixes issue #375

Thanks to @motlin for improving gitignore support! 

## How to Update

```
npm update -g repomix
```

--------

As always if you encounter any issues or have suggestions please let us know through our GitHub issues or join our Discord community https://discord.gg/wNYzTwZFku for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.36.md">
This release adds MCP server support, improves ignore pattern handling on the website, and includes dependency updates.

## What's New 🚀

### MCP Server Support (#399)
* Added initial implementation of the [Model Context Protocol (MCP)](https://modelcontextprotocol.io) server
  * Allows AI assistants to directly interact with your codebase without manual file preparation
  * Provides two powerful tools:
    * `pack_codebase`: Package local code directories for AI analysis
    * `pack_remote_repository`: Fetch, clone and package GitHub repositories

We've also submitted Repomix to the MCP marketplace:
- https://github.com/cline/mcp-marketplace/issues/64

To use Repomix as an MCP server with Cline (VS Code extension), edit the `cline_mcp_settings.json` file:
```json
{
  "mcpServers": {
    "repomix": {
      "command": "npx",
      "args": [
        "-y",
        "repomix",
        "--mcp"
      ]
    }
  }
}
```

<img width="520" alt="image" src="https://github.com/user-attachments/assets/c698e8ba-91bb-4207-b0fe-ba0a56871975" />

For more details, please refer to the documentation:
https://github.com/yamadashy/repomix#mcp-integration

## Improvements ⚡️

### Enhanced Ignore Pattern Support (#396)
* Now allows special characters like `!` `(` `)` in ignore patterns via the website

**Known Issue**: There's currently an issue where negation patterns (`!`) don't work correctly. See [Issue #400](https://github.com/yamadashy/repomix/issues/400) for details.

Thank you @eastlondoner for your first contribution to the project!

## How to Update

```
npm update -g repomix
```

--------

As always if you encounter any issues or have suggestions please let us know through our GitHub issues or join our Discord community https://discord.gg/wNYzTwZFku for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.4.md">
This release introduces enhanced directory handling capabilities and includes several improvements to core functionality, making Repomix more versatile and reliable.

## What's New

### Empty Directory Support (#180, #161)
- Added new option `includeEmptyDirectories`  to include empty directories in repository structure

To include empty directories in your output, add the following to your `repomix.config.json`:

```json
{
  "output": {
    "includeEmptyDirectories": true
  }
}
```

We'd like to thank @iNerdStack for implementing this feature in their contribution to Repomix!

## Improvements

### Statistics Formatting Enhancement (#177)
- Added number formatting for improved readability
- Fixed token calculation for more accurate reporting

## How to Update

To update to the latest version, run:

```bash
npm update -g repomix
```

---

We value your feedback and contributions in making Repomix better! If you encounter any issues or have suggestions, please share them through our GitHub issues.
</file>

<file path=".github/releases/v0.2.x/v0.2.40.md">
This release brings significant enhancements to Model Context Protocol (MCP) integration and improves file handling capabilities.

## Improvements ⚡

### Enhanced MCP Integration (#419, #415, #409, #413)
- Added file and directory reading capabilities with integrated [Secretlint](https://github.com/secretlint/secretlint) security checks
- Introduced result retrieval tools for Claude Desktop and Cursor AI assistants
 
**Pack local repo with compress:**
```bash
Please pack this with compress in repomix.
<path>
```

![MCP Integration - Command Example](https://github.com/user-attachments/assets/6eb70126-ed60-4d5e-956d-1454ab7bfd41)

**Read detailed results:**
![MCP Integration - Results View](https://github.com/user-attachments/assets/db536a6d-c164-4426-9993-25fbff21ffa5)

For more MCP details, please refer to the documentation:
https://github.com/yamadashy/repomix#mcp-integration

### Extended File Format Support (#407)
- Added support for Bun lockfile format (`bun.lockb`)

Special thanks to @jiftoo for their first contribution!

## How to Update

```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.41.md">
This release introduces Git-based file sorting and enhances file compression capabilities.

## What's New 🚀

### Git-based File Sorting (#356, #421)
* Added ability to sort files by Git commit frequency
  * Prioritizes frequently modified files in the output
* Can be controlled via CLI options or configuration
  * Use `--no-git-sort-by-changes` flag to disable Git-based sorting
  * Configure in repomix.config.json:
    ```json
    {
      "output": {
        "git": {
          "sortByChanges": true,
          "sortByChangesMaxCommits": 100
        }
      }
    }
    ```
Special thanks to @SpyC0der77 for suggesting this feature!

## Improvements ⚡️

### Enhanced Compress Mode (#420)
* Added Vue.js and CSS file support for compress mode

## How to Update

```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.2.x/v0.2.5.md">
## Bug Fixes

### Fixed Missing Dependency (#186)
- Added missing `minimatch` dependency

## How to Update

To update to the latest version, run:

```bash
npm update -g repomix
```

---

We value your feedback and contributions in making Repomix better! If you encounter any issues or have suggestions, please share them through our GitHub issues.
</file>

<file path=".github/releases/v0.2.x/v0.2.6.md">
This release introduces remote repository features and security check improvements.

## What's New

### Enhanced Remote Repository Support (#196, #199)
- Added new `--remote-branch` option for cloning specific branches

Example usage:
```bash
# Clone a specific branch
repomix --remote user/repo --remote-branch develop
```

Special thanks to @tranquochuy645 for their first contribution, adding the remote branch feature!

### Security Check Improvements (#191, #201)
- Added `--no-security-check` command line option for more control over security checking
- Enables bypassing security checks when needed (e.g., when working with cryptographic libraries)

## How to Update

To update to the latest version, run:
```bash
npm update -g repomix
```

---

We value your feedback and contributions in making Repomix better! If you encounter any issues or have suggestions, please share them through our GitHub issues.
</file>

<file path=".github/releases/v0.2.x/v0.2.7.md">
This release focuses on improving code quality and performance, particularly when processing large codebases.

## Improvements

### JSON Configuration Improvements (#209, #214)
- Added support for inline and block comments in repomix.config.json

Special thanks to @ivanionut for improving JSON configuration handling with their first contribution!

### Enhanced File Processing Performance (#208, #223)
- Optimized file processing efficiency when removeComments and removeEmptyLines are enabled

## Internal Changes

### Code Reorganization (#217)
- Refactored packager.ts into smaller, single-purpose functions
- Improved code maintainability while preserving functionality

Special thanks to @mikelovesrobots for the excellent refactoring work on their first contribution! The changes have made the codebase more maintainable for future development.

To update to the latest version, run:
```bash
npm update -g repomix
```

---

As always, we appreciate your feedback and contributions to make Repomix even better! If you encounter any issues or have suggestions, please share them through our GitHub issues.
</file>

<file path=".github/releases/v0.2.x/v0.2.8.md">
This release introduces new configuration options to control the output of the file summary and directory structure sections, providing more flexibility in customizing the output.

## What's New

### Customizable File Summary and Directory Structure Output (#206, #224)

- Added `output.fileSummary` option (default: `true`): Controls whether to include the file summary section at the beginning of the output.
- Added `output.directoryStructure` option (default: `true`): Controls whether to include the directory structure in the output.

These options allow you to tailor the output to your specific needs. For example:

-   You can omit the file summary and directory structure to reduce token usage when interacting with LLMs.
-   You can include only necessary sections to generate output optimized for specific AI models.

**Example Configuration:**

```json5
{
  "output": {
    "fileSummary": false,
    "directoryStructure": true,
    // ... other settings
  }
}
```


To update to the latest version, run:
```bash
npm update -g repomix
```

---

As always, we appreciate your feedback and contributions to make Repomix even better! If you encounter any issues or have suggestions, please share them through our GitHub issues.
</file>

<file path=".github/releases/v0.3.x/v0.3.0.md">
> [!IMPORTANT]
> The default output format has been changed to XML in this release.

This version has been bumped to 0.3.0 not because of a major update, but due to a breaking change in the default output format. It represents an important improvement for anyone installing Repomix for the first time.

## Breaking Changes 🔄

### Default Output Format Changed to XML (#422)
- The default output format has been changed to XML
  - XML format provides better parsing accuracy for AI models (especially Claude)
  - Other formats (Markdown, Plain Text) remain available via the `--style` option

## How to Update

```bash
npm update -g repomix
```

---

If you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.3.x/v0.3.1.md">
This release introduces enhancements including improved comment removal support for C++, code compression features for Solidity, and MCP improvements.

## Improvements ⚡️

### C++ Comment Removal Enhancement (#435)
- Added support for comment removal `--remove-comments` in C++ file extensions:
  - .h, .hpp (header files)
  - .cpp, .cc, .cxx (source files)

Special thanks to @AdijeShen for this valuable contribution in expanding C++ support!

### Solidity Support Enhancement (#436)
- Added compression support `--compress` for Solidity files
- Implemented comment removal `--remove-comments` functionality

### MCP Resource Enhancement (#426, #434)
- Enhanced read_repomix_output tool functionality:
  - Now includes output as a resource

### Default Ignore Pattern Enhancement (#428)
- Added `uv.lock` to the default ignore list

## Documentation 📚

### French Documentation (#429)
- Added comprehensive French guides for installation and usage

https://repomix.com/fr/

## How to Update

To update to the latest version, run:
```bash
npm update -g repomix
```

---

If you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.3.x/v0.3.2.md">
Repomix v0.3.2 brings various improvements including website functionality improvements, better CLI usability, and improved glob pattern handling reliability.

## What's New 🚀

### Website Compression Functionality (#448)
- Improved processing efficiency on the [repomix.com](https://repomix.com/), enabling smoother processing of large repositories directly from the browser.

<img width="233" alt="image" src="https://github.com/user-attachments/assets/19d72c83-7eea-492e-a2ec-d6ed93f0f846" />

## Improvements ⚡

### Semantic Suggestion System for CLI (#452)
Added functionality that automatically suggests correct options when incorrect option names are entered.

Special thanks to @pranshugupta01 for this thoughtful usability enhancement that makes the CLI experience much more intuitive for users!

### Glob Pattern Handling Improvements
- Automatically removes extra whitespace from comma-separated glob patterns (#464)
- Consistently handles directory patterns with trailing slashes, making `folder/` and `folder` patterns behave the same way (#453)
- Improved brace expansion and whitespace handling in CLI pattern options for more accurate and predictable behavior with complex glob patterns (#469)

Special thanks to @pranshugupta01 for these meticulous pattern handling improvements that make file filtering more reliable and predictable!

## Documentation 📚

### VS Code Server Installation Docs (#439)
👇🏻 Click to open VS Code with the Repomix MCP server pre-configured:

[![Install in VS Code](https://img.shields.io/badge/VS_Code-Install_Server-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=repomix&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22repomix%22%2C%22--mcp%22%5D%7D)

Special thanks to @burkeholland for this excellent contribution that makes the integration with VS Code more seamless and user-friendly!

### Ensured consistency across all documentation regarding the default output format change to XML (#466)

Special thanks to @yoshi-taka for the careful attention to documentation consistency across the project!

## How to Update

```bash
npm install -g repomix@latest
```

---

If you encounter any issues or have suggestions, please let us know through [GitHub Issues](https://github.com/yamadashy/repomix/issues) or join our [Discord community](https://discord.gg/wNYzTwZFku).
</file>

<file path=".github/releases/v0.3.x/v0.3.3.md">
Repomix v0.3.3 brings metadata-only output, expanded library support, Wayland clipboard compatibility, and various improvements for better usability and maintainability.

## What's New 🚀

### No Files Output Mode `--no-files` (#475, #491)
- Added the ability to generate output containing only metadata, excluding file contents, using the `--no-files` flag.
  - Useful for fast analysis of large repositories or when you want to avoid including file bodies.

### Wayland Clipboard `wl-copy` Support (#484)
- Clipboard copy now works on Linux Wayland environments using `wl-copy`.
  - The `--copy` option is now fully supported on Wayland.

Special thanks to @pmdyy for adding Wayland clipboard support!

### Expanded Core Exports for Library Usage (#504, #492)
- More core functions are now exported for direct use when integrating Repomix as a Node.js library.

Special thanks to @riqwan for contributing to the core export improvements!

> [!TIP]
> Want to use Repomix as a library in your Node.js project?  
> See the official guide here: [Using Repomix as a Library](https://repomix.com/guide/development/using-repomix-as-a-library)

## Improvements ⚡

### Various Maintenance & Fixes (#496, #497, #499)
- Spellcheck now includes dot files.
- Fixed `.editorconfig` and EditorConfig violations.

Special thanks to @szepeviktor for maintenance improvements!

## How to Update

```bash
npm install -g repomix@latest
```

---

If you encounter any issues or have suggestions, please let us know through [GitHub Issues](https://github.com/yamadashy/repomix/issues) or join our [Discord community](https://discord.gg/wNYzTwZFku).
</file>

<file path=".github/releases/v0.3.x/v0.3.5.md">
This release introduces git diff support, CLI output enhancements, GitHub Actions support, and website-based URL input history management. It also includes several documentation improvements and Node.js compatibility updates.

## What's New 🚀

### Git Diff Support (#533)
- Added git diff support with `--include-diffs` flag
  - Includes git diffs in the output, covering both staged and unstaged changes for better context

Special thanks to @pmdyy for this contribution!

### CLI Output Enhancement (#534)
- Added `--stdout` option for CLI output  
  - Provides more flexibility for integrating Repomix in scripts and pipelines
    ```bash
    # Send output to stdout, then pipe into another command (for example, simonw/llm)
    repomix --stdout | llm "Please explain what this code does."
    ```

### GitHub Actions Support (#510, #528)
- Added GitHub Action for integrating Repomix into CI/CD workflows  

See full usage at [repomix.com/guide/github-actions](https://repomix.com/guide/github-actions).

## Improvements ⚡

### MCP Tool Annotations Support (#537)  
- Added support for Model Context Protocol (MCP) [tool annotations](https://modelcontextprotocol.io/docs/concepts/tools#tool-annotations)

### Website URL Input History (#527)
- Added input history management for repository URLs on the website  

<img width="509" alt="image" src="https://github.com/user-attachments/assets/05615e8f-01d2-45fd-9fb0-71d7d2c93a66" />

### Node 24 Support
- Added support for Node.js v24 (#543)  

## Documentation 📚
- Added Chinese (Traditional) documentation (#526)  

## How to Update

```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.3.x/v0.3.6.md">
This release enhances header configuration control, adds JSON Schema validation, and improves Docker integration for the MCP server with comprehensive documentation updates.

## Improvements ⚡

### Enhanced `--no-file-summary` Option (#556)
- `--no-file-summary` now also suppresses the generation header
  - Header text (`headerText`) is still displayed, maintaining custom messages
  - Users can now control headers more flexibly and intuitively, showing custom headers while hiding Repomix-generated content

Special thanks to @joshwand for this significant improvement!

### JSON Schema Configuration Validation (#570)
- Added JSON schema for `repomix.config.json` validation
  - Enables auto-completion and validation in supported editors
  - Improves developer experience in VSCode and other editors with JSON schema support
```json
{
  "$schema": "https://repomix.com/schemas/latest/schema.json",
  "output": {
    "filePath": "repomix-output.md",
    "style": "markdown"
  }
}
```

## Documentation 📚

### Docker Configuration for MCP Server (#559)
- Added Docker container support for running Repomix as an MCP server
```json
{
  "mcpServers": {
    "repomix-docker": {
      "command": "docker",
      "args": [
        "run",
        "-i",
        "--rm",
        "ghcr.io/yamadashy/repomix",
        "--mcp"
      ]
    }
  }
}
```

## How to Update

```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path=".github/releases/v0.3.x/v0.3.7.md">
This release brings major enhancements to the MCP (Model Context Protocol) server and improved remote repository handling.

## What's New 🚀

### MCP Tool Grep Functionality (#590)

We've added a powerful `grep_repomix_output` tool to the Repomix MCP server! This feature enables AI assistants to perform advanced searches within packaged codebases. Additionally, the `read_repomix_output` tool now supports partial content retrieval.

<img width="754" alt="image" src="https://github.com/user-attachments/assets/cc656d86-b692-4e8b-be80-122b957a9a9d" />

This functionality allows AI assistants to efficiently search for specific patterns in codebases and retrieve results with surrounding context.
By combining the `grep_repomix_output` and `read_repomix_output` tools, repository analysis is now possible without fetching the entire output, making it particularly useful for analyzing medium to large-scale repositories.

For MCP setup instructions, see:
https://github.com/yamadashy/repomix?tab=readme-ov-file#mcp-server-integration

## Improvements ⚡

### CLI Help Group Feature Implementation (#578)

The CLI help display has been improved. Options are now organized into logical groups for better usability:

```bash
$ repomix -h
Usage: repomix [options] [directories...]

Repomix - Pack your repository into a single AI-friendly file

Arguments:
  directories                        list of directories to process (default: ["."])

Basic Options
  -v, --version                      show version information

Output Options
  -o, --output <file>                specify the output file name
  --stdout                           output to stdout instead of writing to a file
  --style <type>                     specify the output style (xml, markdown, plain)
  --parsable-style                   by escaping and formatting, ensure the output is parsable as a
                                     document of its type
  --compress                         perform code compression to reduce token count
  
Filter Options
  --include <patterns>               list of include patterns (comma-separated)
  -i, --ignore <patterns>            additional ignore patterns (comma-separated)

...
```

### Enhanced Remote Repository Reference Handling (#583, #592)

Remote repository processing has become more robust with improved URL handling:

- The `--remote` option now handles URLs more precisely by reading refs to correctly distinguish between branch names and folder paths
- Proper identification and processing of remote branches and tags
- Better handling of repository paths and subdirectories

## How to Update

```bash
npm update -g repomix
```

---

As always, if you have any issues or suggestions, please let us know on GitHub issues or our [Discord community](https://discord.gg/wNYzTwZFku).
</file>

<file path=".github/releases/v0.3.x/v0.3.8.md">
This release brings major updates including browser extension support, extensive multilingual expansion, and enhanced mobile experience.

## What's New 🚀

### Browser Extension (#612)
Introducing a browser extension that provides instant access to Repomix from any GitHub repository! The Chrome extension adds a convenient "Repomix" button to GitHub repository pages.

[![image](https://github.com/user-attachments/assets/ca81bd58-f2a9-4184-ae43-18ed52294dad)](https://chromewebstore.google.com/detail/repomix/fimfamikepjgchehkohedilpdigcpkoa)

#### Installation
- Chrome Extension: [Repomix - Chrome Web Store](https://chromewebstore.google.com/detail/repomix/fimfamikepjgchehkohedilpdigcpkoa)
- Firefox Add-on: [Repomix - Firefox Add-ons](https://addons.mozilla.org/firefox/addon/repomix/)

#### Key Features
- One-click access to any GitHub repository
- More exciting features coming soon!

### Website: Open with your app (#616)
📱 You can now send Repomix output directly to Claude or Gemini on mobile!

Perfect when you're on the go and need to analyze a GitHub repo fast  just tap "Open with your app" to share it to your favorite chat app.

Try it on [repomix.com](https://repomix.com)!

https://github.com/user-attachments/assets/c2059c65-3891-4400-8d09-e976a268d93a

### `.jsonc` and `.json5` Configuration File Support (#620)
Added support for `.jsonc` and `.json5` configuration file extensions with priority ordering.
```json5
// repomix.jsonc or repomix.json5
{
  // Comments are now supported!
  "include": ["src/**"],
  "exclude": ["**/*.test.js"]
}
```

## Documentation 📚

### Multilingual Support Expansion (#602, #603, #607)
Added three new languages to the website:
- **Indonesian (id)**: Bahasa Indonesia support
- **Vietnamese (vi)**: Tiếng Việt support  
- **Hindi (hi)**: हिन्दी support

This brings our total language support to 12 languages.

## How to Update

```bash
npm update -g repomix
```

---

As always, if you have any issues or suggestions, please let us know on GitHub issues or our [Discord community](https://discord.gg/wNYzTwZFku).
</file>

<file path=".github/releases/v0.3.x/v0.3.9.md">
This release brings important improvements to CLI reliability and enhanced documentation for power users.

## What's New 🚀

### CLI Exit Code Enhancement (#632)
Repomix now properly sets exit codes when operations fail, significantly improving CI/CD integration and error handling workflows. This enhancement ensures that build pipelines and automation scripts can correctly detect and respond to Repomix failures.

Special thanks to @sakamossan for implementing this important feature! 

## How to Update

```bash
npm update -g repomix
```

---

As always, if you have any issues or suggestions, please let us know on GitHub issues or our [Discord community](https://discord.gg/wNYzTwZFku).
</file>

<file path=".github/pull_request_template.md">
<!-- Please include a summary of the changes -->

## Checklist

- [ ] Run `npm run test`
- [ ] Run `npm run lint`
</file>

<file path="browser/CLAUDE.md">
# Browser Extension Guidelines

This file provides guidance for working with the Repomix browser extension.

## Project Overview

Cross-browser extension (Chrome/Firefox/Edge) that adds Repomix integration to GitHub repository pages. Uses Manifest V3 with content scripts to inject a "Repomix" button directly into GitHub's UI.

## Directory Structure

```
browser/
├── app/                    # Extension source code
   ├── _locales/          # Internationalization files (11 languages)
   ├── images/            # Extension icons (16px to 128px)
   ├── manifest.json      # Extension manifest (Manifest V3)
   ├── scripts/           # TypeScript source files
      ├── background.ts  # Service worker (background script)
      └── content.ts     # Content script for GitHub integration
   └── styles/            # CSS styles for injected elements
├── dist/                  # Built extension files (generated)
├── promo/                 # Store promotional materials
└── tests/                 # Test files
```

## Development Commands

```bash
npm run dev chrome     # Development mode for Chrome
npm run build-all      # Build for all browsers
npm run lint          # TypeScript type checking
npm run test          # Run tests
npm run generate-icons # Generate icon set from SVG
```

## Internationalization

### Supported Languages (11 total)
English, Japanese, German, French, Spanish, Portuguese (Brazilian), Indonesian, Vietnamese, Korean, Chinese (Simplified/Traditional), Hindi.

### Adding New Languages
1. Create directory in `app/_locales/[language_code]/`
2. Add `messages.json` with required keys:
   - `appName`, `appDescription`, `buttonText`
3. Add `detailed-description.txt` for store descriptions
4. Test extension loads correctly with new locale
</file>

<file path="browser/README.md">
# Repomix Extension

A browser extension that adds a Repomix button to GitHub repository pages.

## 🚀 Features

- Adds a "Repomix" button to GitHub repository pages
- One-click redirect to Repomix (https://repomix.com)
- Seamlessly integrates with GitHub's UI design
- Works on Chrome, Firefox, and Edge

## 🛠️ Usage

1. Install the browser extension
2. Navigate to any GitHub repository page
3. A "Repomix" button will appear in the page header action area
4. Click the button to open the repository in Repomix

## 💻 Development

### Prerequisites

- Node.js 22 or higher

### Setup

```bash
# Install dependencies
npm install

# Generate icons
npm run generate-icons

# Development mode for Chrome
npm run dev chrome

# Development mode for Firefox
npm run dev firefox

# Development mode for Edge
npm run dev edge
```

### Build

```bash
# Build for all browsers
npm run build-all

# Build for specific browsers
npm run build chrome
npm run build firefox
npm run build edge
```

Built files will be generated in the `dist/` folder.

### Manual Installation

1. Run `npm run build chrome` to build
2. Open `chrome://extensions/` in Chrome
3. Enable "Developer mode"
4. Click "Load unpacked extension"
5. Select the `dist/chrome` folder

## 📝 Technical Specifications

- **Manifest V3** - Latest browser extension specification
- **Content Scripts** - Direct button injection into GitHub pages
- **Internationalization** - English and Japanese support
- **Cross-browser** - Chrome, Firefox, Edge support

## 🔒 Privacy

This extension:
- Does not collect any data
- Does not track user behavior
- Only accesses github.com
- Requires minimal permissions
</file>

<file path="src/cli/actions/defaultAction.ts">
import path from 'node:path';
import { loadFileConfig, mergeConfigs } from '../../config/configLoad.js';
import {
  type RepomixConfigCli,
  type RepomixConfigFile,
  type RepomixConfigMerged,
  type RepomixOutputStyle,
  repomixConfigCliSchema,
} from '../../config/configSchema.js';
import { readFilePathsFromStdin } from '../../core/file/fileStdin.js';
import { type PackResult, pack } from '../../core/packager.js';
import { RepomixError } from '../../shared/errorHandle.js';
import { rethrowValidationErrorIfZodError } from '../../shared/errorHandle.js';
import { logger } from '../../shared/logger.js';
import { splitPatterns } from '../../shared/patternUtils.js';
import { printCompletion, printSecurityCheck, printSummary, printTopFiles } from '../cliPrint.js';
import { Spinner } from '../cliSpinner.js';
import type { CliOptions } from '../types.js';
import { runMigrationAction } from './migrationAction.js';
⋮----
export interface DefaultActionRunnerResult {
  packResult: PackResult;
  config: RepomixConfigMerged;
}
⋮----
export const runDefaultAction = async (
  directories: string[],
  cwd: string,
  cliOptions: CliOptions,
): Promise<DefaultActionRunnerResult> =>
⋮----
// Run migration before loading config
⋮----
// Load the config file
⋮----
// Parse the CLI options into a config
⋮----
// Merge default, file, and CLI configs
⋮----
// Route to appropriate processing workflow
⋮----
/**
 * Handles stdin processing workflow for file paths input.
 */
export const handleStdinProcessing = async (
  directories: string[],
  cwd: string,
  config: RepomixConfigMerged,
  cliOptions: CliOptions,
): Promise<DefaultActionRunnerResult> =>
⋮----
// Validate directory arguments for stdin mode
⋮----
// Use pack with predefined files from stdin
⋮----
/**
 * Handles normal directory processing workflow.
 */
export const handleDirectoryProcessing = async (
  directories: string[],
  cwd: string,
  config: RepomixConfigMerged,
  cliOptions: CliOptions,
): Promise<DefaultActionRunnerResult> =>
⋮----
/**
 * Prints the results of packing operation including top files, security check, summary, and completion.
 */
const printResults = (cwd: string, packResult: PackResult, config: RepomixConfigMerged): void =>
⋮----
/**
 * Builds CLI configuration from command-line options.
 *
 * Note: Due to Commander.js behavior with --no-* flags:
 * - When --no-* flags are used (e.g., --no-file-summary), the options explicitly become false
 * - When no flag is specified, Commander defaults to true (e.g., options.fileSummary === true)
 * - For --no-* flags, we only apply the setting when it's explicitly false to respect config file values
 * - This allows the config file to maintain control unless explicitly overridden by CLI
 */
export const buildCliConfig = (options: CliOptions): RepomixConfigCli =>
⋮----
// Only apply gitignore setting if explicitly set to false
⋮----
// Only apply defaultPatterns setting if explicitly set to false
⋮----
// Only apply securityCheck setting if explicitly set to false
⋮----
// Only apply fileSummary setting if explicitly set to false
⋮----
// Only apply directoryStructure setting if explicitly set to false
⋮----
// Only apply files setting if explicitly set to false
⋮----
// Only apply gitSortByChanges setting if explicitly set to false
</file>

<file path="src/cli/actions/initAction.ts">
import fs from 'node:fs/promises';
import path from 'node:path';
⋮----
import pc from 'picocolors';
import {
  type RepomixConfigFile,
  type RepomixOutputStyle,
  defaultConfig,
  defaultFilePathMap,
} from '../../config/configSchema.js';
import { getGlobalDirectory } from '../../config/globalDirectory.js';
import { getVersion } from '../../core/file/packageJsonParse.js';
import { logger } from '../../shared/logger.js';
⋮----
const onCancelOperation = () =>
⋮----
export const runInitAction = async (rootDir: string, isGlobal: boolean): Promise<void> =>
⋮----
// Step 1: Ask if user wants to create a config file
⋮----
// Step 2: Ask if user wants to create a .repomixignore file
⋮----
export const createConfigFile = async (rootDir: string, isGlobal: boolean): Promise<boolean> =>
⋮----
// File doesn't exist, so we can proceed
⋮----
export const createIgnoreFile = async (rootDir: string, isGlobal: boolean): Promise<boolean> =>
⋮----
// File doesn't exist, so we can proceed
</file>

<file path="src/cli/actions/mcpAction.ts">
import { runMcpServer } from '../../mcp/mcpServer.js';
import { logger } from '../../shared/logger.js';
⋮----
export const runMcpAction = async (): Promise<void> =>
</file>

<file path="src/cli/actions/migrationAction.ts">
import path from 'node:path';
⋮----
import pc from 'picocolors';
import { getGlobalDirectory } from '../../config/globalDirectory.js';
import { logger } from '../../shared/logger.js';
⋮----
interface MigrationPaths {
  oldConfigPath: string;
  newConfigPath: string;
  oldIgnorePath: string;
  newIgnorePath: string;
  oldInstructionPath: string;
  newInstructionPath: string;
  oldOutputPaths: string[];
  newOutputPaths: string[];
  oldGlobalConfigPath: string;
  newGlobalConfigPath: string;
}
⋮----
interface MigrationResult {
  configMigrated: boolean;
  ignoreMigrated: boolean;
  instructionMigrated: boolean;
  outputFilesMigrated: string[];
  globalConfigMigrated: boolean;
  error?: Error;
}
⋮----
/**
 * Check if a file exists at the given path
 */
const fileExists = async (filePath: string): Promise<boolean> =>
⋮----
/**
 * Replace all occurrences of 'repopack' with 'repomix' in a string
 */
const replaceRepopackString = (content: string): string =>
⋮----
/**
 * Update file content by replacing 'repopack' with 'repomix'
 */
const updateFileContent = async (filePath: string): Promise<boolean> =>
⋮----
// Check if content needs to be updated
⋮----
/**
 * Parse JSON content, update instructionFilePath if exists
 */
const updateInstructionPath = (content: string): string =>
⋮----
// Also update output.filePath if it exists
⋮----
/**
 * Get output file paths pairs
 */
const getOutputFilePaths = (rootDir: string):
⋮----
/**
 * Migrate a single file from old path to new path
 */
const migrateFile = async (
  oldPath: string,
  newPath: string,
  description: string,
  isConfig = false,
): Promise<boolean> =>
⋮----
// Read and update content
⋮----
// For config files, also update instructionFilePath and output.filePath
⋮----
// Ensure the target directory exists
⋮----
// Write to new file
⋮----
// Remove old file
⋮----
/**
 * Update content of gitignore and repomixignore files
 */
const updateIgnoreFiles = async (rootDir: string): Promise<void> =>
⋮----
/**
 * Get all migration related file paths
 */
const getMigrationPaths = (rootDir: string): MigrationPaths =>
⋮----
/**
 * Migrate output files
 */
const migrateOutputFiles = async (oldPaths: string[], newPaths: string[]): Promise<string[]> =>
⋮----
export const runMigrationAction = async (rootDir: string): Promise<MigrationResult> =>
⋮----
// Check if migration is needed
⋮----
// Show migration notice based on what needs to be migrated
⋮----
// Confirm migration with user
⋮----
// Show migration notice
⋮----
// Migrate config file
⋮----
// Migrate global config file
⋮----
// Migrate ignore file
⋮----
// Migrate instruction file
⋮----
// Migrate output files
⋮----
// Update content in gitignore and repomixignore
⋮----
// Show success message
</file>

<file path="src/cli/actions/remoteAction.ts">
import os from 'node:os';
import path from 'node:path';
import pc from 'picocolors';
import { execGitShallowClone } from '../../core/git/gitCommand.js';
import { downloadGitHubArchive, isArchiveDownloadSupported } from '../../core/git/gitHubArchive.js';
import { getRemoteRefs } from '../../core/git/gitRemoteHandle.js';
import { isGitHubRepository, parseGitHubRepoInfo, parseRemoteValue } from '../../core/git/gitRemoteParse.js';
import { isGitInstalled } from '../../core/git/gitRepositoryHandle.js';
import { RepomixError } from '../../shared/errorHandle.js';
import { logger } from '../../shared/logger.js';
import { Spinner } from '../cliSpinner.js';
import type { CliOptions } from '../types.js';
import { type DefaultActionRunnerResult, runDefaultAction } from './defaultAction.js';
⋮----
export const runRemoteAction = async (
  repoUrl: string,
  cliOptions: CliOptions,
  deps = {
    isGitInstalled,
    execGitShallowClone,
    getRemoteRefs,
    runDefaultAction,
    downloadGitHubArchive,
    isGitHubRepository,
    parseGitHubRepoInfo,
    isArchiveDownloadSupported,
  },
): Promise<DefaultActionRunnerResult> =>
⋮----
// Check if this is a GitHub repository and archive download is supported
⋮----
// Try GitHub archive download first
⋮----
// Override ref with CLI option if provided
⋮----
timeout: 60000, // 1 minute timeout for large repos
⋮----
// Show downloaded bytes when percentage is not available
⋮----
// Clear the temp directory for git clone attempt
⋮----
// Fall back to git clone
⋮----
// Use git clone directly
⋮----
// Run the default action on the downloaded/cloned repository
⋮----
// Copy output file only when not in stdout mode
// In stdout mode, output is written directly to stdout without creating a file,
// so attempting to copy a non-existent file would cause an error and exit code 1
⋮----
// Cleanup the temporary directory
⋮----
/**
 * Performs git clone operation with spinner and error handling
 */
const performGitClone = async (
  repoUrl: string,
  tempDirPath: string,
  cliOptions: CliOptions,
  deps: {
    isGitInstalled: typeof isGitInstalled;
    getRemoteRefs: typeof getRemoteRefs;
    execGitShallowClone: typeof execGitShallowClone;
  },
): Promise<void> =>
⋮----
// Check if git is installed only when we actually need to use git
⋮----
// Get remote refs
⋮----
// Parse the remote URL with the refs information
⋮----
// Clone the repository
⋮----
export const createTempDirectory = async (): Promise<string> =>
⋮----
export const cloneRepository = async (
  url: string,
  directory: string,
  remoteBranch?: string,
  deps = {
    execGitShallowClone,
  },
): Promise<void> =>
⋮----
export const cleanupTempDirectory = async (directory: string): Promise<void> =>
⋮----
export const copyOutputToCurrentDirectory = async (
  sourceDir: string,
  targetDir: string,
  outputFileName: string,
): Promise<void> =>
⋮----
// Create target directory if it doesn't exist
</file>

<file path="src/cli/actions/versionAction.ts">
import { getVersion } from '../../core/file/packageJsonParse.js';
import { logger } from '../../shared/logger.js';
⋮----
export const runVersionAction = async (): Promise<void> =>
</file>

<file path="src/cli/cliPrint.ts">
import path from 'node:path';
import pc from 'picocolors';
import type { RepomixConfigMerged } from '../config/configSchema.js';
import type { PackResult } from '../core/packager.js';
import type { SuspiciousFileResult } from '../core/security/securityCheck.js';
import { logger } from '../shared/logger.js';
⋮----
export const printSummary = (packResult: PackResult, config: RepomixConfigMerged) =>
⋮----
export const printSecurityCheck = (
  rootDir: string,
  suspiciousFilesResults: SuspiciousFileResult[],
  suspiciousGitDiffResults: SuspiciousFileResult[],
  config: RepomixConfigMerged,
) =>
⋮----
// Print results for files
⋮----
// Print results for git diffs
⋮----
export const printTopFiles = (
  fileCharCounts: Record<string, number>,
  fileTokenCounts: Record<string, number>,
  topFilesLength: number,
  totalTokens: number,
) =>
⋮----
// Filter files that have token counts (top candidates by char count)
⋮----
// Use the actual total tokens from the entire output
⋮----
export const printCompletion = () =>
</file>

<file path="src/cli/cliRun.ts">
import process from 'node:process';
import { Command, Option, program } from 'commander';
import pc from 'picocolors';
import { getVersion } from '../core/file/packageJsonParse.js';
import { handleError } from '../shared/errorHandle.js';
import { logger, repomixLogLevels } from '../shared/logger.js';
import { runDefaultAction } from './actions/defaultAction.js';
import { runInitAction } from './actions/initAction.js';
import { runMcpAction } from './actions/mcpAction.js';
import { runRemoteAction } from './actions/remoteAction.js';
import { runVersionAction } from './actions/versionAction.js';
import type { CliOptions } from './types.js';
⋮----
// Semantic mapping for CLI suggestions
// This maps conceptually related terms (not typos) to valid options
⋮----
export const run = async () =>
⋮----
// Basic Options
⋮----
// Output Options
⋮----
// Filter Options
⋮----
// Remote Repository Options
⋮----
// Configuration Options
⋮----
// Security Options
⋮----
// Token Count Options
⋮----
// MCP
⋮----
// Other Options
⋮----
// Custom error handling function
⋮----
// Check if this is an unknown option error
⋮----
// Check if the option has a semantic match
⋮----
// We have a direct semantic match
⋮----
// Fall back to the original Commander error handler
⋮----
const commanderActionEndpoint = async (directories: string[], options: CliOptions =
⋮----
export const runCli = async (directories: string[], cwd: string, options: CliOptions) =>
⋮----
// Detect stdout mode
// NOTE: For compatibility, currently not detecting pipe mode
⋮----
// Set log level based on verbose and quiet flags
⋮----
// In stdout mode, set log level to SILENT
⋮----
// Skip version header in stdin mode to avoid interfering with piped output from interactive tools like fzf
</file>

<file path="src/cli/cliSpinner.ts">
import cliSpinners from 'cli-spinners';
import logUpdate from 'log-update';
import pc from 'picocolors';
import type { CliOptions } from './types.js';
⋮----
export class Spinner
⋮----
constructor(message: string, cliOptions: CliOptions)
⋮----
// If the user has specified the verbose flag, don't show the spinner
⋮----
start(): void
⋮----
update(message: string): void
⋮----
stop(finalMessage: string): void
⋮----
succeed(message: string): void
⋮----
fail(message: string): void
</file>

<file path="src/cli/types.ts">
import type { OptionValues } from 'commander';
import type { RepomixOutputStyle } from '../config/configSchema.js';
⋮----
export interface CliOptions extends OptionValues {
  // Basic Options
  version?: boolean;

  // Output Options
  output?: string;
  stdout?: boolean;
  style?: RepomixOutputStyle;
  parsableStyle?: boolean;
  compress?: boolean;
  outputShowLineNumbers?: boolean;
  copy?: boolean;
  fileSummary?: boolean;
  directoryStructure?: boolean;
  files?: boolean;
  removeComments?: boolean;
  removeEmptyLines?: boolean;
  headerText?: string;
  instructionFilePath?: string;
  includeEmptyDirectories?: boolean;
  gitSortByChanges?: boolean;
  includeDiffs?: boolean;

  // Filter Options
  include?: string;
  ignore?: string;
  gitignore?: boolean;
  defaultPatterns?: boolean;
  stdin?: boolean;

  // Remote Repository Options
  remote?: string;
  remoteBranch?: string;

  // Configuration Options
  config?: string;
  init?: boolean;
  global?: boolean;

  // Security Options
  securityCheck?: boolean;

  // Token Count Options
  tokenCountEncoding?: string;

  // MCP
  mcp?: boolean;

  // Other Options
  topFilesLen?: number;
  verbose?: boolean;
  quiet?: boolean;
}
⋮----
// Basic Options
⋮----
// Output Options
⋮----
// Filter Options
⋮----
// Remote Repository Options
⋮----
// Configuration Options
⋮----
// Security Options
⋮----
// Token Count Options
⋮----
// MCP
⋮----
// Other Options
</file>

<file path="src/config/configLoad.ts">
import path from 'node:path';
import JSON5 from 'json5';
import pc from 'picocolors';
import { RepomixError, rethrowValidationErrorIfZodError } from '../shared/errorHandle.js';
import { logger } from '../shared/logger.js';
import {
  type RepomixConfigCli,
  type RepomixConfigFile,
  type RepomixConfigMerged,
  defaultConfig,
  defaultFilePathMap,
  repomixConfigFileSchema,
  repomixConfigMergedSchema,
} from './configSchema.js';
import { getGlobalDirectory } from './globalDirectory.js';
⋮----
const getGlobalConfigPaths = () =>
⋮----
const checkFileExists = async (filePath: string): Promise<boolean> =>
⋮----
const findConfigFile = async (configPaths: string[], logPrefix: string): Promise<string | null> =>
⋮----
export const loadFileConfig = async (rootDir: string, argConfigPath: string | null): Promise<RepomixConfigFile> =>
⋮----
// If a specific config path is provided, use it directly
⋮----
// Try to find a local config file using the priority order
⋮----
// Try to find a global config file using the priority order
⋮----
const loadAndValidateConfig = async (filePath: string): Promise<RepomixConfigFile> =>
⋮----
export const mergeConfigs = (
  cwd: string,
  fileConfig: RepomixConfigFile,
  cliConfig: RepomixConfigCli,
): RepomixConfigMerged =>
⋮----
// If the output file path is not provided in the config file or CLI, use the default file path for the style
</file>

<file path="src/config/configSchema.ts">
import type { TiktokenEncoding } from 'tiktoken';
import { z } from 'zod';
⋮----
// Output style enum
⋮----
export type RepomixOutputStyle = z.infer<typeof repomixOutputStyleSchema>;
⋮----
// Default values map
⋮----
// Base config schema
⋮----
// Default config schema with default values
⋮----
.default(50 * 1024 * 1024), // Default: 50MB
⋮----
// File-specific schema. Add options for file path and style
⋮----
// CLI-specific schema. Add options for standard output mode
⋮----
// Merged schema for all configurations
⋮----
export type RepomixConfigDefault = z.infer<typeof repomixConfigDefaultSchema>;
export type RepomixConfigFile = z.infer<typeof repomixConfigFileSchema>;
export type RepomixConfigCli = z.infer<typeof repomixConfigCliSchema>;
export type RepomixConfigMerged = z.infer<typeof repomixConfigMergedSchema>;
</file>

<file path="src/config/defaultIgnore.ts">
// Version control
⋮----
// Dependency directories
⋮----
// Logs
⋮----
// Runtime data
⋮----
// Directory for instrumented libs generated by jscoverage/JSCover
⋮----
// Coverage directory used by tools like istanbul
⋮----
// nyc test coverage
⋮----
// Grunt intermediate storage
⋮----
// node-waf configuration
⋮----
// Compiled binary addons
⋮----
// TypeScript v1 declaration files
⋮----
// Optional npm cache directory
⋮----
// Cache directories
⋮----
// Optional REPL history
⋮----
// Output of 'npm pack'
⋮----
// Yarn files
⋮----
// Yarn Integrity file
⋮----
// dotenv environment variables file
⋮----
// next.js build output
⋮----
// nuxt.js build output
⋮----
// vuepress build output
⋮----
// Serverless directories
⋮----
// FuseBox cache
⋮----
// DynamoDB Local files
⋮----
// TypeScript output
⋮----
// OS generated files
⋮----
// Editor directories and files
⋮----
// Build outputs
⋮----
// Temporary files
⋮----
// repomix output
⋮----
'**/repopack-output.*', // Legacy
⋮----
// Essential Node.js-related entries
⋮----
// Essential Python-related entries
⋮----
// Essential Rust-related entries
⋮----
// Essential PHP-related entries
⋮----
// Essential Ruby-related entries
⋮----
// Essential Go-related entries
⋮----
// Essential Elixir-related entries
⋮----
// Essential Haskell-related entries
</file>

<file path="src/config/globalDirectory.ts">
import os from 'node:os';
import path from 'node:path';
⋮----
export const getGlobalDirectory = () =>
</file>

<file path="src/core/file/workers/fileCollectWorker.ts">
import path from 'node:path';
import { logger, setLogLevelByEnv } from '../../../shared/logger.js';
import { readRawFile } from '../fileRead.js';
⋮----
export interface FileCollectTask {
  filePath: string;
  rootDir: string;
  maxFileSize: number;
}
⋮----
// Set logger log level from environment variable if provided
</file>

<file path="src/core/file/workers/fileProcessWorker.ts">
import type { RepomixConfigMerged } from '../../../config/configSchema.js';
import { logger, setLogLevelByEnv } from '../../../shared/logger.js';
import { processContent } from '../fileProcessContent.js';
import type { ProcessedFile, RawFile } from '../fileTypes.js';
⋮----
export interface FileProcessTask {
  rawFile: RawFile;
  config: RepomixConfigMerged;
}
⋮----
// Set logger log level from environment variable if provided
</file>

<file path="src/core/file/fileCollect.ts">
import pc from 'picocolors';
import type { RepomixConfigMerged } from '../../config/configSchema.js';
import { logger } from '../../shared/logger.js';
import { initPiscina } from '../../shared/processConcurrency.js';
import type { RepomixProgressCallback } from '../../shared/types.js';
import type { RawFile } from './fileTypes.js';
import type { FileCollectTask } from './workers/fileCollectWorker.js';
⋮----
const initTaskRunner = (numOfTasks: number) =>
⋮----
export const collectFiles = async (
  filePaths: string[],
  rootDir: string,
  config: RepomixConfigMerged,
  progressCallback: RepomixProgressCallback = () => {},
  deps = {
    initTaskRunner,
  },
): Promise<RawFile[]> =>
</file>

<file path="src/core/file/fileManipulate.ts">
import path from 'node:path';
import strip from 'strip-comments';
⋮----
export interface FileManipulator {
  removeComments(content: string): string;
  removeEmptyLines(content: string): string;
}
⋮----
removeComments(content: string): string;
removeEmptyLines(content: string): string;
⋮----
const rtrimLines = (content: string): string
⋮----
class BaseManipulator implements FileManipulator
⋮----
removeComments(content: string): string
⋮----
removeEmptyLines(content: string): string
⋮----
class StripCommentsManipulator extends BaseManipulator
⋮----
constructor(language: string)
⋮----
class CppManipulator extends BaseManipulator
⋮----
class PythonManipulator extends BaseManipulator
⋮----
removeDocStrings(content: string): string
⋮----
removeHashComments(content: string): string
⋮----
const searchInPairs = (pairs: [number, number][], hashIndex: number): boolean =>
⋮----
class CompositeManipulator extends BaseManipulator
⋮----
constructor(...manipulators: FileManipulator[])
⋮----
export const getFileManipulator = (filePath: string): FileManipulator | null =>
</file>

<file path="src/core/file/filePathSort.ts">
import path from 'node:path';
⋮----
// Sort paths for general use (not affected by git change count)
export const sortPaths = (filePaths: string[]): string[] =>
⋮----
if (!isLastA && isLastB) return -1; // Directory
if (isLastA && !isLastB) return 1; // File
⋮----
return partsA[i].localeCompare(partsB[i]); // Alphabetical order
⋮----
// Sort by path length when all parts are equal
</file>

<file path="src/core/file/fileProcess.ts">
import pc from 'picocolors';
import type { RepomixConfigMerged } from '../../config/configSchema.js';
import { logger } from '../../shared/logger.js';
import { initPiscina } from '../../shared/processConcurrency.js';
import type { RepomixProgressCallback } from '../../shared/types.js';
import { type FileManipulator, getFileManipulator } from './fileManipulate.js';
import type { ProcessedFile, RawFile } from './fileTypes.js';
import type { FileProcessTask } from './workers/fileProcessWorker.js';
⋮----
type GetFileManipulator = (filePath: string) => FileManipulator | null;
⋮----
const initTaskRunner = (numOfTasks: number) =>
⋮----
export const processFiles = async (
  rawFiles: RawFile[],
  config: RepomixConfigMerged,
  progressCallback: RepomixProgressCallback,
  deps: {
    initTaskRunner: typeof initTaskRunner;
    getFileManipulator: GetFileManipulator;
  } = {
    initTaskRunner,
    getFileManipulator,
  },
): Promise<ProcessedFile[]> =>
</file>

<file path="src/core/file/fileProcessContent.ts">
import type { RepomixConfigMerged } from '../../config/configSchema.js';
import { logger } from '../../shared/logger.js';
import { parseFile } from '../treeSitter/parseFile.js';
import { getFileManipulator } from './fileManipulate.js';
import type { RawFile } from './fileTypes.js';
⋮----
/**
 * Process the content of a file according to the configuration
 * Applies various transformations based on the config:
 * - Remove comments
 * - Remove empty lines
 * - Compress content using Tree-sitter
 * - Add line numbers
 *
 * @param rawFile Raw file data containing path and content
 * @param config Repomix configuration
 * @returns Processed content string
 */
export const processContent = async (rawFile: RawFile, config: RepomixConfigMerged): Promise<string> =>
⋮----
//re-throw error
</file>

<file path="src/core/file/fileRead.ts">
import iconv from 'iconv-lite';
import { isBinary } from 'istextorbinary';
import jschardet from 'jschardet';
import { logger } from '../../shared/logger.js';
⋮----
/**
 * Read a file and return its text content
 * @param filePath Path to the file
 * @param maxFileSize Maximum file size in bytes
 * @returns File content as string, or null if the file is binary or exceeds size limit
 */
export const readRawFile = async (filePath: string, maxFileSize: number): Promise<string | null> =>
</file>

<file path="src/core/file/fileSearch.ts">
import type { Stats } from 'node:fs';
import fs from 'node:fs/promises';
import path from 'node:path';
import { globby } from 'globby';
import { minimatch } from 'minimatch';
import type { RepomixConfigMerged } from '../../config/configSchema.js';
import { defaultIgnoreList } from '../../config/defaultIgnore.js';
import { RepomixError } from '../../shared/errorHandle.js';
import { logger } from '../../shared/logger.js';
import { sortPaths } from './filePathSort.js';
import { PermissionError, checkDirectoryPermissions } from './permissionCheck.js';
⋮----
export interface FileSearchResult {
  filePaths: string[];
  emptyDirPaths: string[];
}
⋮----
const findEmptyDirectories = async (
  rootDir: string,
  directories: string[],
  ignorePatterns: string[],
): Promise<string[]> =>
⋮----
// This checks if the directory itself matches any ignore patterns
⋮----
// Check if a path is a git worktree reference file
const isGitWorktreeRef = async (gitPath: string): Promise<boolean> =>
⋮----
/**
 * Escapes special characters in glob patterns to handle paths with parentheses.
 * Example: "src/(categories)" -> "src/\\(categories\\)"
 */
export const escapeGlobPattern = (pattern: string): string =>
⋮----
// First escape backslashes
⋮----
// Then escape special characters () and [], but NOT {}
⋮----
/**
 * Normalizes glob patterns by removing trailing slashes and ensuring consistent directory pattern handling.
 * Makes "**\/folder", "**\/folder/", and "**\/folder/**\/*" behave identically.
 *
 * @param pattern The glob pattern to normalize
 * @returns The normalized pattern
 */
export const normalizeGlobPattern = (pattern: string): string =>
⋮----
// Remove trailing slash but preserve patterns that end with "**/"
⋮----
// Convert **/folder to **/folder/** for consistent ignore pattern behavior
⋮----
// Get all file paths considering the config
export const searchFiles = async (
  rootDir: string,
  config: RepomixConfigMerged,
  explicitFiles?: string[],
): Promise<FileSearchResult> =>
⋮----
// Check if the path exists and get its type
⋮----
// Handle other specific error codes with more context
⋮----
// Preserve original error stack trace for debugging
⋮----
// Check if the path is a directory
⋮----
// Now check directory permissions
⋮----
// Normalize ignore patterns to handle trailing slashes consistently
⋮----
// Check if .git is a worktree reference
⋮----
// Modify ignore patterns for git worktree
⋮----
// Remove '.git/**' pattern and add '.git' to ignore the reference file
⋮----
// Start with configured include patterns
⋮----
// If explicit files are provided, add them to include patterns
⋮----
// Escape the path to handle special characters
⋮----
// If no include patterns at all, default to all files
⋮----
// Handle EPERM errors specifically
⋮----
// Re-throw PermissionError as is
⋮----
export const parseIgnoreContent = (content: string): string[] =>
⋮----
export const getIgnoreFilePatterns = async (config: RepomixConfigMerged): Promise<string[]> =>
⋮----
export const getIgnorePatterns = async (rootDir: string, config: RepomixConfigMerged): Promise<string[]> =>
⋮----
// Add default ignore patterns
⋮----
// Add repomix output file
⋮----
// Add custom ignore patterns
⋮----
// Add patterns from .git/info/exclude if useGitignore is enabled
⋮----
// File might not exist or might not be accessible, which is fine
</file>

<file path="src/core/file/fileStdin.ts">
import path from 'node:path';
import readline from 'node:readline/promises';
import type { Readable } from 'node:stream';
import { RepomixError } from '../../shared/errorHandle.js';
import { logger } from '../../shared/logger.js';
⋮----
export interface StdinFileResult {
  filePaths: string[];
  emptyDirPaths: string[];
}
⋮----
export interface StdinDependencies {
  stdin: NodeJS.ReadableStream & { isTTY?: boolean };
  createReadlineInterface: (options: { input: Readable }) => readline.Interface;
}
⋮----
/**
 * Filters and validates lines from stdin input.
 * Removes empty lines and comments (lines starting with #).
 */
export const filterValidLines = (lines: string[]): string[] =>
⋮----
/**
 * Resolves relative paths to absolute paths and deduplicates them.
 */
export const resolveAndDeduplicatePaths = (lines: string[], cwd: string): string[] =>
⋮----
/**
 * Reads lines from a readable stream using readline interface.
 * Waits for EOF before returning all collected lines.
 * Handles interactive tools like fzf that may take time to provide output.
 */
export const readLinesFromStream = async (
  input: Readable,
  createInterface: (options: { input: Readable }) => readline.Interface = readline.createInterface,
): Promise<string[]> =>
⋮----
// The for-await loop naturally waits for EOF before completing
⋮----
// Safely close the readline interface if it has a close method
⋮----
/**
 * Reads file paths from stdin, one per line.
 * Filters out empty lines and comments (lines starting with #).
 * Converts relative paths to absolute paths based on the current working directory.
 */
export const readFilePathsFromStdin = async (
  cwd: string,
  deps: StdinDependencies = {
    stdin: process.stdin,
    createReadlineInterface: readline.createInterface,
  },
): Promise<StdinFileResult> =>
⋮----
// Check if stdin is a TTY (interactive mode)
⋮----
// Read all lines from stdin (wait for EOF)
⋮----
// Filter out empty lines and comments
⋮----
// Convert relative paths to absolute paths and deduplicate
⋮----
emptyDirPaths: [], // Empty directories not supported with stdin input
</file>

<file path="src/core/file/fileTreeGenerate.ts">
import nodepath from 'node:path';
⋮----
export interface TreeNode {
  name: string;
  children: TreeNode[];
  isDirectory: boolean;
}
⋮----
const createTreeNode = (name: string, isDirectory: boolean): TreeNode => (
⋮----
export const generateFileTree = (files: string[], emptyDirPaths: string[] = []): TreeNode =>
⋮----
// Add empty directories
⋮----
const addPathToTree = (root: TreeNode, path: string, isDirectory: boolean): void =>
⋮----
const sortTreeNodes = (node: TreeNode) =>
⋮----
export const treeToString = (node: TreeNode, prefix = ''): string =>
⋮----
export const generateTreeString = (files: string[], emptyDirPaths: string[] = []): string =>
</file>

<file path="src/core/file/fileTypes.ts">
export interface RawFile {
  path: string;
  content: string;
}
⋮----
export interface ProcessedFile {
  path: string;
  content: string;
}
</file>

<file path="src/core/file/packageJsonParse.ts">
import path from 'node:path';
⋮----
import { logger } from '../../shared/logger.js';
⋮----
export const getVersion = async (): Promise<string> =>
⋮----
const parsePackageJson = async (): Promise<
</file>

<file path="src/core/file/permissionCheck.ts">
import { constants } from 'node:fs';
⋮----
import { platform } from 'node:os';
import { logger } from '../../shared/logger.js';
⋮----
export interface PermissionCheckResult {
  hasAllPermission: boolean;
  error?: Error;
  details?: {
    read?: boolean;
    write?: boolean;
    execute?: boolean;
  };
}
⋮----
export class PermissionError extends Error
⋮----
constructor(
    message: string,
    public readonly path: string,
    public readonly code?: string,
)
⋮----
export const checkDirectoryPermissions = async (dirPath: string): Promise<PermissionCheckResult> =>
⋮----
// First try to read directory contents
⋮----
// Check specific permissions
⋮----
const getMacOSPermissionMessage = (dirPath: string, errorCode?: string): string =>
</file>

<file path="src/core/git/gitCommand.ts">
import { execFile } from 'node:child_process';
import fs from 'node:fs/promises';
import path from 'node:path';
import { promisify } from 'node:util';
import { RepomixError } from '../../shared/errorHandle.js';
import { logger } from '../../shared/logger.js';
⋮----
export const execGitLogFilenames = async (
  directory: string,
  maxCommits = 100,
  deps = {
    execFileAsync,
  },
): Promise<string[]> =>
⋮----
export const execGitDiff = async (
  directory: string,
  options: string[] = [],
  deps = {
    execFileAsync,
  },
): Promise<string> =>
⋮----
'--no-color', // Avoid ANSI color codes
⋮----
export const execGitVersion = async (
  deps = {
    execFileAsync,
  },
): Promise<string> =>
⋮----
export const execGitRevParse = async (
  directory: string,
  deps = {
    execFileAsync,
  },
): Promise<string> =>
⋮----
export const execLsRemote = async (
  url: string,
  deps = {
    execFileAsync,
  },
): Promise<string> =>
⋮----
export const execGitShallowClone = async (
  url: string,
  directory: string,
  remoteBranch?: string,
  deps = {
    execFileAsync,
  },
) =>
⋮----
// git fetch --depth 1 origin <short SHA> always throws "couldn't find remote ref" error
⋮----
// Rethrow error as nothing else we can do
⋮----
// Short SHA detection - matches a hexadecimal string of 4 to 39 characters
// If the string matches this regex, it MIGHT be a short SHA
// If the string doesn't match, it is DEFINITELY NOT a short SHA
⋮----
// Rethrow error as nothing else we can do
⋮----
// Maybe the error is due to a short SHA, let's try again
// Can't use --depth 1 here as we need to fetch the specific commit
⋮----
// Clean up .git directory
⋮----
/**
 * Validates a Git URL for security and format
 * @throws {RepomixError} If the URL is invalid or contains potentially dangerous parameters
 */
export const validateGitUrl = (url: string): void =>
⋮----
// Check if the URL starts with git@ or https://
</file>

<file path="src/core/git/gitDiffHandle.ts">
import type { RepomixConfigMerged } from '../../config/configSchema.js';
import { RepomixError } from '../../shared/errorHandle.js';
import { logger } from '../../shared/logger.js';
import { execGitDiff } from './gitCommand.js';
import { isGitRepository } from './gitRepositoryHandle.js';
⋮----
export interface GitDiffResult {
  workTreeDiffContent: string;
  stagedDiffContent: string;
}
⋮----
export const getWorkTreeDiff = async (
  directory: string,
  deps = {
    execGitDiff,
    isGitRepository,
  },
): Promise<string> =>
⋮----
export const getStagedDiff = async (
  directory: string,
  deps = {
    execGitDiff,
    isGitRepository,
  },
): Promise<string> =>
⋮----
/**
 * Helper function to get git diff with common repository check and error handling
 */
const getDiff = async (
  directory: string,
  options: string[],
  deps = {
    execGitDiff,
    isGitRepository,
  },
): Promise<string> =>
⋮----
// Check if the directory is a git repository
⋮----
// Get the diff with provided options
⋮----
export const getGitDiffs = async (
  rootDirs: string[],
  config: RepomixConfigMerged,
  deps = {
    getWorkTreeDiff,
    getStagedDiff,
  },
): Promise<GitDiffResult | undefined> =>
⋮----
// Get git diffs if enabled
⋮----
// Use the first directory as the git repository root
// Usually this would be the root of the project
</file>

<file path="src/core/git/gitHubArchive.ts">
import { createWriteStream } from 'node:fs';
⋮----
import { Readable, Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { unzip } from 'fflate';
import { RepomixError } from '../../shared/errorHandle.js';
import { logger } from '../../shared/logger.js';
import {
  buildGitHubArchiveUrl,
  buildGitHubMasterArchiveUrl,
  buildGitHubTagArchiveUrl,
  checkGitHubResponse,
  getArchiveFilename,
} from './gitHubArchiveApi.js';
import type { GitHubRepoInfo } from './gitRemoteParse.js';
⋮----
export interface ArchiveDownloadOptions {
  timeout?: number; // Download timeout in milliseconds (default: 30000)
  retries?: number; // Number of retry attempts (default: 3)
}
⋮----
timeout?: number; // Download timeout in milliseconds (default: 30000)
retries?: number; // Number of retry attempts (default: 3)
⋮----
export interface ArchiveDownloadProgress {
  downloaded: number;
  total: number | null;
  percentage: number | null;
}
⋮----
export type ProgressCallback = (progress: ArchiveDownloadProgress) => void;
⋮----
/**
 * Downloads and extracts a GitHub repository archive
 */
export const downloadGitHubArchive = async (
  repoInfo: GitHubRepoInfo,
  targetDirectory: string,
  options: ArchiveDownloadOptions = {},
  onProgress?: ProgressCallback,
  deps = {
    fetch: globalThis.fetch,
    fs,
    pipeline,
    Transform,
    createWriteStream,
  },
): Promise<void> =>
⋮----
// Ensure target directory exists
⋮----
// Try downloading with multiple URL formats: main branch, master branch (fallback), then tag format
⋮----
return; // Success - exit early
⋮----
// If it's a 404-like error and we have more URLs to try, don't retry this URL
⋮----
// If it's the last attempt, don't wait
⋮----
const delay = Math.min(1000 * 2 ** (attempt - 1), 5000); // Exponential backoff, max 5s
⋮----
// If we get here, all attempts failed
⋮----
/**
 * Downloads and extracts archive from a single URL
 */
const downloadAndExtractArchive = async (
  archiveUrl: string,
  targetDirectory: string,
  repoInfo: GitHubRepoInfo,
  timeout: number,
  onProgress?: ProgressCallback,
  deps = {
    fetch: globalThis.fetch,
    fs,
    pipeline,
    Transform,
    createWriteStream,
  },
): Promise<void> =>
⋮----
// Download the archive
⋮----
// Extract the archive
⋮----
// Clean up the downloaded archive file
⋮----
/**
 * Downloads a file from URL with progress tracking
 */
const downloadFile = async (
  url: string,
  filePath: string,
  timeout: number,
  onProgress?: ProgressCallback,
  deps = {
    fetch: globalThis.fetch,
    fs,
    pipeline,
    Transform,
    createWriteStream,
  },
): Promise<void> =>
⋮----
// Use Readable.fromWeb for better stream handling
⋮----
// Transform stream for progress tracking
⋮----
transform(chunk, _encoding, callback)
⋮----
// Update progress at most every 100ms to avoid too frequent updates
⋮----
flush(callback)
⋮----
// Send final progress update
⋮----
// Write to file
⋮----
/**
 * Extracts a ZIP archive using fflate library
 */
const extractZipArchive = async (
  archivePath: string,
  targetDirectory: string,
  repoInfo: GitHubRepoInfo,
  deps = {
    fs,
  },
): Promise<void> =>
⋮----
// Always use in-memory extraction for simplicity and reliability
⋮----
/**
 * Extracts ZIP archive by loading it entirely into memory (faster for small files)
 */
const extractZipArchiveInMemory = async (
  archivePath: string,
  targetDirectory: string,
  repoInfo: GitHubRepoInfo,
  deps = {
    fs,
  },
): Promise<void> =>
⋮----
// Read the ZIP file as a buffer
⋮----
// Extract ZIP using fflate
⋮----
// Process extracted files concurrently in the callback
⋮----
/**
 * Process extracted files sequentially to avoid EMFILE errors
 */
const processExtractedFiles = async (
  extracted: Record<string, Uint8Array>,
  targetDirectory: string,
  repoInfo: GitHubRepoInfo,
  deps = {
    fs,
  },
): Promise<void> =>
⋮----
// Process files sequentially to avoid EMFILE errors completely
⋮----
// GitHub archives have a top-level directory like "repo-branch/"
// We need to remove this prefix from the file paths
⋮----
// Find and remove the repo prefix
⋮----
// Remove the first directory (repo-branch/)
⋮----
// Skip empty paths (root directory)
⋮----
// Sanitize relativePath to prevent path traversal attacks
⋮----
// Reject absolute paths outright
⋮----
// Check if this entry is a directory (ends with /) or empty file data indicates directory
⋮----
// Create directory immediately
⋮----
// Create parent directory if needed and write file
⋮----
// Write file sequentially
⋮----
/**
 * Checks if archive download is supported for the given repository info
 */
export const isArchiveDownloadSupported = (_repoInfo: GitHubRepoInfo): boolean =>
⋮----
// Archive download is supported for all GitHub repositories
// In the future, we might add conditions here (e.g., size limits, private repos)
</file>

<file path="src/core/git/gitHubArchiveApi.ts">
import { RepomixError } from '../../shared/errorHandle.js';
import type { GitHubRepoInfo } from './gitRemoteParse.js';
⋮----
/**
 * Constructs GitHub archive download URL
 * Format: https://github.com/owner/repo/archive/refs/heads/branch.zip
 * For tags: https://github.com/owner/repo/archive/refs/tags/tag.zip
 * For commits: https://github.com/owner/repo/archive/commit.zip
 */
export const buildGitHubArchiveUrl = (repoInfo: GitHubRepoInfo): string =>
⋮----
// Default to main branch - fallback to master will be handled by the caller
⋮----
// Check if ref looks like a commit SHA (40 hex chars or shorter)
⋮----
// For branches and tags, we need to determine the type
// Default to branch format, will fallback to tag if needed
⋮----
/**
 * Builds alternative archive URL for master branch as fallback
 */
export const buildGitHubMasterArchiveUrl = (repoInfo: GitHubRepoInfo): string | null =>
⋮----
return null; // Only applicable when no ref is specified
⋮----
/**
 * Builds alternative archive URL for tags
 */
export const buildGitHubTagArchiveUrl = (repoInfo: GitHubRepoInfo): string | null =>
⋮----
return null; // Not applicable for commits or no ref
⋮----
/**
 * Gets the expected archive filename from GitHub
 * Format: repo-branch.zip or repo-sha.zip
 */
export const getArchiveFilename = (repoInfo: GitHubRepoInfo): string =>
⋮----
// GitHub uses the last part of the ref for the filename
⋮----
/**
 * Checks if a response indicates a GitHub API rate limit or error
 */
export const checkGitHubResponse = (response: Response): void =>
</file>

<file path="src/core/git/gitRemoteHandle.ts">
import { RepomixError } from '../../shared/errorHandle.js';
import { logger } from '../../shared/logger.js';
import { execLsRemote, validateGitUrl } from './gitCommand.js';
⋮----
export const getRemoteRefs = async (
  url: string,
  deps = {
    execLsRemote,
  },
): Promise<string[]> =>
⋮----
// Extract ref names from the output
// Format is: hash\tref_name
⋮----
// Skip the hash part and extract only the ref name
⋮----
// Remove 'refs/heads/' or 'refs/tags/' prefix
</file>

<file path="src/core/git/gitRemoteParse.ts">
import gitUrlParse, { type GitUrl } from 'git-url-parse';
import { RepomixError } from '../../shared/errorHandle.js';
import { logger } from '../../shared/logger.js';
⋮----
interface IGitUrl extends GitUrl {
  commit: string | undefined;
}
⋮----
export interface GitHubRepoInfo {
  owner: string;
  repo: string;
  ref?: string; // branch, tag, or commit SHA
}
⋮----
ref?: string; // branch, tag, or commit SHA
⋮----
// Check the short form of the GitHub URL. e.g. yamadashy/repomix
⋮----
export const isValidShorthand = (remoteValue: string): boolean =>
⋮----
export const parseRemoteValue = (
  remoteValue: string,
  refs: string[] = [],
):
⋮----
// This will make parsedFields.toString() automatically append '.git' to the returned url
⋮----
export const isValidRemoteValue = (remoteValue: string, refs: string[] = []): boolean =>
⋮----
/**
 * Parses remote value and extracts GitHub repository information if it's a GitHub repo
 * Returns null if the remote value is not a GitHub repository
 */
export const parseGitHubRepoInfo = (remoteValue: string): GitHubRepoInfo | null =>
⋮----
// Handle shorthand format: owner/repo
⋮----
// For GitHub URLs with branch/tag/commit info, extract directly from URL
⋮----
// Extract ref from URL patterns like /tree/branch or /commit/sha
⋮----
// Fall back to git-url-parse if URL parsing fails
⋮----
// Parse using git-url-parse for other cases
⋮----
// Only proceed if it's a GitHub repository
⋮----
// Extract owner and repo from full_name (e.g., "owner/repo")
⋮----
repo: repo.replace(/\.git$/, ''), // Remove .git suffix
⋮----
// Add ref if available
⋮----
/**
 * Checks if a remote value represents a GitHub repository
 */
export const isGitHubRepository = (remoteValue: string): boolean =>
</file>

<file path="src/core/git/gitRepositoryHandle.ts">
import { logger } from '../../shared/logger.js';
import { execGitLogFilenames, execGitRevParse, execGitVersion } from './gitCommand.js';
⋮----
export const getFileChangeCount = async (
  directory: string,
  maxCommits = 100,
  deps = {
    execGitLogFilenames,
  },
): Promise<Record<string, number>> =>
⋮----
export const isGitRepository = async (
  directory: string,
  deps = {
    execGitRevParse,
  },
): Promise<boolean> =>
⋮----
export const isGitInstalled = async (
  deps = {
    execGitVersion,
  },
): Promise<boolean> =>
</file>

<file path="src/core/metrics/workers/fileMetricsWorker.ts">
import type { TiktokenEncoding } from 'tiktoken';
import { logger, setLogLevelByEnv } from '../../../shared/logger.js';
import type { ProcessedFile } from '../../file/fileTypes.js';
import { TokenCounter } from '../TokenCounter.js';
import type { FileMetrics } from './types.js';
⋮----
export interface FileMetricsTask {
  file: ProcessedFile;
  index: number;
  totalFiles: number;
  encoding: TiktokenEncoding;
}
⋮----
// Worker-level singleton for TokenCounter
⋮----
const getTokenCounter = (encoding: TiktokenEncoding): TokenCounter =>
⋮----
// Set logger log level from environment variable if provided
⋮----
export const calculateIndividualFileMetrics = async (
  file: ProcessedFile,
  encoding: TiktokenEncoding,
): Promise<FileMetrics> =>
⋮----
// Cleanup when worker is terminated
</file>

<file path="src/core/metrics/workers/outputMetricsWorker.ts">
import type { TiktokenEncoding } from 'tiktoken';
import { logger, setLogLevelByEnv } from '../../../shared/logger.js';
import { TokenCounter } from '../TokenCounter.js';
⋮----
export interface OutputMetricsTask {
  content: string;
  encoding: TiktokenEncoding;
  path?: string;
}
⋮----
// Worker-level singleton for TokenCounter
⋮----
const getTokenCounter = (encoding: TiktokenEncoding): TokenCounter =>
⋮----
// Set logger log level from environment variable if provided
⋮----
// Cleanup when worker is terminated
</file>

<file path="src/core/metrics/workers/types.ts">
export interface FileMetrics {
  path: string;
  charCount: number;
  tokenCount: number;
}
</file>

<file path="src/core/metrics/calculateAllFileMetrics.ts">
import pc from 'picocolors';
import type { TiktokenEncoding } from 'tiktoken';
import { logger } from '../../shared/logger.js';
import { initPiscina } from '../../shared/processConcurrency.js';
import type { RepomixProgressCallback } from '../../shared/types.js';
import type { ProcessedFile } from '../file/fileTypes.js';
import type { FileMetricsTask } from './workers/fileMetricsWorker.js';
import type { FileMetrics } from './workers/types.js';
⋮----
const initTaskRunner = (numOfTasks: number) =>
⋮----
export const calculateAllFileMetrics = async (
  processedFiles: ProcessedFile[],
  tokenCounterEncoding: TiktokenEncoding,
  progressCallback: RepomixProgressCallback,
  deps = {
    initTaskRunner,
  },
): Promise<FileMetrics[]> =>
⋮----
export const calculateSelectiveFileMetrics = async (
  processedFiles: ProcessedFile[],
  targetFilePaths: string[],
  tokenCounterEncoding: TiktokenEncoding,
  progressCallback: RepomixProgressCallback,
  deps = {
    initTaskRunner,
  },
): Promise<FileMetrics[]> =>
</file>

<file path="src/core/metrics/calculateMetrics.ts">
import type { RepomixConfigMerged } from '../../config/configSchema.js';
import type { RepomixProgressCallback } from '../../shared/types.js';
import type { ProcessedFile } from '../file/fileTypes.js';
import type { GitDiffResult } from '../git/gitDiffHandle.js';
import { calculateAllFileMetrics, calculateSelectiveFileMetrics } from './calculateAllFileMetrics.js';
import { calculateOutputMetrics } from './calculateOutputMetrics.js';
⋮----
export interface CalculateMetricsResult {
  totalFiles: number;
  totalCharacters: number;
  totalTokens: number;
  fileCharCounts: Record<string, number>;
  fileTokenCounts: Record<string, number>;
  gitDiffTokenCount: number;
}
⋮----
import { TokenCounter } from './TokenCounter.js';
⋮----
export const calculateMetrics = async (
  processedFiles: ProcessedFile[],
  output: string,
  progressCallback: RepomixProgressCallback,
  config: RepomixConfigMerged,
  gitDiffResult: GitDiffResult | undefined,
  deps = {
    calculateAllFileMetrics,
    calculateSelectiveFileMetrics,
    calculateOutputMetrics,
  },
): Promise<CalculateMetricsResult> =>
⋮----
// Calculate token count for git diffs if included
⋮----
// For top files display optimization: calculate token counts only for top files by character count
⋮----
// Get top files by character count first
⋮----
// Build character counts for all files
⋮----
// Build token counts only for top files
</file>

<file path="src/core/metrics/calculateOutputMetrics.ts">
import type { TiktokenEncoding } from 'tiktoken';
import { logger } from '../../shared/logger.js';
import { initPiscina } from '../../shared/processConcurrency.js';
import type { OutputMetricsTask } from './workers/outputMetricsWorker.js';
⋮----
const MIN_CONTENT_LENGTH_FOR_PARALLEL = 1_000_000; // 1000KB
⋮----
const initTaskRunner = (numOfTasks: number) =>
⋮----
export const calculateOutputMetrics = async (
  content: string,
  encoding: TiktokenEncoding,
  path?: string,
  deps = {
    initTaskRunner,
  },
): Promise<number> =>
⋮----
// Split content into chunks for parallel processing
⋮----
// Process chunks in parallel
⋮----
// Sum up the results
⋮----
// Process small content directly
</file>

<file path="src/core/metrics/TokenCounter.ts">
import { type Tiktoken, type TiktokenEncoding, get_encoding } from 'tiktoken';
import { logger } from '../../shared/logger.js';
⋮----
export class TokenCounter
⋮----
constructor(encodingName: TiktokenEncoding)
⋮----
// Setup encoding with the specified model
⋮----
public countTokens(content: string, filePath?: string): number
⋮----
public free(): void
</file>

<file path="src/core/output/outputStyles/markdownStyle.ts">
import Handlebars from 'handlebars';
⋮----
export const getMarkdownTemplate = () =>
⋮----
return /* md */ `
</file>

<file path="src/core/output/outputStyles/plainStyle.ts">
export const getPlainTemplate = () =>
</file>

<file path="src/core/output/outputStyles/xmlStyle.ts">
export const getXmlTemplate = () =>
⋮----
return /* xml */ `
</file>

<file path="src/core/output/outputGenerate.ts">
import fs from 'node:fs/promises';
import path from 'node:path';
import { XMLBuilder } from 'fast-xml-parser';
import Handlebars from 'handlebars';
import type { RepomixConfigMerged } from '../../config/configSchema.js';
import { RepomixError } from '../../shared/errorHandle.js';
import { type FileSearchResult, searchFiles } from '../file/fileSearch.js';
import { generateTreeString } from '../file/fileTreeGenerate.js';
import type { ProcessedFile } from '../file/fileTypes.js';
import type { GitDiffResult } from '../git/gitDiffHandle.js';
import type { OutputGeneratorContext, RenderContext } from './outputGeneratorTypes.js';
import { sortOutputFiles } from './outputSort.js';
import {
  generateHeader,
  generateSummaryFileFormat,
  generateSummaryNotes,
  generateSummaryPurpose,
  generateSummaryUsageGuidelines,
} from './outputStyleDecorate.js';
import { getMarkdownTemplate } from './outputStyles/markdownStyle.js';
import { getPlainTemplate } from './outputStyles/plainStyle.js';
import { getXmlTemplate } from './outputStyles/xmlStyle.js';
⋮----
const calculateMarkdownDelimiter = (files: ReadonlyArray<ProcessedFile>): string =>
⋮----
const createRenderContext = (outputGeneratorContext: OutputGeneratorContext): RenderContext =>
⋮----
const generateParsableXmlOutput = async (renderContext: RenderContext): Promise<string> =>
⋮----
const generateHandlebarOutput = async (config: RepomixConfigMerged, renderContext: RenderContext): Promise<string> =>
⋮----
export const generateOutput = async (
  rootDirs: string[],
  config: RepomixConfigMerged,
  processedFiles: ProcessedFile[],
  allFilePaths: string[],
  gitDiffResult: GitDiffResult | undefined = undefined,
  deps = {
    buildOutputGeneratorContext,
    generateHandlebarOutput,
    generateParsableXmlOutput,
    sortOutputFiles,
  },
): Promise<string> =>
⋮----
// Sort processed files by git change count if enabled
⋮----
export const buildOutputGeneratorContext = async (
  rootDirs: string[],
  config: RepomixConfigMerged,
  allFilePaths: string[],
  processedFiles: ProcessedFile[],
  gitDiffResult: GitDiffResult | undefined = undefined,
): Promise<OutputGeneratorContext> =>
</file>

<file path="src/core/output/outputGeneratorTypes.ts">
import type { RepomixConfigMerged } from '../../config/configSchema.js';
import type { ProcessedFile } from '../file/fileTypes.js';
import type { GitDiffResult } from '../git/gitDiffHandle.js';
⋮----
export interface OutputGeneratorContext {
  generationDate: string;
  treeString: string;
  processedFiles: ProcessedFile[];
  config: RepomixConfigMerged;
  instruction: string;
  gitDiffResult: GitDiffResult | undefined;
}
⋮----
export interface RenderContext {
  readonly generationHeader: string;
  readonly summaryPurpose: string;
  readonly summaryFileFormat: string;
  readonly summaryUsageGuidelines: string;
  readonly summaryNotes: string;
  readonly headerText: string | undefined;
  readonly instruction: string;
  readonly treeString: string;
  readonly processedFiles: ReadonlyArray<ProcessedFile>;
  readonly fileSummaryEnabled: boolean;
  readonly directoryStructureEnabled: boolean;
  readonly filesEnabled: boolean;
  readonly escapeFileContent: boolean;
  readonly markdownCodeBlockDelimiter: string;
  readonly gitDiffEnabled: boolean;
  readonly gitDiffWorkTree: string | undefined;
  readonly gitDiffStaged: string | undefined;
}
</file>

<file path="src/core/output/outputSort.ts">
import fs from 'node:fs/promises';
import path from 'node:path';
import type { RepomixConfigMerged } from '../../config/configSchema.js';
import { logger } from '../../shared/logger.js';
import type { ProcessedFile } from '../file/fileTypes.js';
import { getFileChangeCount, isGitInstalled } from '../git/gitRepositoryHandle.js';
⋮----
// Sort files by git change count for output
export const sortOutputFiles = async (
  files: ProcessedFile[],
  config: RepomixConfigMerged,
  deps = {
    getFileChangeCount,
    isGitInstalled,
  },
): Promise<ProcessedFile[]> =>
⋮----
// If git sort is not enabled, return original order
⋮----
// Check if Git is installed
⋮----
// If `.git` directory is not found, return original order
⋮----
// Get file change counts
⋮----
// Sort files by change count (files with more changes go to the bottom)
⋮----
// If git command fails, return original order
</file>

<file path="src/core/output/outputStyleDecorate.ts">
import type { RepomixConfigMerged } from '../../config/configSchema.js';
⋮----
interface ContentInfo {
  selection: {
    isEntireCodebase: boolean;
    include?: boolean;
    ignore?: boolean;
    gitignore?: boolean;
    defaultIgnore?: boolean;
  };
  processing: {
    commentsRemoved: boolean;
    emptyLinesRemoved: boolean;
    securityCheckEnabled: boolean;
    showLineNumbers: boolean;
    parsableStyle: boolean;
    compressed: boolean;
  };
  sorting: {
    gitChanges: boolean;
  };
}
⋮----
export const analyzeContent = (config: RepomixConfigMerged): ContentInfo =>
⋮----
export const generateHeader = (config: RepomixConfigMerged, generationDate: string): string =>
⋮----
// Generate selection description
⋮----
// Add processing information
⋮----
export const generateSummaryPurpose = (config: RepomixConfigMerged): string =>
⋮----
export const generateSummaryFileFormat = (): string =>
⋮----
export const generateSummaryUsageGuidelines = (config: RepomixConfigMerged, repositoryInstruction: string): string =>
⋮----
export const generateSummaryNotes = (config: RepomixConfigMerged): string =>
⋮----
// File selection notes
⋮----
// Processing notes
⋮----
// Sorting notes
⋮----
// Git diffs notes
</file>

<file path="src/core/packager/copyToClipboardIfEnabled.ts">
import { spawn } from 'node:child_process';
import clipboard from 'clipboardy';
import type { RepomixConfigMerged } from '../../config/configSchema.js';
import { logger } from '../../shared/logger.js';
import type { RepomixProgressCallback } from '../../shared/types.js';
⋮----
export const copyToClipboardIfEnabled = async (
  output: string,
  progressCallback: RepomixProgressCallback,
  config: RepomixConfigMerged,
): Promise<void> =>
</file>

<file path="src/core/packager/writeOutputToDisk.ts">
import fs from 'node:fs/promises';
import path from 'node:path';
import type { RepomixConfigMerged } from '../../config/configSchema.js';
import { logger } from '../../shared/logger.js';
⋮----
// Write output to file or stdout
export const writeOutputToDisk = async (output: string, config: RepomixConfigMerged): Promise<undefined> =>
⋮----
// Write to stdout
⋮----
// Normal case: write to file
⋮----
// Create output directory if it doesn't exist
</file>

<file path="src/core/security/workers/securityCheckWorker.ts">
import { lintSource } from '@secretlint/core';
import { creator } from '@secretlint/secretlint-rule-preset-recommend';
import type { SecretLintCoreConfig } from '@secretlint/types';
import { logger, setLogLevelByEnv } from '../../../shared/logger.js';
⋮----
// Security check type to distinguish between regular files and git diffs
export type SecurityCheckType = 'file' | 'gitDiff';
⋮----
export interface SecurityCheckTask {
  filePath: string;
  content: string;
  type: SecurityCheckType;
}
⋮----
export interface SuspiciousFileResult {
  filePath: string;
  messages: string[];
  type: SecurityCheckType;
}
⋮----
// Set logger log level from environment variable if provided
⋮----
export const runSecretLint = async (
  filePath: string,
  content: string,
  type: SecurityCheckType,
  config: SecretLintCoreConfig,
): Promise<SuspiciousFileResult | null> =>
⋮----
// Do not log the actual messages to prevent leaking sensitive information
⋮----
export const createSecretLintConfig = (): SecretLintCoreConfig => (
</file>

<file path="src/core/security/filterOutUntrustedFiles.ts">
import type { RawFile } from '../file/fileTypes.js';
import type { SuspiciousFileResult } from './securityCheck.js';
⋮----
export const filterOutUntrustedFiles = (
  rawFiles: RawFile[],
  suspiciousFilesResults: SuspiciousFileResult[],
): RawFile[]
</file>

<file path="src/core/security/securityCheck.ts">
import pc from 'picocolors';
import { logger } from '../../shared/logger.js';
import { initPiscina } from '../../shared/processConcurrency.js';
import type { RepomixProgressCallback } from '../../shared/types.js';
import type { RawFile } from '../file/fileTypes.js';
import type { GitDiffResult } from '../git/gitDiffHandle.js';
import type { SecurityCheckTask, SecurityCheckType } from './workers/securityCheckWorker.js';
⋮----
export interface SuspiciousFileResult {
  filePath: string;
  messages: string[];
  type: SecurityCheckType;
}
⋮----
const initTaskRunner = (numOfTasks: number) =>
⋮----
export const runSecurityCheck = async (
  rawFiles: RawFile[],
  progressCallback: RepomixProgressCallback = () => {},
  gitDiffResult?: GitDiffResult,
  deps = {
    initTaskRunner,
  },
): Promise<SuspiciousFileResult[]> =>
⋮----
// Add Git diff content for security checking if available
⋮----
// Combine file tasks and Git diff tasks
</file>

<file path="src/core/security/validateFileSafety.ts">
import type { RepomixConfigMerged } from '../../config/configSchema.js';
import { logger } from '../../shared/logger.js';
import type { RepomixProgressCallback } from '../../shared/types.js';
import type { ProcessedFile, RawFile } from '../file/fileTypes.js';
import type { GitDiffResult } from '../git/gitDiffHandle.js';
import { filterOutUntrustedFiles } from './filterOutUntrustedFiles.js';
import { type SuspiciousFileResult, runSecurityCheck } from './securityCheck.js';
⋮----
// Marks which files are suspicious and which are safe
// Returns Git diff results separately so they can be included in the output
// even if they contain sensitive information
export const validateFileSafety = async (
  rawFiles: RawFile[],
  progressCallback: RepomixProgressCallback,
  config: RepomixConfigMerged,
  gitDiffResult?: GitDiffResult,
  deps = {
    runSecurityCheck,
    filterOutUntrustedFiles,
  },
) =>
⋮----
// Separate Git diff results from regular file results
</file>

<file path="src/core/treeSitter/parseStrategies/CssParseStrategy.ts">
import type { SyntaxNode } from 'web-tree-sitter';
import type { ParseContext, ParseStrategy } from './ParseStrategy.js';
⋮----
export class CssParseStrategy implements ParseStrategy
⋮----
parseCapture(
    capture: { node: SyntaxNode; name: string },
    lines: string[],
    processedChunks: Set<string>,
    context: ParseContext,
): string | null
⋮----
// Process CSS-specific capture names
⋮----
// Extract all lines for comments, only the first line for others
⋮----
// For selectors and at-rules, extract only the first line
</file>

<file path="src/core/treeSitter/parseStrategies/DefaultParseStrategy.ts">
import type { SyntaxNode } from 'web-tree-sitter';
import type { ParseContext, ParseStrategy } from './ParseStrategy.js';
⋮----
export class DefaultParseStrategy implements ParseStrategy
⋮----
parseCapture(
    capture: { node: SyntaxNode; name: string },
    lines: string[],
    processedChunks: Set<string>,
    context: ParseContext,
): string | null
</file>

<file path="src/core/treeSitter/parseStrategies/GoParseStrategy.ts">
import type { SyntaxNode } from 'web-tree-sitter';
import type { ParseContext, ParseStrategy } from './ParseStrategy.js';
⋮----
enum CaptureType {
  Comment = 'comment',
  Type = 'definition.type',
  Interface = 'definition.interface',
  Struct = 'definition.struct',
  Package = 'definition.package',
  Import = 'definition.import',
  Function = 'definition.function',
  Method = 'definition.method',
  Module = 'definition.module',
  Variable = 'definition.variable',
  Constant = 'definition.constant',
}
⋮----
type ParseResult = {
  content: string | null;
  processedSignatures?: Set<string>;
};
⋮----
export class GoParseStrategy implements ParseStrategy
⋮----
parseCapture(
    capture: { node: SyntaxNode; name: string },
    lines: string[],
    processedChunks: Set<string>,
    context: ParseContext,
): string | null
⋮----
// Comments
⋮----
// Package declarations
⋮----
// Import declarations
⋮----
// Variable declarations
⋮----
// Constant declarations
⋮----
// Type definitions
⋮----
// Function declarations
⋮----
// Method declarations
⋮----
private getCaptureType(name: string): Set<CaptureType>
⋮----
private getFunctionName(lines: string[], startRow: number): string | null
⋮----
// "func funcName(" pattern detection
⋮----
// Helper to get method name including receiver type
private getMethodWithReceiver(lines: string[], startRow: number): string | null
⋮----
// "func (r ReceiverType) methodName(" pattern detection
⋮----
private findClosingToken(
    lines: string[],
    startRow: number,
    endRow: number,
    openToken: string,
    closeToken: string,
): number
⋮----
private parseSimpleDeclaration(lines: string[], startRow: number, processedChunks: Set<string>): ParseResult
⋮----
private parseBlockDeclaration(
    lines: string[],
    startRow: number,
    endRow: number,
    processedChunks: Set<string>,
): ParseResult
⋮----
private parseFunctionOrMethod(
    lines: string[],
    startRow: number,
    endRow: number,
    processedChunks: Set<string>,
    isMethod: boolean,
): ParseResult
⋮----
private parseTypeDefinition(
    lines: string[],
    startRow: number,
    endRow: number,
    processedChunks: Set<string>,
): ParseResult
</file>

<file path="src/core/treeSitter/parseStrategies/ParseStrategy.ts">
import type { Query, SyntaxNode, Tree } from 'web-tree-sitter';
import type { RepomixConfigMerged } from '../../../config/configSchema.js';
import type { SupportedLang } from '../lang2Query.js';
import { CssParseStrategy } from './CssParseStrategy.js';
import { DefaultParseStrategy } from './DefaultParseStrategy.js';
import { GoParseStrategy } from './GoParseStrategy.js';
import { PythonParseStrategy } from './PythonParseStrategy.js';
import { TypeScriptParseStrategy } from './TypeScriptParseStrategy.js';
import { VueParseStrategy } from './VueParseStrategy.js';
⋮----
export interface ParseContext {
  fileContent: string;
  lines: string[];
  tree: Tree;
  query: Query;
  config: RepomixConfigMerged;
}
⋮----
export interface ParseStrategy {
  parseCapture(
    capture: { node: SyntaxNode; name: string },
    lines: string[],
    processedChunks: Set<string>,
    context: ParseContext,
  ): string | null;
}
⋮----
parseCapture(
    capture: { node: SyntaxNode; name: string },
    lines: string[],
    processedChunks: Set<string>,
    context: ParseContext,
  ): string | null;
⋮----
export function createParseStrategy(lang: SupportedLang): ParseStrategy
</file>

<file path="src/core/treeSitter/parseStrategies/PythonParseStrategy.ts">
import type { SyntaxNode } from 'web-tree-sitter';
import type { ParseContext, ParseStrategy } from './ParseStrategy.js';
⋮----
enum CaptureType {
  Comment = 'comment',
  Class = 'definition.class',
  Function = 'definition.function',
  Docstring = 'docstring',
  TypeAlias = 'definition.type_alias',
}
⋮----
type ParseResult = {
  content: string | null;
  processedSignatures?: Set<string>;
};
⋮----
export class PythonParseStrategy implements ParseStrategy
⋮----
parseCapture(
    capture: { node: SyntaxNode; name: string },
    lines: string[],
    processedChunks: Set<string>,
    context: ParseContext,
): string | null
⋮----
// Class definition
⋮----
// Function definition
⋮----
// Docstring
⋮----
// Comment
⋮----
// Type alias
⋮----
private getCaptureType(name: string): Set<CaptureType>
⋮----
private getDecorators(lines: string[], startRow: number): string[]
⋮----
decorators.unshift(line); // Add to beginning to maintain order
⋮----
private getClassInheritance(lines: string[], startRow: number): string | null
⋮----
private getFunctionSignature(lines: string[], startRow: number): string | null
⋮----
private parseClassDefinition(lines: string[], startRow: number, processedChunks: Set<string>): ParseResult
⋮----
private parseFunctionDefinition(lines: string[], startRow: number, processedChunks: Set<string>): ParseResult
⋮----
private parseDocstringOrComment(
    lines: string[],
    startRow: number,
    endRow: number,
    processedChunks: Set<string>,
): ParseResult
⋮----
private parseTypeAlias(lines: string[], startRow: number, processedChunks: Set<string>): ParseResult
</file>

<file path="src/core/treeSitter/parseStrategies/TypeScriptParseStrategy.ts">
import type { SyntaxNode } from 'web-tree-sitter';
import type { ParseContext, ParseStrategy } from './ParseStrategy.js';
⋮----
enum CaptureType {
  Comment = 'comment',
  Interface = 'definition.interface',
  Type = 'definition.type',
  Enum = 'definition.enum',
  Class = 'definition.class',
  Import = 'definition.import',
  Function = 'definition.function',
  Method = 'definition.method',
  Property = 'definition.property',
}
⋮----
type ParseResult = {
  content: string | null;
  processedSignatures?: Set<string>;
};
⋮----
export class TypeScriptParseStrategy implements ParseStrategy
⋮----
parseCapture(
    capture: { node: SyntaxNode; name: string },
    lines: string[],
    processedChunks: Set<string>,
    context: ParseContext,
): string | null
⋮----
// Function capture
⋮----
// Class capture
⋮----
// Type definition or import capture
⋮----
// Comment capture
⋮----
private getFunctionName(lines: string[], startRow: number): string | null
⋮----
private getCaptureType(name: string): Set<CaptureType>
⋮----
private parseFunctionDefinition(
    lines: string[],
    startRow: number,
    endRow: number,
    processedChunks: Set<string>,
): ParseResult
⋮----
private findSignatureEnd(lines: string[], startRow: number, endRow: number): number
⋮----
private cleanFunctionSignature(lines: string[]): string
⋮----
private parseClassDefinition(
    lines: string[],
    startRow: number,
    endRow: number,
    processedChunks: Set<string>,
): ParseResult
⋮----
private parseTypeOrImport(
    lines: string[],
    startRow: number,
    endRow: number,
    processedChunks: Set<string>,
): ParseResult
</file>

<file path="src/core/treeSitter/parseStrategies/VueParseStrategy.ts">
import type { SyntaxNode } from 'web-tree-sitter';
import type { ParseContext, ParseStrategy } from './ParseStrategy.js';
⋮----
export class VueParseStrategy implements ParseStrategy
⋮----
parseCapture(
    capture: { node: SyntaxNode; name: string },
    lines: string[],
    processedChunks: Set<string>,
    context: ParseContext,
): string | null
⋮----
// Extract the content based on the capture type
⋮----
// Create a unique ID for this chunk
</file>

<file path="src/core/treeSitter/queries/queryC.ts">

</file>

<file path="src/core/treeSitter/queries/queryCpp.ts">

</file>

<file path="src/core/treeSitter/queries/queryCSharp.ts">

</file>

<file path="src/core/treeSitter/queries/queryCss.ts">

</file>

<file path="src/core/treeSitter/queries/queryGo.ts">

</file>

<file path="src/core/treeSitter/queries/queryJava.ts">

</file>

<file path="src/core/treeSitter/queries/queryJavascript.ts">

</file>

<file path="src/core/treeSitter/queries/queryPhp.ts">

</file>

<file path="src/core/treeSitter/queries/queryPython.ts">

</file>

<file path="src/core/treeSitter/queries/queryRuby.ts">

</file>

<file path="src/core/treeSitter/queries/queryRust.ts">

</file>

<file path="src/core/treeSitter/queries/querySolidity.ts">

</file>

<file path="src/core/treeSitter/queries/querySwift.ts">

</file>

<file path="src/core/treeSitter/queries/queryTypescript.ts">

</file>

<file path="src/core/treeSitter/queries/queryVue.ts">

</file>

<file path="src/core/treeSitter/queries/README.md">
# Credits
Repomix uses modified versions of tree-sitter queries from Aider and Cline:
* [https://github.com/Aider-AI/aider](https://github.com/Aider-AI/aider)  licensed under the Apache License 2.0.
* [https://github.com/cline/cline](https://github.com/cline/cline)  licensed under the Apache License 2.0.

Aider uses modified versions of the tags.scm files from these open source 
tree-sitter language implementations:

* [https://github.com/tree-sitter/tree-sitter-c](https://github.com/tree-sitter/tree-sitter-c)  licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-c-sharp](https://github.com/tree-sitter/tree-sitter-c-sharp)  licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-cpp](https://github.com/tree-sitter/tree-sitter-cpp)  licensed under the MIT License.
* [https://github.com/Wilfred/tree-sitter-elisp](https://github.com/Wilfred/tree-sitter-elisp)  licensed under the MIT License.
* [https://github.com/elixir-lang/tree-sitter-elixir](https://github.com/elixir-lang/tree-sitter-elixir)  licensed under the Apache License, Version 2.0.
* [https://github.com/elm-tooling/tree-sitter-elm](https://github.com/elm-tooling/tree-sitter-elm)  licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-go](https://github.com/tree-sitter/tree-sitter-go)  licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-java](https://github.com/tree-sitter/tree-sitter-java)  licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-javascript](https://github.com/tree-sitter/tree-sitter-javascript)  licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-ocaml](https://github.com/tree-sitter/tree-sitter-ocaml)  licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-php](https://github.com/tree-sitter/tree-sitter-php)  licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-python](https://github.com/tree-sitter/tree-sitter-python)  licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-ql](https://github.com/tree-sitter/tree-sitter-ql)  licensed under the MIT License.
* [https://github.com/r-lib/tree-sitter-r](https://github.com/r-lib/tree-sitter-r)  licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-ruby](https://github.com/tree-sitter/tree-sitter-ruby)  licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-rust](https://github.com/tree-sitter/tree-sitter-rust)  licensed under the MIT License.
* [https://github.com/tree-sitter/tree-sitter-typescript](https://github.com/tree-sitter/tree-sitter-typescript)  licensed under the MIT License.
</file>

<file path="src/core/treeSitter/ext2Lang.ts">
/**
 * @see https://unpkg.com/browse/tree-sitter-wasms@latest/out/
 */
</file>

<file path="src/core/treeSitter/lang2Query.ts">
import { queryC } from './queries/queryC.js';
import { queryCSharp } from './queries/queryCSharp.js';
import { queryCpp } from './queries/queryCpp.js';
import { queryCss } from './queries/queryCss.js';
import { queryGo } from './queries/queryGo.js';
import { queryJava } from './queries/queryJava.js';
import { queryJavascript } from './queries/queryJavascript.js';
import { queryPhp } from './queries/queryPhp.js';
import { queryPython } from './queries/queryPython.js';
import { queryRuby } from './queries/queryRuby.js';
import { queryRust } from './queries/queryRust.js';
import { querySolidity } from './queries/querySolidity.js';
import { querySwift } from './queries/querySwift.js';
import { queryTypescript } from './queries/queryTypescript.js';
import { queryVue } from './queries/queryVue.js';
⋮----
export type SupportedLang = keyof typeof lang2Query;
</file>

<file path="src/core/treeSitter/languageParser.ts">
import Parser from 'web-tree-sitter';
⋮----
import { RepomixError } from '../../shared/errorHandle.js';
import { ext2Lang } from './ext2Lang.js';
import { type SupportedLang, lang2Query } from './lang2Query.js';
import { loadLanguage } from './loadLanguage.js';
import { type ParseStrategy, createParseStrategy } from './parseStrategies/ParseStrategy.js';
⋮----
interface LanguageResources {
  parser: Parser;
  query: Parser.Query;
  strategy: ParseStrategy;
}
⋮----
export class LanguageParser
⋮----
private getFileExtension(filePath: string): string
⋮----
private async prepareLang(name: SupportedLang): Promise<LanguageResources>
⋮----
private async getResources(name: SupportedLang): Promise<LanguageResources>
⋮----
public async getParserForLang(name: SupportedLang): Promise<Parser>
⋮----
public async getQueryForLang(name: SupportedLang): Promise<Parser.Query>
⋮----
public async getStrategyForLang(name: SupportedLang): Promise<ParseStrategy>
⋮----
public guessTheLang(filePath: string): SupportedLang | undefined
⋮----
public async init(): Promise<void>
⋮----
public async dispose(): Promise<void>
</file>

<file path="src/core/treeSitter/loadLanguage.ts">
import fs from 'node:fs/promises';
import { createRequire } from 'node:module';
import path from 'node:path';
import Parser from 'web-tree-sitter';
⋮----
export async function loadLanguage(langName: string): Promise<Parser.Language>
⋮----
async function getWasmPath(langName: string): Promise<string>
</file>

<file path="src/core/treeSitter/parseFile.ts">
import type { QueryCapture } from 'web-tree-sitter';
import type { RepomixConfigMerged } from '../../config/configSchema.js';
import { logger } from '../../shared/logger.js';
import type { SupportedLang } from './lang2Query.js';
import { LanguageParser } from './languageParser.js';
import { type ParseContext, createParseStrategy } from './parseStrategies/ParseStrategy.js';
⋮----
interface CapturedChunk {
  content: string;
  startRow: number;
  endRow: number;
}
⋮----
// TODO: Do something with config: RepomixConfigMerged, it is not used (yet)
export const parseFile = async (fileContent: string, filePath: string, config: RepomixConfigMerged) =>
⋮----
// Split the file content into individual lines
⋮----
// Language not supported
⋮----
// Parse the file content into an Abstract Syntax Tree (AST)
⋮----
// Get the appropriate parse strategy for the language
⋮----
// Create parse context
⋮----
// Apply the query to the AST and get the captures
⋮----
// Sort captures by their start position
⋮----
const getLanguageParserSingleton = async () =>
⋮----
const filterDuplicatedChunks = (chunks: CapturedChunk[]): CapturedChunk[] =>
⋮----
// Group chunks by their start row
⋮----
// For each start row, keep the chunk with the most content
⋮----
// Sort filtered chunks by start row
⋮----
const mergeAdjacentChunks = (chunks: CapturedChunk[]): CapturedChunk[] =>
⋮----
// Merge the current chunk with the previous one
</file>

<file path="src/core/packager.ts">
import type { RepomixConfigMerged } from '../config/configSchema.js';
import type { RepomixProgressCallback } from '../shared/types.js';
import { collectFiles } from './file/fileCollect.js';
import { sortPaths } from './file/filePathSort.js';
import { processFiles } from './file/fileProcess.js';
import { searchFiles } from './file/fileSearch.js';
import type { ProcessedFile, RawFile } from './file/fileTypes.js';
import { GitDiffResult, getGitDiffs } from './git/gitDiffHandle.js';
import { calculateMetrics } from './metrics/calculateMetrics.js';
import { generateOutput } from './output/outputGenerate.js';
import { copyToClipboardIfEnabled } from './packager/copyToClipboardIfEnabled.js';
import { writeOutputToDisk } from './packager/writeOutputToDisk.js';
import type { SuspiciousFileResult } from './security/securityCheck.js';
import { validateFileSafety } from './security/validateFileSafety.js';
⋮----
export interface PackResult {
  totalFiles: number;
  totalCharacters: number;
  totalTokens: number;
  fileCharCounts: Record<string, number>;
  fileTokenCounts: Record<string, number>;
  gitDiffTokenCount: number;
  suspiciousFilesResults: SuspiciousFileResult[];
  suspiciousGitDiffResults: SuspiciousFileResult[];
  processedFiles: ProcessedFile[];
  safeFilePaths: string[];
}
⋮----
export const pack = async (
  rootDirs: string[],
  config: RepomixConfigMerged,
  progressCallback: RepomixProgressCallback = () => {},
  overrideDeps: Partial<typeof defaultDeps> = {},
  explicitFiles?: string[],
): Promise<PackResult> =>
⋮----
// Sort file paths
⋮----
// Regroup sorted file paths by rootDir
⋮----
// Get git diffs if enabled - run this before security check
⋮----
// Run security check and get filtered safe files
⋮----
// Process files (remove comments, etc.)
⋮----
// Create a result object that includes metrics and security results
</file>

<file path="src/mcp/prompts/packRemoteRepositoryPrompts.ts">
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
⋮----
/**
 * Register Repomix-related prompts to the MCP server
 */
export const registerPackRemoteRepositoryPrompt = (mcpServer: McpServer) =>
⋮----
// Pack Remote Repository Prompt
⋮----
// Convert compress string to boolean
</file>

<file path="src/mcp/tools/fileSystemReadDirectoryTool.ts">
import fs from 'node:fs/promises';
import path from 'node:path';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { z } from 'zod';
import { logger } from '../../shared/logger.js';
import { buildMcpToolErrorResponse, buildMcpToolSuccessResponse } from './mcpToolRuntime.js';
⋮----
/**
 * Register file system directory listing tool
 */
export const registerFileSystemReadDirectoryTool = (mcpServer: McpServer) =>
⋮----
// Ensure path is absolute
⋮----
// Check if directory exists
⋮----
// Read directory contents
</file>

<file path="src/mcp/tools/fileSystemReadFileTool.ts">
import fs from 'node:fs/promises';
import path from 'node:path';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { z } from 'zod';
import type { SuspiciousFileResult } from '../../core/security/securityCheck.js';
import { createSecretLintConfig, runSecretLint } from '../../core/security/workers/securityCheckWorker.js';
import { logger } from '../../shared/logger.js';
import { buildMcpToolErrorResponse, buildMcpToolSuccessResponse } from './mcpToolRuntime.js';
⋮----
/**
 * Register file system read file tool with security checks
 */
export const registerFileSystemReadFileTool = (mcpServer: McpServer) =>
⋮----
// Ensure path is absolute
⋮----
// Check if file exists
⋮----
// Check if it's a directory
⋮----
// Read file content
⋮----
// Perform security check using the existing worker
⋮----
// If security check found issues, block the file
</file>

<file path="src/mcp/tools/grepRepomixOutputTool.ts">
import fs from 'node:fs/promises';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { z } from 'zod';
import { logger } from '../../shared/logger.js';
import { buildMcpToolErrorResponse, buildMcpToolSuccessResponse, getOutputFilePath } from './mcpToolRuntime.js';
⋮----
/**
 * Search options for grep functionality
 */
interface SearchOptions {
  pattern: string;
  contextLines: number;
  beforeLines: number;
  afterLines: number;
  ignoreCase: boolean;
}
⋮----
/**
 * Search match result
 */
interface SearchMatch {
  lineNumber: number;
  line: string;
  matchedText: string;
}
⋮----
/**
 * Search result containing matches and formatted output
 */
interface SearchResult {
  matches: SearchMatch[];
  formattedOutput: string[];
}
⋮----
/**
 * Register the tool to search Repomix output files with grep-like functionality
 */
export const registerGrepRepomixOutputTool = (mcpServer: McpServer) =>
⋮----
// Determine before and after lines
⋮----
// Perform grep search using separated functions
⋮----
/**
 * Create and validate a regular expression pattern
 */
export const createRegexPattern = (
  pattern: string,
  ignoreCase: boolean,
  deps = {
    RegExp,
  },
): RegExp =>
⋮----
/**
 * Search for pattern matches in file content
 */
export const searchInContent = (
  content: string,
  options: SearchOptions,
  deps = {
    createRegexPattern,
  },
): SearchMatch[] =>
⋮----
/**
 * Format search results with separate before and after context lines
 */
export const formatSearchResults = (
  lines: string[],
  matches: SearchMatch[],
  beforeLines: number,
  afterLines: number,
): string[] =>
⋮----
// Add separator if there's a gap between previous and current context
⋮----
/**
 * Perform grep-like search on content
 */
export const performGrepSearch = (
  content: string,
  options: SearchOptions,
  deps = {
    searchInContent,
    formatSearchResults,
  },
): SearchResult =>
</file>

<file path="src/mcp/tools/mcpToolRuntime.ts">
import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { generateFileTree, generateTreeString } from '../../core/file/fileTreeGenerate.js';
import type { ProcessedFile } from '../../core/file/fileTypes.js';
import { logger } from '../../shared/logger.js';
⋮----
// Map to store generated output files
⋮----
// Register an output file
export const registerOutputFile = (id: string, filePath: string): void =>
⋮----
// Get file path from output ID
export const getOutputFilePath = (id: string): string | undefined =>
⋮----
export interface McpToolMetrics {
  totalFiles: number;
  totalCharacters: number;
  totalTokens: number;
  fileCharCounts: Record<string, number>;
  fileTokenCounts: Record<string, number>;
  processedFiles: ProcessedFile[];
  safeFilePaths: string[];
}
⋮----
export interface McpToolContext {
  directory?: string;
  repository?: string;
}
⋮----
/**
 * Creates a temporary directory for MCP tool operations
 */
export const createToolWorkspace = async (): Promise<string> =>
⋮----
/**
 * Generate a unique output ID
 */
export const generateOutputId = (): string =>
⋮----
/**
 * Creates a result object with metrics information for MCP tools
 */
export const formatToolResponse = async (
  context: McpToolContext,
  metrics: McpToolMetrics,
  outputFilePath: string,
  topFilesLen = 5,
): Promise<CallToolResult> =>
⋮----
// Generate output ID and register the file
⋮----
// Calculate total lines from the output file
⋮----
// Get top files by character count
⋮----
// Directory Structure
⋮----
// Create JSON string with all the metrics information
⋮----
/**
 * Creates an error result for MCP tools
 */
export const formatToolError = (error: unknown): CallToolResult =>
⋮----
/**
 * Creates a successful MCP tool response with type safety
 */
export const buildMcpToolSuccessResponse = (messages: string[]): CallToolResult =>
⋮----
/**
 * Creates an error MCP tool response with type safety
 */
export const buildMcpToolErrorResponse = (errorMessages: string[]): CallToolResult =>
</file>

<file path="src/mcp/tools/packCodebaseTool.ts">
import path from 'node:path';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { z } from 'zod';
import { runCli } from '../../cli/cliRun.js';
import type { CliOptions } from '../../cli/types.js';
import {
  buildMcpToolErrorResponse,
  createToolWorkspace,
  formatToolError,
  formatToolResponse,
} from './mcpToolRuntime.js';
⋮----
export const registerPackCodebaseTool = (mcpServer: McpServer) =>
⋮----
// Extract metrics information from the pack result
</file>

<file path="src/mcp/tools/packRemoteRepositoryTool.ts">
import path from 'node:path';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { z } from 'zod';
import { runCli } from '../../cli/cliRun.js';
import type { CliOptions } from '../../cli/types.js';
import {
  buildMcpToolErrorResponse,
  createToolWorkspace,
  formatToolError,
  formatToolResponse,
} from './mcpToolRuntime.js';
⋮----
export const registerPackRemoteRepositoryTool = (mcpServer: McpServer) =>
⋮----
// Extract metrics information from the pack result
</file>

<file path="src/mcp/tools/readRepomixOutputTool.ts">
import fs from 'node:fs/promises';
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
import { z } from 'zod';
import { logger } from '../../shared/logger.js';
import { buildMcpToolErrorResponse, buildMcpToolSuccessResponse, getOutputFilePath } from './mcpToolRuntime.js';
⋮----
/**
 * Register the tool to read Repomix output files
 */
export const registerReadRepomixOutputTool = (mcpServer: McpServer) =>
⋮----
// Get the file path from the registry
⋮----
// Check if the file exists
⋮----
// Read the file content
⋮----
// Validate that startLine is less than or equal to endLine when both are provided
</file>

<file path="src/mcp/mcpServer.ts">
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { getVersion } from '../core/file/packageJsonParse.js';
import { logger } from '../shared/logger.js';
import { registerPackRemoteRepositoryPrompt } from './prompts/packRemoteRepositoryPrompts.js';
import { registerFileSystemReadDirectoryTool } from './tools/fileSystemReadDirectoryTool.js';
import { registerFileSystemReadFileTool } from './tools/fileSystemReadFileTool.js';
import { registerGrepRepomixOutputTool } from './tools/grepRepomixOutputTool.js';
import { registerPackCodebaseTool } from './tools/packCodebaseTool.js';
import { registerPackRemoteRepositoryTool } from './tools/packRemoteRepositoryTool.js';
import { registerReadRepomixOutputTool } from './tools/readRepomixOutputTool.js';
⋮----
export const createMcpServer = async () =>
⋮----
// Register the prompts
⋮----
// Register the tools
⋮----
type Dependencies = {
  processExit?: (code?: number) => never;
};
⋮----
export const runMcpServer = async (deps: Dependencies = defaultDependencies) =>
⋮----
const handleExit = async () =>
</file>

<file path="src/shared/constants.ts">

</file>

<file path="src/shared/errorHandle.ts">
import { z } from 'zod';
import { REPOMIX_DISCORD_URL, REPOMIX_ISSUES_URL } from './constants.js';
import { logger, repomixLogLevels } from './logger.js';
⋮----
export class RepomixError extends Error
⋮----
constructor(message: string)
⋮----
export class RepomixConfigValidationError extends RepomixError
⋮----
export const handleError = (error: unknown): void =>
⋮----
// If expected error, show stack trace for debugging
⋮----
// If unexpected error, show stack trace by default
⋮----
// Unknown errors
⋮----
// Community support information
⋮----
export const rethrowValidationErrorIfZodError = (error: unknown, message: string): void =>
</file>

<file path="src/shared/logger.ts">
import util from 'node:util';
import pc from 'picocolors';
⋮----
SILENT: -1, // No output
ERROR: 0, // error
WARN: 1, // warn
INFO: 2, // success, info, log, note
DEBUG: 3, // debug, trace
⋮----
export type RepomixLogLevel = (typeof repomixLogLevels)[keyof typeof repomixLogLevels];
⋮----
class RepomixLogger
⋮----
constructor()
⋮----
init()
⋮----
setLogLevel(level: RepomixLogLevel)
⋮----
getLogLevel(): RepomixLogLevel
⋮----
error(...args: unknown[])
⋮----
warn(...args: unknown[])
⋮----
success(...args: unknown[])
⋮----
info(...args: unknown[])
⋮----
log(...args: unknown[])
⋮----
note(...args: unknown[])
⋮----
debug(...args: unknown[])
⋮----
trace(...args: unknown[])
⋮----
private formatArgs(args: unknown[]): string
⋮----
export const setLogLevel = (level: RepomixLogLevel) =>
⋮----
/**
 * Set logger log level from REPOMIX_LOGLEVEL environment variable if valid.
 */
export const setLogLevelByEnv = () =>
</file>

<file path="src/shared/patternUtils.ts">
/**
 * Splits comma-separated glob patterns while preserving brace expansion patterns.
 * This ensures patterns with braces are treated as a single pattern,
 * rather than being split at commas inside the braces.
 * Whitespace around patterns is also trimmed.
 */
export const splitPatterns = (patterns?: string): string[] =>
⋮----
// Only split on commas when not inside braces
⋮----
// Add the last pattern
</file>

<file path="src/shared/processConcurrency.ts">
import os from 'node:os';
import { Piscina } from 'piscina';
import { logger } from './logger.js';
⋮----
export const getProcessConcurrency = (): number =>
⋮----
export const getWorkerThreadCount = (numOfTasks: number):
⋮----
// Limit max threads based on number of tasks
⋮----
export const initPiscina = (numOfTasks: number, workerPath: string): Piscina =>
</file>

<file path="src/shared/types.ts">
export type RepomixProgressCallback = (message: string) => void;
</file>

<file path="src/types/git-url-parse.d.ts">
/**
 * Type definition extension for git-url-parse library
 *
 * This file exists because the git-url-parse library's built-in type definitions
 * are incomplete. The library supports a second 'refs' parameter for the gitUrlParse
 * function, which is documented in the library's README but not included in its
 * type definitions.
 *
 * Without this type definition extension, we would need to use @ts-ignore when
 * calling gitUrlParse with the refs parameter, which reduces type safety and
 * makes the code harder to maintain.
 *
 * This file uses TypeScript's module augmentation feature to extend the existing
 * type definitions without modifying the original library code.
 */
⋮----
interface GitUrl extends gitUp.ParsedUrl {
      /** The Git provider (e.g. `"github.com"`). */
      source: string;
      /** The repository owner. */
      owner: string;
      /** The repository name. */
      name: string;
      /** The repository ref (e.g., "master" or "dev"). */
      ref: string;
      /** A filepath relative to the repository root. */
      filepath: string;
      /** The type of filepath in the url ("blob" or "tree"). */
      filepathtype: string;
      /** The owner and name values in the `owner/name` format. */
      full_name: string;
      /** The organization the owner belongs to. This is CloudForge specific. */
      organization: string;
      /** Whether to add the `.git` suffix or not. */
      git_suffix?: boolean | undefined;
      toString(type?: string): string;
    }
⋮----
/** The Git provider (e.g. `"github.com"`). */
⋮----
/** The repository owner. */
⋮----
/** The repository name. */
⋮----
/** The repository ref (e.g., "master" or "dev"). */
⋮----
/** A filepath relative to the repository root. */
⋮----
/** The type of filepath in the url ("blob" or "tree"). */
⋮----
/** The owner and name values in the `owner/name` format. */
⋮----
/** The organization the owner belongs to. This is CloudForge specific. */
⋮----
/** Whether to add the `.git` suffix or not. */
⋮----
toString(type?: string): string;
⋮----
function stringify(url: GitUrl, type?: string): string;
⋮----
/**
   * Parses a Git url.
   * @param url The Git url to parse.
   * @param refs An array of strings representing the refs. This is helpful for URLs with branches containing slashes.
   * @returns The GitUrl object containing parsed information.
   */
function gitUrlParse(url: string, refs?: string[]): gitUrlParse.GitUrl;
</file>

<file path="src/index.ts">
// ---------------------------------------------------------------------------------------------------------------------
// Core
// ---------------------------------------------------------------------------------------------------------------------
⋮----
// File
⋮----
// Git
⋮----
// Security
⋮----
// Token Count
⋮----
// Tree-sitter
⋮----
// ---------------------------------------------------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------------------------------------------------
⋮----
// ---------------------------------------------------------------------------------------------------------------------
// Shard
// ---------------------------------------------------------------------------------------------------------------------
⋮----
// ---------------------------------------------------------------------------------------------------------------------
// CLI
// ---------------------------------------------------------------------------------------------------------------------
⋮----
// Run CLI Repomix
⋮----
// Init action
⋮----
// Default action
⋮----
// Remote action
</file>

<file path="website/README.md">
# Repomix Website

This directory contains the source code for the Repomix website, built with [VitePress](https://vitepress.dev/) and [Vue.js](https://vuejs.org/)

## Prerequisites

- Docker must be installed on your system

## Development

To start the development server:

```bash
# Start the website development server
npm run website

# Access the website at http://localhost:5173/
```

## Documentation

When updating documentation, you only need to update the English version (`client/src/en/`).
The maintainers will handle translations to other languages.

## Building for Production

To build the website for production:

```bash
npm run website:build
```

The built files will be available in the `client/dist` directory.
</file>

<file path="CLAUDE.md">
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Please make sure to check the rules written in `.agents/rules/base.md` as they contain important project-specific guidelines and instructions.
</file>

<file path="CODE_OF_CONDUCT.md">
# Repomix Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we, as contributors and maintainers, pledge to make participation in our project and community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contribute to creating a positive environment include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as physical or electronic addresses, without explicit permission
* Other conduct that could reasonably be considered inappropriate in a professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that do not align with this Code of Conduct or to ban temporarily or permanently any contributor for behaviors that they deem inappropriate, threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [[email protected]](mailto:[email protected]). All complaints will be reviewed and investigated, resulting in a response deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality concerning the reporter of an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [https://www.contributor-covenant.org/version/1/4/code-of-conduct.html](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html).

[homepage]: https://www.contributor-covenant.org

For answers to common questions about this Code of Conduct, see [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq).
</file>

<file path="CONTRIBUTING.md">
# Contribution Guide

Thanks for your interest in **Repomix**! 🚀 We'd love your help to make it even better. Here's how you can get involved:


- **Create an Issue**: Spot a bug? Have an idea for a new feature? Let us know by creating an issue.
- **Submit a Pull Request**: Found something to fix or improve? Jump in and submit a PR!
- **Spread the Word**: Share your experience with Repomix on social media, blogs, or with your tech community.
- **Use Repomix**: The best feedback comes from real-world usage, so feel free to integrate Repomix into your own projects!

## Maintainers

Repomix is maintained by Yamadashy ([@yamadashy](https://github.com/yamadashy)). While all contributions are welcome, please understand that not every suggestion may be accepted if they don't align with the project's goals or coding standards.

---

## Pull Requests

Before submitting a Pull Request, please ensure:

1. Your code passes all tests: Run `npm run test`
2. Your code adheres to our linting standards: Run `npm run lint`
3. You have updated relevant documentation (especially README.md) if you've added or changed functionality.

## Local Development

To set up Repomix for local development:

```bash
git clone https://github.com/yamadashy/repomix.git
cd repomix
npm install
```

To run Repomix locally:

```bash
npm run repomix
```

### Docker Usage
You can also run Repomix using Docker. Here's how:

First, build the Docker image:
```bash
docker build -t repomix .
```

Then, run the Docker container:
```bash
docker run -v ./:/app -it --rm repomix
```

### Coding Style

We use [Biome](https://biomejs.dev/) for linting and formatting. Please make sure your code follows the style guide by running:

```bash
npm run lint
```

### Testing

We use [Vitest](https://vitest.dev/) for testing. To run the tests:

```bash
npm run test
```

For test coverage:

```bash
npm run test-coverage
```

### Documentation

When adding new features or making changes, please update the relevant documentation in the README.md file.

### Website Development

The Repomix website is built with [VitePress](https://vitepress.dev/). To run the website locally:

```bash
# Prerequisites: Docker must be installed on your system

# Start the website development server
npm run website

# Access the website at http://localhost:5173/
```

The website source code is located in the `website` directory. The main components are:

- `website/client`: Frontend code (Vue.js components, styles, etc.)
- `website/server`: Backend API server

When updating documentation, you only need to update the English version (`website/client/src/en/`).
The maintainers will handle translations to other languages.

## Releasing

New versions are managed by the maintainer. If you think a release is needed, open an issue to discuss it

Thank you for contributing to Repomix!
</file>

<file path="llms-install.md">
# Repomix MCP Server Installation Guide

This guide is specifically designed for AI agents like Cline to install and configure the Repomix MCP server for use with LLM applications like Claude Desktop, Cursor, Roo Code, and Cline.

## Overview

Repomix MCP server is a powerful tool that packages local or remote codebases into AI-friendly formats. It allows AI assistants to analyze code efficiently without manual file preparation, optimizing token usage and providing consistent output.

## Prerequisites

Before installation, you need:

1. Node.js 20.0.0 or higher
2. npm (Node Package Manager)

## Installation and Configuration

### Configure MCP Settings

Add the Repomix MCP server configuration to your MCP settings file based on your LLM client:

#### Configuration File Locations

- Cline (VS Code Extension): `~/Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json`
- Roo Code (VS Code Extension): `~/Library/Application Support/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/cline_mcp_settings.json`
- Claude Desktop: `~/Library/Application Support/Claude/claude_desktop_config.json`
- Cursor: `[project root]/.cursor/mcp.json`

Add this configuration to your chosen client's settings file:

```json
{
  "mcpServers": {
    "repomix": {
      "command": "npx",
      "args": [
        "-y",
        "repomix",
        "--mcp"
      ],
      "disabled": false,
      "autoApprove": []
    }
  }
}
```

This configuration uses `npx` to run Repomix directly without requiring a global installation.

## Available MCP Tools

Once configured, you'll have access to these Repomix tools:

### 1. pack_codebase

This tool packages a local code directory into a consolidated XML file for AI analysis. It analyzes the codebase structure, extracts relevant code content, and generates a comprehensive report including metrics, file tree, and formatted code content.

**Parameters:**
- `directory`: (Required) Absolute path to the directory to pack
- `compress`: (Optional, default: false) Enable Tree-sitter compression to extract essential code signatures and structure while removing implementation details. Reduces token usage by ~70% while preserving semantic meaning. Generally not needed since grep_repomix_output allows incremental content retrieval. Use only when you specifically need the entire codebase content for large repositories.
- `includePatterns`: (Optional) Specify files to include using fast-glob patterns. Multiple patterns can be comma-separated (e.g., "**/*.{js,ts}", "src/**,docs/**"). Only matching files will be processed.
- `ignorePatterns`: (Optional) Specify additional files to exclude using fast-glob patterns. Multiple patterns can be comma-separated (e.g., "test/**,*.spec.js", "node_modules/**,dist/**"). These patterns supplement .gitignore and built-in exclusions.
- `topFilesLength`: (Optional, default: 10) Number of largest files by size to display in the metrics summary for codebase analysis.

**Example:**
```json
{
  "directory": "/path/to/your/project",
  "compress": false,
  "includePatterns": "src/**/*.ts,**/*.md",
  "ignorePatterns": "**/*.log,tmp/",
  "topFilesLength": 10
}
```

### 2. pack_remote_repository

This tool fetches, clones, and packages a GitHub repository into a consolidated XML file for AI analysis. It automatically clones the remote repository, analyzes its structure, and generates a comprehensive report.

**Parameters:**
- `remote`: (Required) GitHub repository URL or user/repo format (e.g., "yamadashy/repomix", "https://github.com/user/repo", or "https://github.com/user/repo/tree/branch")
- `compress`: (Optional, default: false) Enable Tree-sitter compression to extract essential code signatures and structure while removing implementation details. Reduces token usage by ~70% while preserving semantic meaning. Generally not needed since grep_repomix_output allows incremental content retrieval. Use only when you specifically need the entire codebase content for large repositories.
- `includePatterns`: (Optional) Specify files to include using fast-glob patterns. Multiple patterns can be comma-separated (e.g., "**/*.{js,ts}", "src/**,docs/**"). Only matching files will be processed.
- `ignorePatterns`: (Optional) Specify additional files to exclude using fast-glob patterns. Multiple patterns can be comma-separated (e.g., "test/**,*.spec.js", "node_modules/**,dist/**"). These patterns supplement .gitignore and built-in exclusions.
- `topFilesLength`: (Optional, default: 10) Number of largest files by size to display in the metrics summary for codebase analysis.

**Example:**
```json
{
  "remote": "yamadashy/repomix",
  "compress": false,
  "includePatterns": "src/**/*.ts,**/*.md",
  "ignorePatterns": "**/*.log,tmp/",
  "topFilesLength": 10
}
```

### 3. read_repomix_output

This tool reads the contents of a Repomix-generated output file. Supports partial reading with line range specification for large files. This tool is designed for environments where direct file system access is limited.

**Parameters:**
- `outputId`: (Required) ID of the Repomix output file to read
- `startLine`: (Optional) Starting line number (1-based, inclusive). If not specified, reads from beginning.
- `endLine`: (Optional) Ending line number (1-based, inclusive). If not specified, reads to end.

**Features:**
- Specifically designed for web-based environments or sandboxed applications
- Retrieves the content of previously generated outputs using their ID
- Provides secure access to packed codebase without requiring file system access
- Supports partial reading for large files

**Example:**
```json
{
  "outputId": "8f7d3b1e2a9c6054",
  "startLine": 100,
  "endLine": 200
}
```

### 4. grep_repomix_output

This tool searches for patterns in a Repomix output file using grep-like functionality with JavaScript RegExp syntax. Returns matching lines with optional context lines around matches.

**Parameters:**
- `outputId`: (Required) ID of the Repomix output file to search
- `pattern`: (Required) Search pattern (JavaScript RegExp regular expression syntax)
- `contextLines`: (Optional, default: 0) Number of context lines to show before and after each match. Overridden by beforeLines/afterLines if specified.
- `beforeLines`: (Optional) Number of context lines to show before each match (like grep -B). Takes precedence over contextLines.
- `afterLines`: (Optional) Number of context lines to show after each match (like grep -A). Takes precedence over contextLines.
- `ignoreCase`: (Optional, default: false) Perform case-insensitive matching

**Features:**
- Uses JavaScript RegExp syntax for powerful pattern matching
- Supports context lines for better understanding of matches
- Allows separate control of before/after context lines
- Case-sensitive and case-insensitive search options

**Example:**
```json
{
  "outputId": "8f7d3b1e2a9c6054",
  "pattern": "function\\s+\\w+\\(",
  "contextLines": 3,
  "ignoreCase": false
}
```

### 5. file_system_read_file

This tool reads a file from the local file system using an absolute path. Includes built-in security validation to detect and prevent access to files containing sensitive information.

**Parameters:**
- `path`: (Required) Absolute path to the file to read

**Security features:**
- Implements security validation using [Secretlint](https://github.com/secretlint/secretlint)
- Prevents access to files containing sensitive information (API keys, passwords, secrets)
- Validates absolute paths to prevent directory traversal attacks

**Example:**
```json
{
  "path": "/absolute/path/to/file.txt"
}
```

### 6. file_system_read_directory

This tool lists the contents of a directory using an absolute path. Returns a formatted list showing files and subdirectories with clear indicators.

**Parameters:**
- `path`: (Required) Absolute path to the directory to list

**Features:**
- Shows files and directories with clear indicators (`[FILE]` or `[DIR]`)
- Provides safe directory traversal with proper error handling
- Validates paths and ensures they are absolute
- Useful for exploring project structure and understanding codebase organization

**Example:**
```json
{
  "path": "/absolute/path/to/directory"
}
```

## Verify Installation

To verify the installation is working:

1. Restart your LLM application (Cline, Claude Desktop, etc.)
2. Test the connection by running a simple command like:
  ```
  Please package the local directory /path/to/project for AI analysis using Repomix.
  ```
  or
  ```
  Please fetch and package the GitHub repository yamadashy/repomix for AI analysis.
  ```

## Usage Examples

Here are some examples of how to use Repomix MCP server with AI assistants:

### Local Codebase Analysis

```
Can you analyze the code in my project at /path/to/project? Please use Repomix to package it first.
```

### Remote Repository Analysis

```
I'd like you to review the code in the GitHub repository username/repo. Please use Repomix to package it first.
```

### Specific File Types Analysis

```
Please package my project at /path/to/project, but only include TypeScript files and markdown documentation.
```

## Troubleshooting

### Common Issues and Solutions

1. **MCP server connection issues**
  - Verify the syntax in your MCP settings file is correct
  - Ensure you have an active internet connection (needed for npx to fetch the package)
  - Check if any other MCP servers are causing conflicts

2. **Packaging failures**
  - Verify the specified directory or repository exists
  - Check if you have sufficient disk space
  - For remote repositories, ensure you have internet connectivity
  - Try with simpler parameters first, then add complexity

3. **JSON parsing errors in configuration**
  - Make sure your MCP settings file is properly formatted
  - Verify all paths use forward slashes, even on Windows
  - Check for any missing commas or brackets in the configuration

## Additional Information

For more detailed information, visit the [Repomix official documentation](https://repomix.com). You can also join the [Discord community](https://discord.gg/wNYzTwZFku) for support and questions.
</file>

<file path="README.md">
<div align="center" markdown="1">
   <sup>Special thanks to:</sup>
   <br>
   <br>
   <a href="https://www.warp.dev/repomix">
      <img alt="Warp sponsorship" width="400" src="website/client/src/public/images/sponsors/warp/Terminal-Image.png">
   </a>

### [Warp, the agent terminal for developers](https://www.warp.dev/repomix)
[Available for MacOS, Linux, & Windows](https://www.warp.dev/repomix)<br>

</div>

<hr />

<div align="center">
  <a href="https://repomix.com">
    <img src="website/client/src/public/images/repomix-title.png" alt="Repomix" width="500" height="auto" />
  </a>
  <p align="center">
    <b>Pack your codebase into AI-friendly formats</b>
  </p>
</div>

<p align="center">
  <a href="https://repomix.com"><b>Use Repomix online! 👉 repomix.com</b></a><br>
</p>

<p align="center">
  Need discussion? Join us on <a href="https://discord.gg/wNYzTwZFku">Discord</a>!<br>
  <i>Share your experience and tips</i><br>
  <i>Stay updated on new features</i><br>
  <i>Get help with configuration and usage</i><br>
</p>

<hr />

[![npm](https://img.shields.io/npm/v/repomix.svg?maxAge=1000)](https://www.npmjs.com/package/repomix)
[![npm](https://img.shields.io/npm/d18m/repomix)](https://www.npmjs.com/package/repomix)
[![Actions Status](https://github.com/yamadashy/repomix/actions/workflows/ci.yml/badge.svg)](https://github.com/yamadashy/repomix/actions?query=workflow%3A"ci")
[![codecov](https://codecov.io/github/yamadashy/repomix/graph/badge.svg)](https://codecov.io/github/yamadashy/repomix)
[![Sponsors](https://img.shields.io/github/sponsors/yamadashy?logo=github)](https://github.com/sponsors/yamadashy)
[![Discord](https://badgen.net/discord/online-members/wNYzTwZFku?icon=discord&label=discord)](https://discord.gg/wNYzTwZFku)

[![DeepWiki](https://img.shields.io/badge/DeepWiki-yamadashy%2Frepomix-blue.svg?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAAyCAYAAAAnWDnqAAAAAXNSR0IArs4c6QAAA05JREFUaEPtmUtyEzEQhtWTQyQLHNak2AB7ZnyXZMEjXMGeK/AIi+QuHrMnbChYY7MIh8g01fJoopFb0uhhEqqcbWTp06/uv1saEDv4O3n3dV60RfP947Mm9/SQc0ICFQgzfc4CYZoTPAswgSJCCUJUnAAoRHOAUOcATwbmVLWdGoH//PB8mnKqScAhsD0kYP3j/Yt5LPQe2KvcXmGvRHcDnpxfL2zOYJ1mFwrryWTz0advv1Ut4CJgf5uhDuDj5eUcAUoahrdY/56ebRWeraTjMt/00Sh3UDtjgHtQNHwcRGOC98BJEAEymycmYcWwOprTgcB6VZ5JK5TAJ+fXGLBm3FDAmn6oPPjR4rKCAoJCal2eAiQp2x0vxTPB3ALO2CRkwmDy5WohzBDwSEFKRwPbknEggCPB/imwrycgxX2NzoMCHhPkDwqYMr9tRcP5qNrMZHkVnOjRMWwLCcr8ohBVb1OMjxLwGCvjTikrsBOiA6fNyCrm8V1rP93iVPpwaE+gO0SsWmPiXB+jikdf6SizrT5qKasx5j8ABbHpFTx+vFXp9EnYQmLx02h1QTTrl6eDqxLnGjporxl3NL3agEvXdT0WmEost648sQOYAeJS9Q7bfUVoMGnjo4AZdUMQku50McDcMWcBPvr0SzbTAFDfvJqwLzgxwATnCgnp4wDl6Aa+Ax283gghmj+vj7feE2KBBRMW3FzOpLOADl0Isb5587h/U4gGvkt5v60Z1VLG8BhYjbzRwyQZemwAd6cCR5/XFWLYZRIMpX39AR0tjaGGiGzLVyhse5C9RKC6ai42ppWPKiBagOvaYk8lO7DajerabOZP46Lby5wKjw1HCRx7p9sVMOWGzb/vA1hwiWc6jm3MvQDTogQkiqIhJV0nBQBTU+3okKCFDy9WwferkHjtxib7t3xIUQtHxnIwtx4mpg26/HfwVNVDb4oI9RHmx5WGelRVlrtiw43zboCLaxv46AZeB3IlTkwouebTr1y2NjSpHz68WNFjHvupy3q8TFn3Hos2IAk4Ju5dCo8B3wP7VPr/FGaKiG+T+v+TQqIrOqMTL1VdWV1DdmcbO8KXBz6esmYWYKPwDL5b5FA1a0hwapHiom0r/cKaoqr+27/XcrS5UwSMbQAAAABJRU5ErkJggg==)](https://deepwiki.com/yamadashy/repomix)
<!-- DeepWiki badge generated by https://deepwiki.ryoppippi.com/ -->

📦 Repomix is a powerful tool that packs your entire repository into a single, AI-friendly file.  
It is perfect for when you need to feed your codebase to Large Language Models (LLMs) or other AI tools like Claude,
ChatGPT, DeepSeek, Perplexity, Gemini, Gemma, Llama, Grok, and more.

[![Sponsors](https://cdn.jsdelivr.net/gh/yamadashy/sponsor-list/sponsors/sponsors.png)](https://github.com/sponsors/yamadashy)

## 🏆 Open Source Awards Nomination

We're honored! Repomix has been nominated for the **Powered by AI** category at the [JSNation Open Source Awards 2025](https://osawards.com/javascript/).

This wouldn't have been possible without all of you using and supporting Repomix. Thank you!

If Repomix has helped you analyze or pack codebases for AI tools, we'd be grateful for your vote in the **Powered by AI** category.

## 🎉 New: Repomix Website & Discord Community!

- Try Repomix in your browser at [repomix.com](https://repomix.com/)
- Join our [Discord Server](https://discord.gg/wNYzTwZFku) for support and discussion

**We look forward to seeing you there!**

## 🌟 Features

- **AI-Optimized**: Formats your codebase in a way that's easy for AI to understand and process.
- **Token Counting**: Provides token counts for each file and the entire repository, useful for LLM context limits.
- **Simple to Use**: You need just one command to pack your entire repository.
- **Customizable**: Easily configure what to include or exclude.
- **Git-Aware**: Automatically respects your `.gitignore` files and `.git/info/exclude`.
- **Security-Focused**: Incorporates [Secretlint](https://github.com/secretlint/secretlint) for robust security checks to detect and prevent inclusion of sensitive information.
- **Code Compression**: The `--compress` option uses [Tree-sitter](https://github.com/tree-sitter/tree-sitter) to extract key code elements, reducing token count while preserving structure.

## 🚀 Quick Start

### Using the CLI Tool `>_`

You can try Repomix instantly in your project directory without installation:

```bash
npx repomix@latest
```

Or install globally for repeated use:

```bash
# Install using npm
npm install -g repomix

# Alternatively using yarn
yarn global add repomix

# Alternatively using bun
bun add -g repomix

# Alternatively using Homebrew (macOS/Linux)
brew install repomix

# Then run in any project directory
repomix
```

That's it! Repomix will generate a `repomix-output.xml` file in your current directory, containing your entire
repository in an AI-friendly format.

You can then send this file to an AI assistant with a prompt like:

```
This file contains all the files in the repository combined into one.
I want to refactor the code, so please review it first.
```

![Repomix File Usage 1](website/client/src/public/images/docs/repomix-file-usage-1.png)

When you propose specific changes, the AI might be able to generate code accordingly. With features like Claude's
Artifacts, you could potentially output multiple files, allowing for the generation of multiple interdependent pieces of
code.

![Repomix File Usage 2](website/client/src/public/images/docs/repomix-file-usage-2.png)

Happy coding! 🚀

### Using The Website 🌐

Want to try it quickly? Visit the official website at [repomix.com](https://repomix.com). Simply enter your repository
name, fill in any optional details, and click the **Pack** button to see your generated output.

#### Available Options

The website offers several convenient features:

- Customizable output format (XML, Markdown, or Plain Text)
- Instant token count estimation
- Much more!

### Using The Browser Extension 🧩

Get instant access to Repomix directly from any GitHub repository! Our Chrome extension adds a convenient "Repomix" button to GitHub repository pages.

![Repomix Browser Extension](website/client/src/public/images/docs/browser-extension.png)

#### Install
- Chrome Extension: [Repomix - Chrome Web Store](https://chromewebstore.google.com/detail/repomix/fimfamikepjgchehkohedilpdigcpkoa)
- Firefox Add-on: [Repomix - Firefox Add-ons](https://addons.mozilla.org/firefox/addon/repomix/)

#### Features
- One-click access to Repomix for any GitHub repository
- More exciting features coming soon!

### Using The VSCode Extension ⚡️

A community-maintained VSCode extension called [Repomix Runner](https://marketplace.visualstudio.com/items?itemName=DorianMassoulier.repomix-runner) (created by [massdo](https://github.com/massdo)) lets you run Repomix right inside your editor with just a few clicks. Run it on any folder, manage outputs seamlessly, and control everything through VSCode's intuitive interface. 

Want your output as a file or just the content? Need automatic cleanup? This extension has you covered. Plus, it works smoothly with your existing repomix.config.json.

Try it now on the [VSCode Marketplace](https://marketplace.visualstudio.com/items?itemName=DorianMassoulier.repomix-runner)!
Source code is available on [GitHub](https://github.com/massdo/repomix-runner).

### Alternative Tools 🛠️

If you're using Python, you might want to check out `Gitingest`, which is better suited for Python ecosystem and data
science workflows:
https://github.com/cyclotruc/gitingest

## 📊 Usage

To pack your entire repository:

```bash
repomix
```

To pack a specific directory:

```bash
repomix path/to/directory
```

To pack specific files or directories
using [glob patterns](https://github.com/mrmlnc/fast-glob?tab=readme-ov-file#pattern-syntax):

```bash
repomix --include "src/**/*.ts,**/*.md"
```

To exclude specific files or directories:

```bash
repomix --ignore "**/*.log,tmp/"
```

To pack a remote repository:

```bash
repomix --remote https://github.com/yamadashy/repomix

# You can also use GitHub shorthand:
repomix --remote yamadashy/repomix

# You can specify the branch name, tag, or commit hash:
repomix --remote https://github.com/yamadashy/repomix --remote-branch main

# Or use a specific commit hash:
repomix --remote https://github.com/yamadashy/repomix --remote-branch 935b695

# Another convenient way is specifying the branch's URL
repomix --remote https://github.com/yamadashy/repomix/tree/main

# Commit's URL is also supported
repomix --remote https://github.com/yamadashy/repomix/commit/836abcd7335137228ad77feb28655d85712680f1

```

To pack files from a file list (pipe via stdin):

```bash
# Using find command
find src -name "*.ts" -type f | repomix --stdin

# Using git to get tracked files
git ls-files "*.ts" | repomix --stdin

# Using grep to find files containing specific content
grep -l "TODO" **/*.ts | repomix --stdin

# Using ripgrep to find files with specific content
rg -l "TODO|FIXME" --type ts | repomix --stdin

# Using ripgrep (rg) to find files
rg --files --type ts | repomix --stdin

# Using sharkdp/fd to find files
fd -e ts | repomix --stdin

# Using fzf to select from all files
fzf -m | repomix --stdin

# Interactive file selection with fzf
find . -name "*.ts" -type f | fzf -m | repomix --stdin

# Using ls with glob patterns
ls src/**/*.ts | repomix --stdin

# From a file containing file paths
cat file-list.txt | repomix --stdin

# Direct input with echo
echo -e "src/index.ts\nsrc/utils.ts" | repomix --stdin
```

The `--stdin` option allows you to pipe a list of file paths to Repomix, giving you ultimate flexibility in selecting which files to pack.

When using `--stdin`, the specified files are effectively added to the include patterns. This means that the normal include and ignore behavior still applies - files specified via stdin will still be excluded if they match ignore patterns.

> [!NOTE]
> When using `--stdin`, file paths can be relative or absolute, and Repomix will automatically handle path resolution and deduplication.

To compress the output:

```bash
repomix --compress

# You can also use it with remote repositories:
repomix --remote yamadashy/repomix --compress
```

To initialize a new configuration file (`repomix.config.json`):

```bash
repomix --init
```

Once you have generated the packed file, you can use it with Generative AI tools like ChatGPT, DeepSeek, Perplexity, Gemini, Gemma, Llama, Grok, and more.

### Docker Usage 🐳

You can also run Repomix using Docker.  
This is useful if you want to run Repomix in an isolated environment or prefer using containers.

Basic usage (current directory):

```bash
docker run -v .:/app -it --rm ghcr.io/yamadashy/repomix
```

To pack a specific directory:

```bash
docker run -v .:/app -it --rm ghcr.io/yamadashy/repomix path/to/directory
```

Process a remote repository and output to a `output` directory:

```bash
docker run -v ./output:/app -it --rm ghcr.io/yamadashy/repomix --remote https://github.com/yamadashy/repomix
```

### Prompt Examples

Once you have generated the packed file with Repomix, you can use it with AI tools like ChatGPT, DeepSeek, Perplexity, Gemini, Gemma, Llama, Grok, and more.
Here are some example prompts to get you started:

#### Code Review and Refactoring

For a comprehensive code review and refactoring suggestions:

```
This file contains my entire codebase. Please review the overall structure and suggest any improvements or refactoring opportunities, focusing on maintainability and scalability.
```

#### Documentation Generation

To generate project documentation:

```
Based on the codebase in this file, please generate a detailed README.md that includes an overview of the project, its main features, setup instructions, and usage examples.
```

#### Test Case Generation

For generating test cases:

```
Analyze the code in this file and suggest a comprehensive set of unit tests for the main functions and classes. Include edge cases and potential error scenarios.
```

#### Code Quality Assessment

Evaluate code quality and adherence to best practices:

```
Review the codebase for adherence to coding best practices and industry standards. Identify areas where the code could be improved in terms of readability, maintainability, and efficiency. Suggest specific changes to align the code with best practices.
```

#### Library Overview

Get a high-level understanding of the library

```
This file contains the entire codebase of library. Please provide a comprehensive overview of the library, including its main purpose, key features, and overall architecture.
```

Feel free to modify these prompts based on your specific needs and the capabilities of the AI tool you're using.

### Community Discussion

Check out our [community discussion](https://github.com/yamadashy/repomix/discussions/154) where users share:

- Which AI tools they're using with Repomix
- Effective prompts they've discovered
- How Repomix has helped them
- Tips and tricks for getting the most out of AI code analysis

Feel free to join the discussion and share your own experiences! Your insights could help others make better use of
Repomix.

### Output File Format

Repomix generates a single file with clear separators between different parts of your codebase.  
To enhance AI comprehension, the output file begins with an AI-oriented explanation, making it easier for AI models to
understand the context and structure of the packed repository.

#### XML Format (default)

The XML format structures the content in a hierarchical manner:

```xml
This file is a merged representation of the entire codebase, combining all repository files into a single document.

<file_summary>
  (Metadata and usage AI instructions)
</file_summary>

<directory_structure>
src/
cli/
cliOutput.ts
index.ts

(...remaining directories)
</directory_structure>

<files>
<file path="src/index.js">
  // File contents here
</file>

(...remaining files)
</files>

<instruction>
(Custom instructions from `output.instructionFilePath`)
</instruction>
```

For those interested in the potential of XML tags in AI contexts:  
https://docs.anthropic.com/en/docs/build-with-claude/prompt-engineering/use-xml-tags

> When your prompts involve multiple components like context, instructions, and examples, XML tags can be a
> game-changer. They help Claude parse your prompts more accurately, leading to higher-quality outputs.

This means that the XML output from Repomix is not just a different format, but potentially a more effective way to feed
your codebase into AI systems for analysis, code review, or other tasks.

#### Markdown Format

To generate output in Markdown format, use the `--style markdown` option:

```bash
repomix --style markdown
```

The Markdown format structures the content in a hierarchical manner:

````markdown
This file is a merged representation of the entire codebase, combining all repository files into a single document.

# File Summary

(Metadata and usage AI instructions)

# Repository Structure

```
src/
  cli/
    cliOutput.ts
    index.ts
```

(...remaining directories)

# Repository Files

## File: src/index.js

```
// File contents here
```

(...remaining files)

# Instruction

(Custom instructions from `output.instructionFilePath`)
````

This format provides a clean, readable structure that is both human-friendly and easily parseable by AI systems.

#### Plain Text Format

To generate output in plain text format, use the `--style plain` option:

```bash
repomix --style plain
```

```text
This file is a merged representation of the entire codebase, combining all repository files into a single document.

================================================================
File Summary
================================================================
(Metadata and usage AI instructions)

================================================================
Directory Structure
================================================================
src/
  cli/
    cliOutput.ts
    index.ts
  config/
    configLoader.ts

(...remaining directories)

================================================================
Files
================================================================

================
File: src/index.js
================
// File contents here

================
File: src/utils.js
================
// File contents here

(...remaining files)

================================================================
Instruction
================================================================
(Custom instructions from `output.instructionFilePath`)
```

### Command Line Options

#### Basic Options
- `-v, --version`: Show tool version

#### Output Options
- `-o, --output <file>`: Specify the output file name
- `--stdout`: Output to stdout instead of writing to a file (cannot be used with `--output` option)
- `--style <style>`: Specify the output style (`xml`, `markdown`, `plain`)
- `--parsable-style`: Enable parsable output based on the chosen style schema. Note that this can increase token count.
- `--compress`: Perform intelligent code extraction, focusing on essential function and class signatures to reduce token count
- `--output-show-line-numbers`: Show line numbers in the output
- `--copy`: Additionally copy generated output to system clipboard
- `--no-file-summary`: Disable file summary section output
- `--no-directory-structure`: Disable directory structure section output
- `--remove-comments`: Remove comments from supported file types
- `--remove-empty-lines`: Remove empty lines from the output
- `--header-text <text>`: Custom text to include in the file header
- `--instruction-file-path <path>`: Path to a file containing detailed custom instructions
- `--include-empty-directories`: Include empty directories in the output
- `--include-diffs`: Include git diffs in the output (includes both work tree and staged changes separately)
- `--no-git-sort-by-changes`: Disable sorting files by git change count (enabled by default)

#### Filter Options
- `--include <patterns>`: List of include patterns (comma-separated)
- `-i, --ignore <patterns>`: Additional ignore patterns (comma-separated)
- `--stdin`: Read file paths from stdin instead of discovering files automatically
- `--no-gitignore`: Disable .gitignore file usage
- `--no-default-patterns`: Disable default patterns

#### Remote Repository Options
- `--remote <url>`: Process a remote Git repository
- `--remote-branch <name>`: Specify the remote branch name, tag, or commit hash (defaults to repository default branch)

#### Configuration Options
- `-c, --config <path>`: Path to a custom config file
- `--init`: Create config file
- `--global`: Use global config

#### Security Options
- `--no-security-check`: Disable security check

#### Token Count Options
- `--token-count-encoding <encoding>`: Specify token count encoding used by OpenAI's [tiktoken](https://github.com/openai/tiktoken) tokenizer (e.g., `o200k_base` for GPT-4o, `cl100k_base` for GPT-4/3.5). See [tiktoken model.py](https://github.com/openai/tiktoken/blob/main/tiktoken/model.py#L24) for encoding details.

#### MCP
- `--mcp`: Run as a [MCP (Model Context Protocol)](https://modelcontextprotocol.io) server

#### Other Options
- `--top-files-len <number>`: Number of top files to display in the summary
- `--verbose`: Enable verbose logging
- `--quiet`: Disable all output to stdout

Examples:

```bash
# Basic usage
repomix

# Custom output
repomix -o output.xml --style xml

# Output to stdout
repomix --stdout > custom-output.txt

# Send output to stdout, then pipe into another command (for example, simonw/llm)
repomix --stdout | llm "Please explain what this code does."

# Custom output with compression
repomix --compress

# Process specific files
repomix --include "src/**/*.ts" --ignore "**/*.test.ts"

# Remote repository with branch
repomix --remote https://github.com/user/repo/tree/main

# Remote repository with commit
repomix --remote https://github.com/user/repo/commit/836abcd7335137228ad77feb28655d85712680f1

# Remote repository with shorthand
repomix --remote user/repo
```

### Updating Repomix

To update a globally installed Repomix:

```bash
# Using npm
npm update -g repomix

# Using yarn
yarn global upgrade repomix

# Using bun
bun update -g repomix
```

Using `npx repomix` is generally more convenient as it always uses the latest version.

### Remote Repository Processing

Repomix supports processing remote Git repositories without the need for manual cloning. This feature allows you to
quickly analyze any public Git repository with a single command.

To process a remote repository, use the `--remote` option followed by the repository URL:

```bash
repomix --remote https://github.com/yamadashy/repomix
```

You can also use GitHub's shorthand format:

```bash
repomix --remote yamadashy/repomix
```

You can specify the branch name, tag, or commit hash:

```bash
# Using --remote-branch option
repomix --remote https://github.com/yamadashy/repomix --remote-branch main

# Using branch's URL
repomix --remote https://github.com/yamadashy/repomix/tree/main
```

Or use a specific commit hash:

```bash
# Using --remote-branch option
repomix --remote https://github.com/yamadashy/repomix --remote-branch 935b695

# Using commit's URL
repomix --remote https://github.com/yamadashy/repomix/commit/836abcd7335137228ad77feb28655d85712680f1
```

### Code Compression

The `--compress` option utilizes [Tree-sitter](https://github.com/tree-sitter/tree-sitter) to perform intelligent code extraction, focusing on essential function and class signatures while removing implementation details. This can help reduce token count while retaining important structural information.

```bash
repomix --compress
```

For example, this code:

```typescript
import { ShoppingItem } from './shopping-item';

/**
 * Calculate the total price of shopping items
 */
const calculateTotal = (
  items: ShoppingItem[]
) => {
  let total = 0;
  for (const item of items) {
    total += item.price * item.quantity;
  }
  return total;
}

// Shopping item interface
interface Item {
  name: string;
  price: number;
  quantity: number;
}
```

Will be compressed to:

```typescript
import { ShoppingItem } from './shopping-item';
⋮----
/**
 * Calculate the total price of shopping items
 */
const calculateTotal = (
  items: ShoppingItem[]
) => {
⋮----
// Shopping item interface
interface Item {
  name: string;
  price: number;
  quantity: number;
}
```

> [!NOTE]
> This is an experimental feature that we'll be actively improving based on user feedback and real-world usage

### MCP Server Integration

Repomix supports the [Model Context Protocol (MCP)](https://modelcontextprotocol.io), allowing AI assistants to directly interact with your codebase. When run as an MCP server, Repomix provides tools that enable AI assistants to package local or remote repositories for analysis without requiring manual file preparation.

```bash
repomix --mcp
```

#### Configuring MCP Servers

To use Repomix as an MCP server with AI assistants like Claude, you need to configure the MCP settings:

**For VS Code:**

You can install the Repomix MCP server in VS Code using one of these methods:

1. **Using the Install Badge:**

  [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install_Server-0098FF?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=repomix&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22repomix%22%2C%22--mcp%22%5D%7D)
  [![Install in VS Code Insiders](https://img.shields.io/badge/VS_Code_Insiders-Install_Server-24bfa5?style=flat-square&logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=repomix&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22repomix%22%2C%22--mcp%22%5D%7D&quality=insiders)

2. **Using the Command Line:**

  ```bash
  code --add-mcp '{"name":"repomix","command":"npx","args":["-y","repomix","--mcp"]}'
  ```

  For VS Code Insiders:
  ```bash
  code-insiders --add-mcp '{"name":"repomix","command":"npx","args":["-y","repomix","--mcp"]}'
  ```

**For Cline (VS Code extension):**

Edit the `cline_mcp_settings.json` file:
```json
{
  "mcpServers": {
    "repomix": {
      "command": "npx",
      "args": [
        "-y",
        "repomix",
        "--mcp"
      ]
    }
  }
}
```

**For Cursor:**

In Cursor, add a new MCP server from `Cursor Settings` > `MCP` > `+ Add new global MCP server` with a configuration similar to Cline.

**For Claude Desktop:**

Edit the `claude_desktop_config.json` file with similar configuration to Cline's config.

**For Claude Code:**

To configure Repomix as an MCP server in [Claude Code](https://docs.anthropic.com/en/docs/claude-code/overview), use the following command:

```bash
claude mcp add repomix -- npx -y repomix --mcp
```

**Using Docker instead of npx:**

You can use Docker as an alternative to npx for running Repomix as an MCP server:

```json
{
  "mcpServers": {
    "repomix-docker": {
      "command": "docker",
      "args": [
        "run",
        "-i",
        "--rm",
        "ghcr.io/yamadashy/repomix",
        "--mcp"
      ]
    }
  }
}
```

Once configured, your AI assistant can directly use Repomix's capabilities to analyze codebases without manual file preparation, making code analysis workflows more efficient.

#### Available MCP Tools

When running as an MCP server, Repomix provides the following tools:

1. **pack_codebase**: Package a local code directory into a consolidated XML file for AI analysis
  - Parameters:
    - `directory`: Absolute path to the directory to pack
    - `compress`: (Optional, default: false) Enable Tree-sitter compression to extract essential code signatures and structure while removing implementation details. Reduces token usage by ~70% while preserving semantic meaning. Generally not needed since grep_repomix_output allows incremental content retrieval. Use only when you specifically need the entire codebase content for large repositories.
    - `includePatterns`: (Optional) Specify files to include using fast-glob patterns. Multiple patterns can be comma-separated (e.g., "**/*.{js,ts}", "src/**,docs/**"). Only matching files will be processed.
    - `ignorePatterns`: (Optional) Specify additional files to exclude using fast-glob patterns. Multiple patterns can be comma-separated (e.g., "test/**,*.spec.js", "node_modules/**,dist/**"). These patterns supplement .gitignore and built-in exclusions.
    - `topFilesLength`: (Optional, default: 10) Number of largest files by size to display in the metrics summary for codebase analysis.

2. **pack_remote_repository**: Fetch, clone, and package a GitHub repository into a consolidated XML file for AI analysis
  - Parameters:
    - `remote`: GitHub repository URL or user/repo format (e.g., "yamadashy/repomix", "https://github.com/user/repo", or "https://github.com/user/repo/tree/branch")
    - `compress`: (Optional, default: false) Enable Tree-sitter compression to extract essential code signatures and structure while removing implementation details. Reduces token usage by ~70% while preserving semantic meaning. Generally not needed since grep_repomix_output allows incremental content retrieval. Use only when you specifically need the entire codebase content for large repositories.
    - `includePatterns`: (Optional) Specify files to include using fast-glob patterns. Multiple patterns can be comma-separated (e.g., "**/*.{js,ts}", "src/**,docs/**"). Only matching files will be processed.
    - `ignorePatterns`: (Optional) Specify additional files to exclude using fast-glob patterns. Multiple patterns can be comma-separated (e.g., "test/**,*.spec.js", "node_modules/**,dist/**"). These patterns supplement .gitignore and built-in exclusions.
    - `topFilesLength`: (Optional, default: 10) Number of largest files by size to display in the metrics summary for codebase analysis.

3. **read_repomix_output**: Read the contents of a Repomix-generated output file. Supports partial reading with line range specification for large files.
  - Parameters:
    - `outputId`: ID of the Repomix output file to read
    - `startLine`: (Optional) Starting line number (1-based, inclusive). If not specified, reads from beginning.
    - `endLine`: (Optional) Ending line number (1-based, inclusive). If not specified, reads to end.
  - Features:
    - Specifically designed for web-based environments or sandboxed applications
    - Retrieves the content of previously generated outputs using their ID
    - Provides secure access to packed codebase without requiring file system access
    - Supports partial reading for large files

4. **grep_repomix_output**: Search for patterns in a Repomix output file using grep-like functionality with JavaScript RegExp syntax
  - Parameters:
    - `outputId`: ID of the Repomix output file to search
    - `pattern`: Search pattern (JavaScript RegExp regular expression syntax)
    - `contextLines`: (Optional, default: 0) Number of context lines to show before and after each match. Overridden by beforeLines/afterLines if specified.
    - `beforeLines`: (Optional) Number of context lines to show before each match (like grep -B). Takes precedence over contextLines.
    - `afterLines`: (Optional) Number of context lines to show after each match (like grep -A). Takes precedence over contextLines.
    - `ignoreCase`: (Optional, default: false) Perform case-insensitive matching
  - Features:
    - Uses JavaScript RegExp syntax for powerful pattern matching
    - Supports context lines for better understanding of matches
    - Allows separate control of before/after context lines
    - Case-sensitive and case-insensitive search options

5. **file_system_read_file**: Read a file from the local file system using an absolute path. Includes built-in security validation to detect and prevent access to files containing sensitive information.
  - Parameters:
    - `path`: Absolute path to the file to read
  - Security features:
    - Implements security validation using [Secretlint](https://github.com/secretlint/secretlint)
    - Prevents access to files containing sensitive information (API keys, passwords, secrets)
    - Validates absolute paths to prevent directory traversal attacks

6. **file_system_read_directory**: List the contents of a directory using an absolute path. Returns a formatted list showing files and subdirectories with clear indicators.
  - Parameters:
    - `path`: Absolute path to the directory to list
  - Features:
    - Shows files and directories with clear indicators (`[FILE]` or `[DIR]`)
    - Provides safe directory traversal with proper error handling
    - Validates paths and ensures they are absolute
    - Useful for exploring project structure and understanding codebase organization

## ⚙️ Configuration

Create a `repomix.config.json` file in your project root for custom configurations.

```bash
repomix --init
```

Here's an explanation of the configuration options:

| Option                           | Description                                                                                                                  | Default                |
|----------------------------------|------------------------------------------------------------------------------------------------------------------------------|------------------------|
| `input.maxFileSize`              | Maximum file size in bytes to process. Files larger than this will be skipped                                                | `50000000`            |
| `output.filePath`                | The name of the output file                                                                                                  | `"repomix-output.xml"` |
| `output.style`                   | The style of the output (`xml`, `markdown`, `plain`)                                                                         | `"xml"`                |
| `output.parsableStyle`           | Whether to escape the output based on the chosen style schema. Note that this can increase token count.                      | `false`                |
| `output.compress`                | Whether to perform intelligent code extraction to reduce token count                                                         | `false`                |
| `output.headerText`              | Custom text to include in the file header                                                                                    | `null`                 |
| `output.instructionFilePath`     | Path to a file containing detailed custom instructions                                                                       | `null`                 |
| `output.fileSummary`             | Whether to include a summary section at the beginning of the output                                                          | `true`                 |
| `output.directoryStructure`      | Whether to include the directory structure in the output                                                                     | `true`                 |
| `output.files`                   | Whether to include file contents in the output                                                                               | `true`                 |
| `output.removeComments`          | Whether to remove comments from supported file types                                                                         | `false`                |
| `output.removeEmptyLines`        | Whether to remove empty lines from the output                                                                                | `false`                |
| `output.showLineNumbers`         | Whether to add line numbers to each line in the output                                                                       | `false`                |
| `output.copyToClipboard`         | Whether to copy the output to system clipboard in addition to saving the file                                                | `false`                |
| `output.topFilesLength`          | Number of top files to display in the summary. If set to 0, no summary will be displayed                                     | `5`                    |
| `output.includeEmptyDirectories` | Whether to include empty directories in the repository structure                                                             | `false`                |
| `output.git.sortByChanges`       | Whether to sort files by git change count (files with more changes appear at the bottom)                                     | `true`                 |
| `output.git.sortByChangesMaxCommits` | Maximum number of commits to analyze for git changes                                                                     | `100`                  |
| `output.git.includeDiffs`       | Whether to include git diffs in the output (includes both work tree and staged changes separately)                          | `false`                |
| `include`                        | Patterns of files to include (using [glob patterns](https://github.com/mrmlnc/fast-glob?tab=readme-ov-file#pattern-syntax))  | `[]`                   |
| `ignore.useGitignore`            | Whether to use patterns from the project's `.gitignore` file                                                                 | `true`                 |
| `ignore.useDefaultPatterns`      | Whether to use default ignore patterns                                                                                       | `true`                 |
| `ignore.customPatterns`          | Additional patterns to ignore (using [glob patterns](https://github.com/mrmlnc/fast-glob?tab=readme-ov-file#pattern-syntax)) | `[]`                   |
| `security.enableSecurityCheck`   | Whether to perform security checks on files                                                                                  | `true`                 |
| `tokenCount.encoding`            | Token count encoding used by OpenAI's [tiktoken](https://github.com/openai/tiktoken) tokenizer (e.g., `o200k_base` for GPT-4o, `cl100k_base` for GPT-4/3.5). See [tiktoken model.py](https://github.com/openai/tiktoken/blob/main/tiktoken/model.py#L24) for encoding details. | `"o200k_base"`         |

The configuration file supports [JSON5](https://json5.org/) syntax, which allows:
- Comments (both single-line and multi-line)
- Trailing commas in objects and arrays
- Unquoted property names
- More relaxed string syntax

Example configuration:

```json5
{
  "input": {
    "maxFileSize": 50000000
  },
  "output": {
    "filePath": "repomix-output.xml",
    "style": "xml",
    "parsableStyle": false,
    "compress": false,
    "headerText": "Custom header information for the packed file.",
    "fileSummary": true,
    "directoryStructure": true,
    "files": true,
    "removeComments": false,
    "removeEmptyLines": false,
    "topFilesLength": 5,
    "showLineNumbers": false,
    "copyToClipboard": false,
    "includeEmptyDirectories": false,
    "git": {
      "sortByChanges": true,
      "sortByChangesMaxCommits": 100,
      "includeDiffs": false
    }
  },
  "include": ["**/*"],
  "ignore": {
    "useGitignore": true,
    "useDefaultPatterns": true,
    // Patterns can also be specified in .repomixignore
    "customPatterns": [
      "additional-folder",
      "**/*.log"
    ],
  },
  "security": {
    "enableSecurityCheck": true
  },
  "tokenCount": {
    "encoding": "o200k_base"
  }
}
```

### Global Configuration

To create a global configuration file:

```bash
repomix --init --global
```

The global configuration file will be created in:

- Windows: `%LOCALAPPDATA%\Repomix\repomix.config.json`
- macOS/Linux: `$XDG_CONFIG_HOME/repomix/repomix.config.json` or `~/.config/repomix/repomix.config.json`

Note: Local configuration (if present) takes precedence over global configuration.

### Include and Ignore

#### Include Patterns

Repomix now supports specifying files to include
using [glob patterns](https://github.com/mrmlnc/fast-glob?tab=readme-ov-file#pattern-syntax). This allows for more
flexible and powerful file selection:

- Use `**/*.js` to include all JavaScript files in any directory
- Use `src/**/*` to include all files within the `src` directory and its subdirectories
- Combine multiple patterns like `["src/**/*.js", "**/*.md"]` to include JavaScript files in `src` and all Markdown
  files

#### Ignore Patterns

Repomix offers multiple methods to set ignore patterns for excluding specific files or directories during the packing
process:

- **.gitignore**: By default, patterns listed in your project's `.gitignore` files and `.git/info/exclude` are used. This behavior can be controlled with the `ignore.useGitignore` setting or the `--no-gitignore` cli option.
- **Default patterns**: Repomix includes a default list of commonly excluded files and directories (e.g., node_modules,
  .git, binary files). This feature can be controlled with the `ignore.useDefaultPatterns` setting or the `--no-default-patterns` cli option. Please
  see [defaultIgnore.ts](src/config/defaultIgnore.ts) for more details.
- **.repomixignore**: You can create a `.repomixignore` file in your project root to define Repomix-specific ignore
  patterns. This file follows the same format as `.gitignore`.
- **Custom patterns**: Additional ignore patterns can be specified using the `ignore.customPatterns` option in the
  configuration file. You can overwrite this setting with the `-i, --ignore` command line option.

Priority Order (from highest to lowest):

1. Custom patterns `ignore.customPatterns`
2. `.repomixignore`
3. `.gitignore` and `.git/info/exclude` (if `ignore.useGitignore` is true and `--no-gitignore` is not used)
4. Default patterns (if `ignore.useDefaultPatterns` is true and `--no-default-patterns` is not used)

This approach allows for flexible file exclusion configuration based on your project's needs. It helps optimize the size
of the generated pack file by ensuring the exclusion of security-sensitive files and large binary files, while
preventing the leakage of confidential information.

Note: Binary files are not included in the packed output by default, but their paths are listed in the "Repository
Structure" section of the output file. This provides a complete overview of the repository structure while keeping the
packed file efficient and text-based.

### Custom Instruction

The `output.instructionFilePath` option allows you to specify a separate file containing detailed instructions or
context about your project. This allows AI systems to understand the specific context and requirements of your project,
potentially leading to more relevant and tailored analysis or suggestions.

Here's an example of how you might use this feature:

1. Create a file named `repomix-instruction.md` in your project root:

```markdown
# Coding Guidelines

- Follow the Airbnb JavaScript Style Guide
- Suggest splitting files into smaller, focused units when appropriate
- Add comments for non-obvious logic. Keep all text in English
- All new features should have corresponding unit tests

# Generate Comprehensive Output

- Include all content without abbreviation, unless specified otherwise
- Optimize for handling large codebases while maintaining output quality
```

2. In your `repomix.config.json`, add the `instructionFilePath` option:

```json5
{
  "output": {
    "instructionFilePath": "repomix-instruction.md",
    // other options...
  }
}
```

When Repomix generates the output, it will include the contents of `repomix-instruction.md` in a dedicated section.

Note: The instruction content is appended at the end of the output file. This placement can be particularly effective
for AI systems. For those interested in understanding why this might be beneficial, Anthropic provides some insights in
their documentation:  
https://docs.anthropic.com/en/docs/build-with-claude/prompt-engineering/long-context-tips

> Put long-form data at the top: Place your long documents and inputs (~20K+ tokens) near the top of your prompt, above
> your query, instructions, and examples. This can significantly improve Claude's performance across all models.
> Queries at the end can improve response quality by up to 30% in tests, especially with complex, multi-document inputs.

### Comment Removal

When `output.removeComments` is set to `true`, Repomix will attempt to remove comments from supported file types. This
feature can help reduce the size of the output file and focus on the essential code content.

Supported languages include:  
HTML, CSS, JavaScript, TypeScript, Vue, Svelte, Python, PHP, Ruby, C, C#, Java, Go, Rust, Swift, Kotlin, Dart, Shell,
and YAML.

Note: The comment removal process is conservative to avoid accidentally removing code. In complex cases, some comments
might be retained.

## 🔍 Security Check

Repomix includes a security check feature that uses [Secretlint](https://github.com/secretlint/secretlint) to detect
potentially sensitive information in your files. This feature helps you identify possible security risks before sharing
your packed repository.

The security check results will be displayed in the CLI output after the packing process is complete. If any suspicious
files are detected, you'll see a list of these files along with a warning message.

Example output:

```
🔍 Security Check:
──────────────────
2 suspicious file(s) detected:
1. src/utils/test.txt
2. tests/utils/secretLintUtils.test.ts

Please review these files for potentially sensitive information.
```

By default, Repomix's security check feature is enabled. You can disable it by setting `security.enableSecurityCheck` to
`false` in your configuration file:

```json
{
  "security": {
    "enableSecurityCheck": false
  }
}
```

Or using the `--no-security-check` command line option:

```bash
repomix --no-security-check
```

> [!NOTE]
> Disabling security checks may expose sensitive information. Use this option with caution and only when necessary, such
> as when working with test files or documentation that contains example credentials.

## 🤖 Using Repomix with GitHub Actions

You can also use Repomix in your GitHub Actions workflows. This is useful for automating the process of packing your codebase for AI analysis.

Basic usage:

```yaml
- name: Pack repository with Repomix
  uses: yamadashy/repomix/.github/actions/repomix@main
  with:
    output: repomix-output.xml
    style: xml
```

Use `--style` to generate output in different formats:

```yaml
- name: Pack repository with Repomix
  uses: yamadashy/repomix/.github/actions/repomix@main
  with:
    output: repomix-output.md
    style: markdown
```

Pack specific directories with compression:

```yaml
- name: Pack repository with Repomix
  uses: yamadashy/repomix/.github/actions/repomix@main
  with:
    directories: src tests
    include: "**/*.ts,**/*.md"
    ignore: "**/*.test.ts"
    output: repomix-output.txt
    compress: true
```

Upload the output file as an artifact:

```yaml
- name: Pack repository with Repomix
  uses: yamadashy/repomix/.github/actions/repomix@main
  with:
    directories: src
    output: repomix-output.txt
    compress: true

- name: Upload Repomix output
  uses: actions/upload-artifact@v4
  with:
    name: repomix-output
    path: repomix-output.txt
```

Complete workflow example:

```yaml
name: Pack repository with Repomix

on:
  workflow_dispatch:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  pack-repo:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Pack repository with Repomix
        uses: yamadashy/repomix/.github/actions/repomix@main
        with:
          output: repomix-output.xml

      - name: Upload Repomix output
        uses: actions/upload-artifact@v4
        with:
          name: repomix-output.xml
          path: repomix-output.xml
          retention-days: 30
```

See the complete workflow example [here](https://github.com/yamadashy/repomix/blob/main/.github/workflows/pack-repository.yml).

### Action Inputs

| Name | Description | Default |
|------|-------------|---------|
| `directories` | Space-separated list of directories to process (e.g., `src tests docs`) | `.` |
| `include` | Comma-separated glob patterns to include files (e.g., `**/*.ts,**/*.md`) | `""` |
| `ignore` | Comma-separated glob patterns to ignore files (e.g., `**/*.test.ts,**/node_modules/**`) | `""` |
| `output` | Relative path for the packed file (extension determines format: `.txt`, `.md`, `.xml`) | `repomix-output.xml` |
| `compress` | Enable smart compression to reduce output size by pruning implementation details | `true` |
| `style` | Output style (`xml`, `markdown`, `plain`) | `xml` |
| `additional-args` | Extra raw arguments for the repomix CLI (e.g., `--no-file-summary --no-security-check`) | `""` |
| `repomix-version` | Version of the npm package to install (supports semver ranges, tags, or specific versions like `0.2.25`) | `latest` |

### Action Outputs

| Name | Description |
|------|-------------|
| `output_file` | Path to the generated output file. Can be used in subsequent steps for artifact upload, LLM processing, or other operations. The file contains a formatted representation of your codebase based on the specified options. |

## 📚 Using Repomix as a Library

In addition to using Repomix as a CLI tool, you can also use it as a library in your Node.js applications.

### Installation

```bash
npm install repomix
```

### Basic Usage

```javascript
import { runCli, type CliOptions } from 'repomix';

// Process current directory with custom options
async function packProject() {
  const options = {
    output: 'output.xml',
    style: 'xml',
    compress: true,
    quiet: true
  } as CliOptions;
  
  const result = await runCli(['.'], process.cwd(), options);
  return result.packResult;
}
```

### Process Remote Repository

```javascript
import { runCli, type CliOptions } from 'repomix';

// Clone and process a GitHub repo
async function processRemoteRepo(repoUrl) {
  const options = {
    remote: repoUrl,
    output: 'output.xml',
    compress: true
  } as CliOptions;
  
  return await runCli(['.'], process.cwd(), options);
}
```

### Using Core Components

If you need more control, you can use the low-level APIs:

```javascript
import { searchFiles, collectFiles, processFiles, TokenCounter } from 'repomix';

async function analyzeFiles(directory) {
  // Find and collect files
  const { filePaths } = await searchFiles(directory, { /* config */ });
  const rawFiles = await collectFiles(filePaths, directory);
  const processedFiles = await processFiles(rawFiles, { /* config */ });
  
  // Count tokens
  const tokenCounter = new TokenCounter('o200k_base');
  
  // Return analysis results
  return processedFiles.map(file => ({
    path: file.path,
    tokens: tokenCounter.countTokens(file.content)
  }));
}
```

For more examples, check the source code at [website/server/src/remoteRepo.ts](https://github.com/yamadashy/repomix/blob/main/website/server/src/remoteRepo.ts) which demonstrates how repomix.com uses the library.

## 🤝 Contribution

We welcome contributions from the community! To get started, please refer to our [Contributing Guide](CONTRIBUTING.md).

### Contributors

<a href="https://github.com/yamadashy/repomix/graphs/contributors">
  <img alt="contributors" src="https://contrib.rocks/image?repo=yamadashy/repomix"/>
</a>

## 🔒 Privacy Policy

### Repomix CLI Tool

- **Data Collection**: The Repomix CLI tool does **not** collect, transmit, or store any user data, telemetry, or repository information.
- **Network Usage**: Repomix CLI operates fully offline after installation. The only cases where an internet connection is needed are:
  - Installation via npm/yarn.
  - Using the `--remote` flag to process remote repositories.
  - Checking for updates (manually triggered).
- **Security Considerations**: Since all processing is local, Repomix CLI is safe to use with private and internal repositories.

### Repomix Website ([repomix.com](https://repomix.com/))

- **Data Collection**: The Repomix website uses **Google Analytics** to collect usage data, such as page views and user interactions. This helps us understand how the website is used and improve the user experience.
- **File Processing**: When uploading ZIP files or folders, your files are temporarily stored on our servers for processing. All uploaded files and processed data are automatically deleted immediately after processing is complete.

### Repomix Browser Extension

- **Data Collection**: The Repomix browser extension does **not** collect, transmit, or store any user data, telemetry, or repository information.
- **Permissions**: The extension only requires minimal permissions necessary to add the Repomix button to GitHub repository pages. It does not access or modify repository data.

### Liability Disclaimer

Repomix (the CLI tool, website, and browser extension) is provided "as is" without any warranties or guarantees.  
We do not take responsibility for how the generated output is used, including but not limited to its accuracy, legality, or any potential consequences arising from its use.

## 📜 License

This project is licensed under the [MIT License](LICENSE).

<p align="center">
  &nbsp;&nbsp;&nbsp;
  <a href="#repo-content-pjax-container" target="_blank">
    Back To Top
  </a>
</p>
</file>

<file path="repomix-instruction.md">
# Repomix Project Structure and Overview

This document provides a structural overview of the Repomix project, designed to aid AI code assistants (like Copilot) in understanding the codebase.

Please refer to `README.md` for a complete and up-to-date project overview, and `CONTRIBUTING.md` for implementation guidelines and contribution procedures.

## Project Overview

Repomix is a tool that packs the contents of a software repository into a single file, making it easier for AI systems to analyze and process the codebase. It supports various output formats (plain text, XML, Markdown), ignores files based on configurable patterns, and performs security checks to exclude potentially sensitive information.

## Directory Structure

The project is organized into the following directories:

```
repomix/
├── src/ # Main source code
   ├── cli/ # Command-line interface logic (argument parsing, command handling, output)
   ├── config/ # Configuration loading, schema, and defaults
   ├── core/ # Core logic of Repomix
      ├── file/ # File handling (reading, processing, searching, tree structure generation, git commands)
      ├── metrics/ # Calculating code metrics (character count, token count)
      ├── output/ # Output generation (different styles, headers, etc.)
      ├── packager/ # Orchestrates file collection, processing, output, and clipboard operations.
      ├── security/ # Security checks to exclude sensitive files
      ├── tokenCount/ # Token counting using Tiktoken
      └── tree-sitter/ # Code parsing using Tree-sitter and language-specific queries
   └── shared/ # Shared utilities and types (error handling, logging, helper functions)
├── tests/ # Unit and integration tests (organized mirroring src/)
   ├── cli/
   ├── config/
   ├── core/
   ├── integration-tests/
   ├── shared/
   └── testing/
└── website/ # Documentation website (VitePress)
    ├── client/      # Client-side code (Vue.js components, styles, configuration)
       ├── .vitepress/  # VitePress configuration and theme
          ├── config/  # Site configuration files (navigation, sidebar, etc.)
          └── theme/   # Custom theme and styles
       ├── components/ # Vue.js components for the website
       └── src/        # Markdown files for the documentation in various languages (en, ja, etc.)
    └── server/      # Server-side API (for remote repository processing)
        └── src/       # Server source code (API endpoints, request handling)
```

----------------------------------------------------------------

# Coding Guidelines
- Follow the Airbnb JavaScript Style Guide.
- Split files into smaller, focused units when appropriate:
  - Aim to keep code files under 250 lines. If a file exceeds 250 lines, split it into multiple files based on functionality.
- Add comments to clarify non-obvious logic. **Ensure all comments are written in English.**
- Provide corresponding unit tests for all new features.
- After implementation, verify changes by running:
  ```bash
  npm run lint  # Ensure code style compliance
  npm run test  # Verify all tests pass
  ```

## Dependencies and Testing
- Inject dependencies through a deps object parameter for testability
- Example:
  ```typescript
  export const functionName = async (
    param1: Type1,
    param2: Type2,
    deps = {
      defaultFunction1,
      defaultFunction2,
    }
  ) => {
    // Use deps.defaultFunction1() instead of direct call
  };
  ```
- Mock dependencies by passing test doubles through deps object
- Use vi.mock() only when dependency injection is not feasible

## Generate Comprehensive Output
- Include all content without abbreviation, unless specified otherwise
- Optimize for handling large codebases while maintaining output quality

----------------------------------------------------------------

# GitHub Release Note Guidelines
When writing release notes, please follow these guidelines:

- When referencing issues or PRs, use the gh command to verify the content:
  ```bash
  gh issue view <issue-number>  # For checking issue content
  gh pr view <pr-number>        # For checking PR content
  ```
  This helps ensure accuracy in release note descriptions.

Here are some examples of release notes that follow the guidelines:

v0.2.25
````md
This release brings significant improvements to output formatting and introduces flexible remote repository handling capabilities along with enhanced logging features.

# Improvements ⚡

## Remote Repository Enhancement (#335)
- Added branch/tag parsing directly from repository URLs:
```bash
repomix --remote https://github.com/yamadashy/repomix/tree/0.1.x
```
Functions identically to:
```bash
repomix --remote https://github.com/yamadashy/repomix --remote-branch 0.1.x
```

Special thanks to @huy-trn for implementing this user-friendly feature!

## Enhanced Output Formatting (#328, #329, #330)
- Added "End of Codebase" marker for better clarity in output
- Improved output header accuracy:
  - Better representation of codebase scope
  - Clear indication when using `--include` or `--ignore` options

Special thanks to @gitkenan for adding the "End of Codebase" marker and reporting the header issue!

## Path Pattern Support (#337)
- Added support for special characters in paths:
  - Handles parentheses in include patterns (e.g., `src/(categories)/**/*`)
  - Improved escaping for `[]` and `{}`
  - Essential for Next.js route groups and similar frameworks

Thank you @matheuscoelhomalta for improving path pattern support!

# How to Update

```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
````

v0.2.24
````md
This release significantly enhances configuration flexibility with comprehensive CLI flag support and expands default ignore patterns for better project scaffolding. 

# What's New 🚀

## CLI Flags Revolution (#324)
- New command-line configuration now available.

```
- `--no-gitignore`: Disable .gitignore file usage
- `--no-default-patterns`: Disable default patterns
- `--header-text <text>`: Custom text to include in the file header
- `--instruction-file-path <path>`: Path to a file containing detailed custom instructions
- `--include-empty-directories`: Include empty directories in the output
```

Special recognition to @massdo for driving ecosystem growth.

# Improvements ⚡

## Enhanced Ignore Patterns (#318, #322)
- Expanded default ignores for Rust projects:
  - `target/`, `Cargo.lock`, build artifacts
  - PHP, Ruby, Go, Elixir, Haskell: package manager lock files

To @boralg for helping curate Rust-specific patterns!

# How to Update
```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
````

v0.2.23
````md
This release adds significant performance improvements for large repositories, making Repomix faster and more efficient when needed.

# Improvements ⚡

## Parallel Processing Enhancement (#309)
- Implemented worker threads using [Piscina](https://github.com/piscinajs/piscina) for parallel processing

### Benchmark Results
- `yamadashy.repomix`: No significant change
  - Before: 868.73 millis
  - After: 671.26 millis
- `facebook/react`: 29x faster
  - Before: 123.31 secs
  - After: 4.19 secs
- `vercel/next.js`: 58x faster
  - Before: 17.85 mins
  - After: 17.27 secs

Note: While Repomix is not primarily designed for processing large repositories, and speed is not a primary goal, faster processing can provide a better user experience when working with larger codebases.

# How to Update

```bash
npm update -g repomix
```


---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
````

v0.2.22
````md
This release introduces significant improvements to large file handling and expands the Repomix ecosystem with new tools and community channels.

# Improvements ⚡ 

## Improved Large File Handling (#302)

- Added a file size limit check (50MB) to prevent memory issues
- Graceful error handling for large files with clear user guidance:

Special thanks to @slavashvets for their continued contributions!

# Ecosystem Growth 🤝 

## New VS Code Extension (#300)
A community-created VS Code extension "Repomix Runner" is now available:
- Run Repomix directly from VS Code
- Extension by @massdo: [View on VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=DorianMassoulier.repomix-runner)

Thank you @massdo for bringing Repomix to VS Code and expanding our tooling ecosystem!

## Official Social Media
- Launched official Repomix X (Twitter) account: [@repomix_ai](https://x.com/repomix_ai)
  - Follow for updates, tips, and community highlights

# How to Update

```bash
npm update -g repomix
```

---

Join our growing community on [Discord](https://discord.gg/BF8GxZHE2C) and follow us on [X](https://x.com/repomix_ai) for updates!
````

v0.2.21
````md
This release introduces significant improvements to output formatting and documentation, featuring a new parsable style option for enhanced XML handling.

# What's New 🚀 

## Enhanced Output Style Control (#287)
- Added new `parsableStyle` option for better output handling:
  - Ensures output strictly follows the specification of the chosen format
  - Provides properly escaped XML output with fast-xml-parser
  - Dynamically adjusts markdown code block delimiters to avoid content conflicts
- Available via CLI flag `--parsable-style` or in configuration file

Special thanks to @atollk for their first contribution!

# Documentation 📚

## README Enhancements (#296)
- Updated Homebrew installation documentation to include Linux support

Special thanks to @chenrui333 for their continued contributions!

## Website Multi-Language Support (#293)
- Enhanced multi-language support in [repomix.com](https://repomix.com)

# How to Update

To update to the latest version, run:
```bash
npm update -g repomix
```


---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
</file>

<file path="SECURITY.md">
# Security Policy

## Reporting a Vulnerability

To securely report a vulnerability, please [open an advisory on GitHub](https://github.com/yamadashy/repomix/security/advisories/new) or report it by sending an email to `[email protected]`.
</file>

</files>


<instruction>
# Repomix Project Structure and Overview

This document provides a structural overview of the Repomix project, designed to aid AI code assistants (like Copilot) in understanding the codebase.

Please refer to `README.md` for a complete and up-to-date project overview, and `CONTRIBUTING.md` for implementation guidelines and contribution procedures.

## Project Overview

Repomix is a tool that packs the contents of a software repository into a single file, making it easier for AI systems to analyze and process the codebase. It supports various output formats (plain text, XML, Markdown), ignores files based on configurable patterns, and performs security checks to exclude potentially sensitive information.

## Directory Structure

The project is organized into the following directories:

```
repomix/
├── src/ # Main source code
   ├── cli/ # Command-line interface logic (argument parsing, command handling, output)
   ├── config/ # Configuration loading, schema, and defaults
   ├── core/ # Core logic of Repomix
      ├── file/ # File handling (reading, processing, searching, tree structure generation, git commands)
      ├── metrics/ # Calculating code metrics (character count, token count)
      ├── output/ # Output generation (different styles, headers, etc.)
      ├── packager/ # Orchestrates file collection, processing, output, and clipboard operations.
      ├── security/ # Security checks to exclude sensitive files
      ├── tokenCount/ # Token counting using Tiktoken
      └── tree-sitter/ # Code parsing using Tree-sitter and language-specific queries
   └── shared/ # Shared utilities and types (error handling, logging, helper functions)
├── tests/ # Unit and integration tests (organized mirroring src/)
   ├── cli/
   ├── config/
   ├── core/
   ├── integration-tests/
   ├── shared/
   └── testing/
└── website/ # Documentation website (VitePress)
    ├── client/      # Client-side code (Vue.js components, styles, configuration)
       ├── .vitepress/  # VitePress configuration and theme
          ├── config/  # Site configuration files (navigation, sidebar, etc.)
          └── theme/   # Custom theme and styles
       ├── components/ # Vue.js components for the website
       └── src/        # Markdown files for the documentation in various languages (en, ja, etc.)
    └── server/      # Server-side API (for remote repository processing)
        └── src/       # Server source code (API endpoints, request handling)
```

----------------------------------------------------------------

# Coding Guidelines
- Follow the Airbnb JavaScript Style Guide.
- Split files into smaller, focused units when appropriate:
  - Aim to keep code files under 250 lines. If a file exceeds 250 lines, split it into multiple files based on functionality.
- Add comments to clarify non-obvious logic. **Ensure all comments are written in English.**
- Provide corresponding unit tests for all new features.
- After implementation, verify changes by running:
  ```bash
  npm run lint  # Ensure code style compliance
  npm run test  # Verify all tests pass
  ```

## Dependencies and Testing
- Inject dependencies through a deps object parameter for testability
- Example:
  ```typescript
  export const functionName = async (
    param1: Type1,
    param2: Type2,
    deps = {
      defaultFunction1,
      defaultFunction2,
    }
  ) => {
    // Use deps.defaultFunction1() instead of direct call
  };
  ```
- Mock dependencies by passing test doubles through deps object
- Use vi.mock() only when dependency injection is not feasible

## Generate Comprehensive Output
- Include all content without abbreviation, unless specified otherwise
- Optimize for handling large codebases while maintaining output quality

----------------------------------------------------------------

# GitHub Release Note Guidelines
When writing release notes, please follow these guidelines:

- When referencing issues or PRs, use the gh command to verify the content:
  ```bash
  gh issue view <issue-number>  # For checking issue content
  gh pr view <pr-number>        # For checking PR content
  ```
  This helps ensure accuracy in release note descriptions.

Here are some examples of release notes that follow the guidelines:

v0.2.25
````md
This release brings significant improvements to output formatting and introduces flexible remote repository handling capabilities along with enhanced logging features.

# Improvements ⚡

## Remote Repository Enhancement (#335)
- Added branch/tag parsing directly from repository URLs:
```bash
repomix --remote https://github.com/yamadashy/repomix/tree/0.1.x
```
Functions identically to:
```bash
repomix --remote https://github.com/yamadashy/repomix --remote-branch 0.1.x
```

Special thanks to @huy-trn for implementing this user-friendly feature!

## Enhanced Output Formatting (#328, #329, #330)
- Added "End of Codebase" marker for better clarity in output
- Improved output header accuracy:
  - Better representation of codebase scope
  - Clear indication when using `--include` or `--ignore` options

Special thanks to @gitkenan for adding the "End of Codebase" marker and reporting the header issue!

## Path Pattern Support (#337)
- Added support for special characters in paths:
  - Handles parentheses in include patterns (e.g., `src/(categories)/**/*`)
  - Improved escaping for `[]` and `{}`
  - Essential for Next.js route groups and similar frameworks

Thank you @matheuscoelhomalta for improving path pattern support!

# How to Update

```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
````

v0.2.24
````md
This release significantly enhances configuration flexibility with comprehensive CLI flag support and expands default ignore patterns for better project scaffolding. 

# What's New 🚀

## CLI Flags Revolution (#324)
- New command-line configuration now available.

```
- `--no-gitignore`: Disable .gitignore file usage
- `--no-default-patterns`: Disable default patterns
- `--header-text <text>`: Custom text to include in the file header
- `--instruction-file-path <path>`: Path to a file containing detailed custom instructions
- `--include-empty-directories`: Include empty directories in the output
```

Special recognition to @massdo for driving ecosystem growth.

# Improvements ⚡

## Enhanced Ignore Patterns (#318, #322)
- Expanded default ignores for Rust projects:
  - `target/`, `Cargo.lock`, build artifacts
  - PHP, Ruby, Go, Elixir, Haskell: package manager lock files

To @boralg for helping curate Rust-specific patterns!

# How to Update
```bash
npm update -g repomix
```

---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
````

v0.2.23
````md
This release adds significant performance improvements for large repositories, making Repomix faster and more efficient when needed.

# Improvements ⚡

## Parallel Processing Enhancement (#309)
- Implemented worker threads using [Piscina](https://github.com/piscinajs/piscina) for parallel processing

### Benchmark Results
- `yamadashy.repomix`: No significant change
  - Before: 868.73 millis
  - After: 671.26 millis
- `facebook/react`: 29x faster
  - Before: 123.31 secs
  - After: 4.19 secs
- `vercel/next.js`: 58x faster
  - Before: 17.85 mins
  - After: 17.27 secs

Note: While Repomix is not primarily designed for processing large repositories, and speed is not a primary goal, faster processing can provide a better user experience when working with larger codebases.

# How to Update

```bash
npm update -g repomix
```


---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.
````

v0.2.22
````md
This release introduces significant improvements to large file handling and expands the Repomix ecosystem with new tools and community channels.

# Improvements ⚡ 

## Improved Large File Handling (#302)

- Added a file size limit check (50MB) to prevent memory issues
- Graceful error handling for large files with clear user guidance:

Special thanks to @slavashvets for their continued contributions!

# Ecosystem Growth 🤝 

## New VS Code Extension (#300)
A community-created VS Code extension "Repomix Runner" is now available:
- Run Repomix directly from VS Code
- Extension by @massdo: [View on VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=DorianMassoulier.repomix-runner)

Thank you @massdo for bringing Repomix to VS Code and expanding our tooling ecosystem!

## Official Social Media
- Launched official Repomix X (Twitter) account: [@repomix_ai](https://x.com/repomix_ai)
  - Follow for updates, tips, and community highlights

# How to Update

```bash
npm update -g repomix
```

---

Join our growing community on [Discord](https://discord.gg/BF8GxZHE2C) and follow us on [X](https://x.com/repomix_ai) for updates!
````

v0.2.21
````md
This release introduces significant improvements to output formatting and documentation, featuring a new parsable style option for enhanced XML handling.

# What's New 🚀 

## Enhanced Output Style Control (#287)
- Added new `parsableStyle` option for better output handling:
  - Ensures output strictly follows the specification of the chosen format
  - Provides properly escaped XML output with fast-xml-parser
  - Dynamically adjusts markdown code block delimiters to avoid content conflicts
- Available via CLI flag `--parsable-style` or in configuration file

Special thanks to @atollk for their first contribution!

# Documentation 📚

## README Enhancements (#296)
- Updated Homebrew installation documentation to include Linux support

Special thanks to @chenrui333 for their continued contributions!

## Website Multi-Language Support (#293)
- Enhanced multi-language support in [repomix.com](https://repomix.com)

# How to Update

To update to the latest version, run:
```bash
npm update -g repomix
```


---

As always, if you encounter any issues or have suggestions, please let us know through our GitHub issues or join our [Discord community](https://discord.gg/wNYzTwZFku) for support.

</instruction>

For immediate assistance, please email our customer support: [email protected]

Download RAW File