This repository has been archived on 2026-11-17. You can view files and clone it, but cannot push or open issues or pull requests.
caelum0x 49b183818c Unify gitgram + aitimemachine into the monorepo (de-submodule) and merge vendored engines
Convert gitgram/ and aitimemachine/ from embedded git repos (which showed as
opaque submodule gitlinks on GitHub) into fully-tracked first-party content.

AITM now merges its 7 vendored repos as first-party engines:
- memory: beads (Go task DAG) + context7 (docs SDK), unified into saved_contexts
- git: vendored C git (bundled binary) + gitnexus (in-process code intelligence)
- agentic: a2a (@a2a-js/sdk) + pal (AITM-managed Python subprocess)

Includes the full session's product build: Gitgram web/mobile/backend features,
AITM website/CLI/MCP, the unified memory layer, engine build tooling
(scripts/build-engines.sh, Dockerfile, CI), docs (README, ENGINES.md, ARCHITECTURE.md),
and extensive test suites.

Build artifacts, node_modules, external/, and gemini-cli are gitignored.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 14:14:09 +03:00

944 lines
27 KiB
Markdown

# Contributing to repo2txt
Thank you for your interest in contributing! This document provides comprehensive guidance on the project architecture, design patterns, and development workflow.
## ๐Ÿ“‹ Table of Contents
- [Getting Started](#getting-started)
- [Architecture Overview](#architecture-overview)
- [Design Patterns](#design-patterns)
- [Project Structure](#project-structure)
- [Development Workflow](#development-workflow)
- [Testing Strategy](#testing-strategy)
- [Code Style](#code-style)
- [Pull Request Process](#pull-request-process)
## ๐Ÿš€ Getting Started
### Prerequisites
- Node.js 20+ (LTS recommended)
- npm 10+
- Git
- A code editor (VS Code recommended)
### Initial Setup
```bash
# Fork the repository on GitHub
# Clone your fork
git clone https://github.com/YOUR_USERNAME/repo2txt.git
cd repo2txt
# Add upstream remote
git remote add upstream https://github.com/abinthomasonline/repo2txt.git
# Install dependencies
npm install
# Copy test configuration template
cp tests/test-config.example.ts tests/test-config.ts
# Add your GitHub token to test-config.ts (optional, for E2E tests)
# Start development server
npm run dev
```
### Development Commands
```bash
# Development
npm run dev # Start dev server (http://localhost:5173/repo2txt/)
npm run build # Production build
npm run preview # Preview production build
# Testing
npm run test:unit # Run unit tests
npm run test:e2e # Run E2E tests
npm run test:watch # Watch mode for unit tests
npm run test:coverage # Generate coverage report
# Code Quality
npm run typecheck # TypeScript type checking
npm run lint # Lint code
npm run lint:fix # Auto-fix linting issues
npm run format # Format code with Prettier
npm run format:check # Check formatting
# CI Pipeline (runs all checks)
npm run ci # typecheck + lint + test:unit
```
## ๐Ÿ—๏ธ Architecture Overview
### Core Design Principles
1. **Provider Pattern** - Unified interface for multiple data sources
2. **Separation of Concerns** - Clear boundaries between UI, business logic, and data
3. **Type Safety** - TypeScript everywhere with strict mode
4. **Performance First** - Virtual scrolling, code splitting, Web Workers
5. **Privacy First** - All processing happens in the browser
### System Architecture
```
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ React App โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
โ”‚ โ”‚ UI โ”‚ โ”‚ Store โ”‚ โ”‚ Workers โ”‚ โ”‚
โ”‚ โ”‚ Components โ”‚โ—„โ”€โ”ค (Zustand) โ”‚โ—„โ”€โ”ค (Tokenizer) โ”‚ โ”‚
โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ”‚ โ–ฒ โ–ฒ โ”‚
โ”‚ โ”‚ โ”‚ โ”‚
โ”‚ โ–ผ โ–ผ โ”‚
โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
โ”‚ โ”‚ Provider Interface โ”‚ โ”‚
โ”‚ โ”‚ (BaseProvider - Abstract Base Class) โ”‚ โ”‚
โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ”‚ โ–ฒ โ–ฒ โ–ฒ โ–ฒ โ”‚
โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ โ”‚
โ”‚ โ”Œโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ” โ”‚
โ”‚ โ”‚ GitHub โ”‚ Local โ”‚ GitLab โ”‚ Azure โ”‚ โ”‚
โ”‚ โ”‚Providerโ”‚ Providerโ”‚ Provider โ”‚Provider โ”‚ โ”‚
โ”‚ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
```
### Data Flow
```
User Input โ†’ URL Parsing โ†’ Provider Selection โ†’ Tree Fetch
โ†“
File Tree (Virtual Scrolling) โ†’ User Selection โ†’ Filters
โ†“
Content Fetch โ†’ Formatting โ†’ Tokenization (Web Worker)
โ†“
Output Display โ†’ Copy/Download
```
## ๐ŸŽจ Design Patterns
### 1. Provider Pattern
**Purpose:** Abstract different data sources (GitHub, Local, GitLab, Azure) behind a unified interface.
**Implementation:**
```typescript
// Base provider interface
abstract class BaseProvider {
abstract getType(): ProviderType;
abstract validateUrl(url: string): boolean;
abstract parseUrl(url: string): ParsedRepoInfo;
abstract fetchTree(url: string, options?: FetchOptions): Promise<FileNode[]>;
abstract fetchFile(node: FileNode): Promise<FileContent>;
// Shared utilities
async *fetchMultiple(nodes: FileNode[]): AsyncGenerator<FileContent> {
// Progressive loading implementation
}
}
// Concrete implementation
class GitHubProvider extends BaseProvider {
async fetchTree(url: string): Promise<FileNode[]> {
// GitHub-specific implementation
const parsed = this.parseUrl(url);
const tree = await this.fetchGitHubTree(parsed);
return this.normalizeTree(tree);
}
}
```
**Benefits:**
- Easy to add new providers (GitLab, Bitbucket, etc.)
- Consistent interface across all sources
- Shared functionality in base class (error handling, retries, caching)
- Type-safe provider switching
### 2. State Management with Zustand
**Purpose:** Centralized, reactive state management without Redux boilerplate.
**Store Structure:**
```typescript
// Modular stores (slices pattern)
interface AppState {
// UI State
theme: ThemeMode;
isLoading: boolean;
error: ErrorState | null;
// Data State
currentProvider: ProviderType;
tree: FileNode[];
selectedPaths: Set<string>;
excludedPaths: Set<string>;
// Actions
setProvider: (provider: ProviderType) => void;
toggleSelection: (path: string) => void;
// ...more actions
}
// Store composition
const useStore = create<AppState>()(
devtools(
persist(
(set, get) => ({
// Initial state
theme: 'system',
// Actions
setTheme: (theme) => set({ theme }),
// Computed selectors
getSelectedNodes: () => {
const { tree, selectedPaths } = get();
return tree.filter(n => selectedPaths.has(n.path));
}
}),
{ name: 'repo2txt-store' }
)
)
);
```
**Benefits:**
- Simple API with hooks
- DevTools integration
- Persistence support
- Computed selectors
- Minimal re-renders
### 3. Virtual Scrolling
**Purpose:** Efficiently render large file trees (10,000+ files) without performance degradation.
**Implementation:**
```typescript
// Using TanStack Virtual
import { useVirtualizer } from '@tanstack/react-virtual';
function FileTree({ nodes }: { nodes: TreeNode[] }) {
const parentRef = useRef<HTMLDivElement>(null);
// Flatten tree for virtual scrolling
const flatNodes = useMemo(() => flattenTree(nodes), [nodes]);
const virtualizer = useVirtualizer({
count: flatNodes.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 32, // Row height
overscan: 10, // Render extra rows outside viewport
});
return (
<div ref={parentRef} style={{ height: '600px', overflow: 'auto' }}>
<div style={{ height: virtualizer.getTotalSize() }}>
{virtualizer.getVirtualItems().map(virtualRow => (
<FileTreeNode
key={virtualRow.key}
node={flatNodes[virtualRow.index]}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
transform: `translateY(${virtualRow.start}px)`,
}}
/>
))}
</div>
</div>
);
}
```
**Benefits:**
- Constant memory usage regardless of tree size
- Smooth scrolling
- Only renders visible items + overscan
- Automatic height calculation
### 4. Code Splitting with Dynamic Imports
**Purpose:** Reduce initial bundle size by lazy-loading provider implementations.
**Implementation:**
```typescript
// Provider registry with lazy loading
const PROVIDERS = {
github: () => import('@/features/github/GitHubProvider'),
local: () => import('@/features/local/LocalProvider'),
gitlab: () => import('@/features/gitlab/GitLabProvider'),
azure: () => import('@/features/azure/AzureDevOpsProvider'),
};
// Dynamic provider loading in ProviderSelector
const loadProvider = async (type: ProviderType) => {
const ProviderModule = await PROVIDERS[type]();
const ProviderClass = ProviderModule.default;
return new ProviderClass();
};
```
**Bundle Impact:**
- Main chunk: ~330KB
- GitHub provider: ~50KB (loaded on demand)
- Local provider: ~30KB (loaded on demand)
- Each provider only loads when selected
### 5. Web Worker for Tokenization
**Purpose:** Offload CPU-intensive tokenization to background thread.
**Implementation:**
```typescript
// Worker wrapper
class TokenizerWorker {
private worker: Worker;
async tokenize(text: string): Promise<number> {
return new Promise((resolve) => {
this.worker.postMessage({ type: 'tokenize', text });
this.worker.onmessage = (e) => resolve(e.data.tokenCount);
});
}
async tokenizeBatch(
files: FileContent[],
onProgress?: (progress: number) => void
): Promise<{ totalTokens: number; files: FileWithStats[] }> {
// Progressive tokenization with progress callbacks
}
}
// Worker implementation (tokenizer.worker.ts)
self.onmessage = async (event) => {
const { type, text, files } = event.data;
if (type === 'tokenize') {
const tokenCount = encode(text).length;
self.postMessage({ tokenCount });
} else if (type === 'tokenize_batch') {
for (const file of files) {
const tokenCount = encode(file.content).length;
self.postMessage({
type: 'progress',
file: { ...file, tokenCount }
});
}
}
};
```
**Benefits:**
- Non-blocking UI during tokenization
- Progress updates for long operations
- Better perceived performance
- Utilizes multi-core CPUs
### 6. Error Handling Strategy
**Layered error handling with custom error types:**
```typescript
// Custom error classes
class ProviderError extends Error {
constructor(
message: string,
public code: ErrorCode,
public userMessage: string,
public recovery?: () => void
) {
super(message);
}
}
// Error boundaries in React
class ErrorBoundary extends Component {
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
// Log to error tracking service
console.error('Caught error:', error, errorInfo);
}
}
// Error dialog for user-facing errors
{error && (
<ErrorDialog
title="Unable to Complete Request"
message={error.message}
onClose={() => setError(null)}
onAction={error.recovery}
actionLabel={error.recoveryLabel}
/>
)}
```
## ๐Ÿ“ Project Structure
```
repo2txt/
โ”œโ”€โ”€ .github/
โ”‚ โ””โ”€โ”€ workflows/
โ”‚ โ””โ”€โ”€ deploy.yml # GitHub Actions CI/CD
โ”‚
โ”œโ”€โ”€ src/
โ”‚ โ”œโ”€โ”€ features/ # Feature modules (domain-driven)
โ”‚ โ”‚ โ”œโ”€โ”€ github/
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ GitHubProvider.ts # GitHub API implementation
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ components/ # GitHub-specific UI
โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ GitHubAuth.tsx # Token management
โ”‚ โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ GitHubForm.tsx # URL input form
โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ GitHubUrlInput.tsx
โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ __tests__/ # Feature tests
โ”‚ โ”‚ โ”‚
โ”‚ โ”‚ โ”œโ”€โ”€ local/
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ LocalProvider.ts # File System API
โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ components/
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ DirectoryPicker.tsx
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ ZipUploader.tsx
โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ LocalForm.tsx
โ”‚ โ”‚ โ”‚
โ”‚ โ”‚ โ”œโ”€โ”€ gitlab/ # GitLab provider (beta)
โ”‚ โ”‚ โ””โ”€โ”€ azure/ # Azure DevOps (beta)
โ”‚ โ”‚
โ”‚ โ”œโ”€โ”€ components/ # Shared UI components
โ”‚ โ”‚ โ”œโ”€โ”€ ui/ # Base components (buttons, dialogs)
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ Button.tsx
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ ErrorDialog.tsx
โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ ThemeToggle.tsx
โ”‚ โ”‚ โ”‚
โ”‚ โ”‚ โ”œโ”€โ”€ file-tree/ # File tree components
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ FileTree.tsx # Virtual scrolling tree
โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ FileTreeNode.tsx # Individual node
โ”‚ โ”‚ โ”‚
โ”‚ โ”‚ โ”œโ”€โ”€ filters/ # Filtering components
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ AdvancedFilters.tsx
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ ExtensionFilter.tsx
โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ GitignoreEditor.tsx
โ”‚ โ”‚ โ”‚
โ”‚ โ”‚ โ”œโ”€โ”€ OutputPanel.tsx # Output display & actions
โ”‚ โ”‚ โ”œโ”€โ”€ FileStats.tsx # Token/line statistics
โ”‚ โ”‚ โ””โ”€โ”€ ProviderSelector.tsx # Provider tabs
โ”‚ โ”‚
โ”‚ โ”œโ”€โ”€ lib/ # Core business logic
โ”‚ โ”‚ โ”œโ”€โ”€ providers/
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ BaseProvider.ts # Abstract base class
โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ types.ts # Shared provider types
โ”‚ โ”‚ โ”‚
โ”‚ โ”‚ โ”œโ”€โ”€ formatter/
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ Formatter.ts # Output formatting
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ TokenizerWorker.ts # Web Worker wrapper
โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ __tests__/
โ”‚ โ”‚ โ”‚
โ”‚ โ”‚ โ”œโ”€โ”€ gitignore/
โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ GitignoreParser.ts # .gitignore parsing
โ”‚ โ”‚ โ”‚
โ”‚ โ”‚ โ””โ”€โ”€ utils.ts # Shared utilities
โ”‚ โ”‚
โ”‚ โ”œโ”€โ”€ store/ # Zustand state management
โ”‚ โ”‚ โ”œโ”€โ”€ index.ts # Store composition
โ”‚ โ”‚ โ””โ”€โ”€ slices/ # Store slices
โ”‚ โ”‚ โ”œโ”€โ”€ providerSlice.ts # Provider state
โ”‚ โ”‚ โ”œโ”€โ”€ fileTreeSlice.ts # File tree state
โ”‚ โ”‚ โ”œโ”€โ”€ filterSlice.ts # Filter state
โ”‚ โ”‚ โ””โ”€โ”€ uiSlice.ts # UI state (theme, loading)
โ”‚ โ”‚
โ”‚ โ”œโ”€โ”€ hooks/ # Custom React hooks
โ”‚ โ”‚ โ”œโ”€โ”€ useFileTree.ts
โ”‚ โ”‚ โ”œโ”€โ”€ useProvider.ts
โ”‚ โ”‚ โ””โ”€โ”€ useTheme.ts
โ”‚ โ”‚
โ”‚ โ”œโ”€โ”€ workers/ # Web Workers
โ”‚ โ”‚ โ””โ”€โ”€ tokenizer.worker.ts # GPT tokenizer
โ”‚ โ”‚
โ”‚ โ”œโ”€โ”€ types/ # Shared TypeScript types
โ”‚ โ”‚ โ””โ”€โ”€ index.ts
โ”‚ โ”‚
โ”‚ โ”œโ”€โ”€ App.tsx # Root component
โ”‚ โ”œโ”€โ”€ main.tsx # Entry point
โ”‚ โ””โ”€โ”€ index.css # Global styles
โ”‚
โ”œโ”€โ”€ tests/
โ”‚ โ”œโ”€โ”€ e2e/ # End-to-end tests (Playwright)
โ”‚ โ”‚ โ”œโ”€โ”€ dark-mode.spec.ts
โ”‚ โ”‚ โ”œโ”€โ”€ error-scenarios.spec.ts
โ”‚ โ”‚ โ”œโ”€โ”€ github-flow.spec.ts
โ”‚ โ”‚ โ””โ”€โ”€ local-flow.spec.ts
โ”‚ โ”‚
โ”‚ โ”œโ”€โ”€ test-config.ts # Test configuration (git-ignored)
โ”‚ โ””โ”€โ”€ test-config.example.ts # Template
โ”‚
โ”œโ”€โ”€ public/ # Static assets
โ”œโ”€โ”€ dist/ # Build output (git-ignored)
โ”‚
โ”œโ”€โ”€ .eslintrc.cjs # ESLint configuration
โ”œโ”€โ”€ .prettierrc # Prettier configuration
โ”œโ”€โ”€ tsconfig.json # TypeScript configuration
โ”œโ”€โ”€ vite.config.ts # Vite configuration
โ”œโ”€โ”€ playwright.config.ts # Playwright configuration
โ”œโ”€โ”€ vitest.config.ts # Vitest configuration
โ””โ”€โ”€ package.json # Dependencies & scripts
```
### Key Directories Explained
**`features/`** - Domain-driven feature modules. Each feature (GitHub, Local, etc.) is self-contained with its provider implementation, UI components, and tests.
**`components/`** - Shared UI components used across features. Organized by functionality (ui, file-tree, filters).
**`lib/`** - Core business logic independent of UI framework. Could be extracted to a separate package if needed.
**`store/`** - Centralized state management using Zustand slices pattern. Each slice manages a specific concern.
**`workers/`** - Web Workers for CPU-intensive tasks. Keeps UI thread responsive.
## ๐Ÿงช Testing Strategy
### Testing Pyramid
```
/\
/ \ E2E (Playwright) - 25 tests
/____\ Critical user flows
/ \
/ \ Integration - Provider + UI
/__________\
/ \ Unit (Vitest) - 80%+ coverage
/______________\ Business logic, utilities, components
```
### Unit Tests (Vitest + React Testing Library)
**What to test:**
- Pure functions (formatters, parsers, utilities)
- React components in isolation
- Provider methods
- Store actions and selectors
**Example:**
```typescript
// lib/formatter/__tests__/Formatter.test.ts
describe('Formatter', () => {
it('should format directory tree', () => {
const tree = [
{ path: 'src', type: 'tree' },
{ path: 'src/index.ts', type: 'blob' },
];
const formatted = Formatter.formatTree(tree);
expect(formatted).toContain('โ”œโ”€โ”€ ๐Ÿ“ src');
expect(formatted).toContain('โ””โ”€โ”€ ๐Ÿ“„ index.ts');
});
it('should count tokens accurately', () => {
const text = 'Hello world';
const count = Formatter.countTokens(text);
expect(count).toBeGreaterThan(0);
});
});
```
### Integration Tests
**What to test:**
- Provider + FileTree interactions
- Filter + FileTree updates
- Store + Component integration
**Example:**
```typescript
describe('GitHub Provider Integration', () => {
it('should load and display file tree', async () => {
const provider = new GitHubProvider();
const tree = await provider.fetchTree('https://github.com/facebook/react');
render(<FileTree nodes={tree} />);
expect(screen.getByText('package.json')).toBeInTheDocument();
});
});
```
### E2E Tests (Playwright)
**What to test:**
- Complete user workflows
- Cross-browser compatibility
- Real API interactions
**Current Coverage:**
- โœ… Dark mode (5 tests)
- โœ… Error scenarios (8 tests)
- โœ… GitHub flow (6 tests)
- โœ… Local flow (6 tests)
**Example:**
```typescript
// tests/e2e/github-flow.spec.ts
test('should complete full GitHub public repo flow', async ({ page }) => {
await page.goto('/');
// Enter URL
const urlInput = page.getByPlaceholder('https://github.com/facebook/react');
await urlInput.fill('https://github.com/abinthomasonline/repo2txt');
// Load repo
const loadButton = page.getByRole('button', { name: /Load Repository/i });
await loadButton.click();
// Verify file tree
await expect(page.getByTestId('file-tree-heading')).toBeVisible({ timeout: 30000 });
// Generate output
const generateButton = page.getByTestId('generate-output-button');
await generateButton.click();
// Verify output
await expect(page.getByText('Directory Structure:')).toBeVisible();
// Download
const downloadPromise = page.waitForEvent('download');
await page.getByRole('button', { name: /Download/i }).click();
const download = await downloadPromise;
expect(download.suggestedFilename()).toMatch(/\.txt/);
});
```
### Running Tests
```bash
# Unit tests
npm run test:unit # Run once
npm run test:watch # Watch mode
npm run test:coverage # With coverage
# E2E tests
npm run test:e2e # All browsers
npm run test:e2e -- --project=chromium # Single browser
npm run test:e2e:ui # Interactive UI
# Test specific file
npm run test:unit -- Formatter.test.ts
npm run test:e2e -- github-flow.spec.ts
```
### Test Configuration
**E2E Test Token Setup:**
```bash
# Copy template
cp tests/test-config.example.ts tests/test-config.ts
# Add your token to test-config.ts
export const testConfig = {
githubToken: process.env.GITHUB_TOKEN || 'your_token_here',
};
```
**CI Configuration:**
Tests run automatically on PRs via GitHub Actions. Set `GITHUB_TOKEN` secret in repository settings for E2E tests.
## ๐Ÿ’… Code Style
### TypeScript
- **Strict mode enabled** - No implicit any, strict null checks
- **Explicit return types** - For public functions and methods
- **Interface over type** - Prefer interfaces for object shapes
- **Functional style** - Prefer pure functions, immutability
**Example:**
```typescript
// โœ… Good
interface FileNode {
path: string;
type: 'blob' | 'tree';
children?: FileNode[];
}
function filterNodes(nodes: FileNode[], predicate: (node: FileNode) => boolean): FileNode[] {
return nodes.filter(predicate).map(node => ({
...node,
children: node.children ? filterNodes(node.children, predicate) : undefined,
}));
}
// โŒ Bad
function filterNodes(nodes: any, predicate): any {
return nodes.filter(predicate);
}
```
### React Components
- **Functional components** - Use hooks, avoid class components
- **Named exports** - Except for default component export
- **Props interfaces** - Named after component: `ComponentNameProps`
- **Early returns** - Handle edge cases first
**Example:**
```typescript
// โœ… Good
interface FileTreeNodeProps {
node: TreeNode;
depth: number;
onToggle: (path: string) => void;
}
export function FileTreeNode({ node, depth, onToggle }: FileTreeNodeProps) {
if (!node) return null;
const isDirectory = node.type === 'tree';
return (
<div style={{ paddingLeft: `${depth * 16}px` }}>
<button onClick={() => onToggle(node.path)}>
{isDirectory ? '๐Ÿ“' : '๐Ÿ“„'} {node.name}
</button>
</div>
);
}
```
### CSS/Tailwind
- **Tailwind first** - Use utility classes
- **Component classes** - For reusable patterns, define in component
- **Dark mode** - Always add dark: variants
- **Responsive** - Mobile-first with sm:, md:, lg: breakpoints
**Example:**
```tsx
// โœ… Good
<div className="flex items-center gap-2 p-4 bg-white dark:bg-gray-900 rounded-lg">
<button className="px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white rounded-md transition-colors">
Click me
</button>
</div>
// โŒ Bad
<div style={{ display: 'flex', padding: '16px', backgroundColor: '#fff' }}>
<button style={{ padding: '8px 16px', backgroundColor: '#3b82f6' }}>
Click me
</button>
</div>
```
### File Naming
- **Components**: PascalCase (e.g., `FileTree.tsx`, `ErrorDialog.tsx`)
- **Utilities**: camelCase (e.g., `formatTree.ts`, `parseUrl.ts`)
- **Types**: PascalCase (e.g., `FileNode`, `ProviderType`)
- **Tests**: Same as file + `.test.ts` or `.spec.ts`
### Code Organization
**Import Order:**
```typescript
// 1. React/external libraries
import { useState, useEffect } from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
// 2. Internal imports (@/ aliases)
import { BaseProvider } from '@/lib/providers/BaseProvider';
import { FileTree } from '@/components/file-tree/FileTree';
// 3. Types
import type { FileNode, ProviderType } from '@/types';
// 4. Relative imports
import { formatTree } from './utils';
// 5. Styles (if any)
import './styles.css';
```
### ESLint & Prettier
All code must pass linting and formatting:
```bash
npm run lint # Check for issues
npm run lint:fix # Auto-fix
npm run format # Format with Prettier
npm run format:check # Check formatting
```
## ๐Ÿ”„ Development Workflow
### Branch Strategy
- **`master`** - Production-ready code
- **`v2-development`** - Main development branch
- **`feature/*`** - New features (e.g., `feature/gitlab-support`)
- **`fix/*`** - Bug fixes (e.g., `fix/token-storage`)
- **`refactor/*`** - Code refactoring (e.g., `refactor/provider-interface`)
### Commit Messages
Follow [Conventional Commits](https://www.conventionalcommits.org/):
```
<type>(<scope>): <subject>
<body>
<footer>
```
**Types:**
- `feat`: New feature
- `fix`: Bug fix
- `refactor`: Code refactoring
- `test`: Test changes
- `docs`: Documentation
- `style`: Code style changes (formatting)
- `perf`: Performance improvements
- `chore`: Build process, dependencies
**Examples:**
```bash
git commit -m "feat(github): support branch names with slashes"
git commit -m "fix(ui): correct dark mode toggle sequence"
git commit -m "test(e2e): add error dialog tests"
git commit -m "docs: update architecture documentation"
```
### Pull Request Process
1. **Create Feature Branch**
```bash
git checkout -b feature/your-feature
```
2. **Make Changes**
- Write code
- Add tests
- Update documentation
- Run quality checks
3. **Test Locally**
```bash
npm run ci # Type check + lint + unit tests
npm run test:e2e # E2E tests
```
4. **Commit Changes**
```bash
git add .
git commit -m "feat(scope): your feature description"
```
5. **Push to GitHub**
```bash
git push origin feature/your-feature
```
6. **Create Pull Request**
- Fill out PR template
- Link related issues
- Request reviews
7. **Address Review Feedback**
- Make requested changes
- Push additional commits
- Re-request review
8. **Merge**
- Squash merge for feature branches
- Merge commit for releases
### PR Checklist
Before submitting a PR:
- [ ] Code follows style guide
- [ ] All tests pass locally
- [ ] Added tests for new features
- [ ] Updated documentation
- [ ] No TypeScript errors
- [ ] No ESLint warnings
- [ ] Formatted with Prettier
- [ ] Tested in multiple browsers (if UI change)
- [ ] Tested dark mode (if UI change)
- [ ] Added/updated comments for complex logic
- [ ] No console.logs or debugger statements
- [ ] Bundle size impact is acceptable
## ๐Ÿ› Debugging Tips
### React DevTools
Install [React DevTools](https://react.dev/learn/react-developer-tools) for component inspection and state debugging.
### Zustand DevTools
DevTools integration is enabled in development:
```typescript
// Inspect store in browser console
window.__ZUSTAND_STORE__
```
### Vite Debug Mode
```bash
# Enable verbose logging
DEBUG=vite:* npm run dev
```
### Common Issues
**Issue: E2E tests failing with rate limit**
- Add GitHub token to `tests/test-config.ts`
**Issue: Build fails with TypeScript errors**
- Run `npm run typecheck` to see all errors
- Use `npm run build:check` for strict type checking
**Issue: Virtual scrolling not working**
- Check parent container has fixed height
- Verify `flattenTree` function is memoized
**Issue: Web Worker not loading**
- Check worker file path in Vite config
- Ensure worker is imported with `?worker` suffix
## ๐Ÿ“š Additional Resources
- [React Documentation](https://react.dev/)
- [TypeScript Handbook](https://www.typescriptlang.org/docs/)
- [Vite Guide](https://vitejs.dev/guide/)
- [Zustand Documentation](https://zustand-demo.pmnd.rs/)
- [Tailwind CSS](https://tailwindcss.com/docs)
- [Playwright Documentation](https://playwright.dev/)
## ๐Ÿ’ฌ Questions?
- **GitHub Discussions**: [Ask questions](https://github.com/abinthomasonline/repo2txt/discussions)
- **Issues**: [Report bugs](https://github.com/abinthomasonline/repo2txt/issues)
- **Email**: abinthomasonline@gmail.com
---
Thank you for contributing to repo2txt! ๐ŸŽ‰