npm package: @scriptdb/storage
Description: Storage module resolver for script database
Latest version: 1.1.3

# @scriptdb/storage

Storage module for the script database, providing a Git-based file system with full version control capabilities.

## Features

- **Git-based storage**: Complete version control for all files
- **File operations**: Add, update, delete, and retrieve files
- **Repository management**: Initialize, configure, and manage Git repositories
- **Remote operations**: Push, pull, fetch, and clone repositories
- **Configuration management**: Full Git configuration support
- **Cross-platform compatibility**: Works on Windows, macOS, and Linux

## Installation

```bash
bun add @scriptdb/storage
```

## Quick Start

```typescript
import { Storage } from '@scriptdb/storage';

// Initialize storage
const storage = new Storage('./my-repo');
await storage.initialize();

// Add a file
await storage.addFile('hello.txt', 'Hello, World!');

// Commit changes
await storage.commit('Initial commit');

// Get file content
const file = await storage.getFile('hello.txt');
console.log(file.content); // "Hello, World!"
```

## API Reference

### Constructor

```typescript
new Storage(repoPath: string)
```

Creates a new storage instance with the specified repository path.

### Methods

#### initialize(repoPath?)

Initializes a Git repository at the specified path.

```typescript
await storage.initialize(repoPath?: string): Promise<SimpleGit>
```

#### File Operations

##### addFile(filePath, content)

Adds a new file to the repository.

```typescript
await storage.addFile(filePath: string, content: string): Promise<{ success: boolean; message: string; path?: string }>
```

##### updateFile(filePath, content)

Updates an existing file.

```typescript
await storage.updateFile(filePath: string, content: string): Promise<{ success: boolean; message: string; path?: string }>
```

##### getFile(filePath)

Retrieves file content.

```typescript
await storage.getFile(filePath: string): Promise<{ success: boolean; content?: string; path?: string; message?: string }>
```

##### deleteFile(filePath)

Deletes a file from the repository.

```typescript
await storage.deleteFile(filePath: string): Promise<{ success: boolean; message: string }>
```

#### Repository Operations

##### commit(message)

Commits staged changes.

```typescript
await storage.commit(message: string): Promise<{ success: boolean; message: string }>
```

##### getStatus()

Gets the current repository status.

```typescript
await storage.getStatus(): Promise<RepoStatus>
```

##### getHistory(filePath)

Gets commit history for a file.

```typescript
await storage.getHistory(filePath: string): Promise<CommitHistory[]>
```

##### listFiles()

Lists all files in the repository.

```typescript
await storage.listFiles(): Promise<string[]>
```

#### Git Configuration

##### setConfig(config, scope?)

Sets Git configuration values.

```typescript
await storage.setConfig(config: GitConfig, scope?: 'local' | 'global' | 'system'): Promise<{ success: boolean; message: string; changes?: any[] }>
```

##### getConfig(key, scope?)

Gets a specific Git configuration value.

```typescript
await storage.getConfig(key: string, scope?: 'local' | 'global' | 'system'): Promise<{ success: boolean; key?: string; value?: string; scope?: string; message?: string }>
```

##### listConfig(scope?)

Lists all Git configuration values.

```typescript
await storage.listConfig(scope?: 'local' | 'global' | 'system'): Promise<{ success: boolean; scope: string; config?: any; message?: string }>
```

##### setupBasicConfig(userName?, userEmail?, additionalConfig?)

Sets up basic Git configuration.

```typescript
await storage.setupBasicConfig(userName?: string, userEmail?: string, additionalConfig?: Record<string, string>): Promise<{ success: boolean; message: string }>
```

#### Remote Operations

##### addRemote(name, url)

Adds a remote repository.

```typescript
await storage.addRemote(name: string, url: string): Promise<{ success: boolean; message: string; name?: string; url?: string }>
```

##### removeRemote(name)

Removes a remote repository.

```typescript
await storage.removeRemote(name: string): Promise<{ success: boolean; message: string; name?: string }>
```

##### listRemotes()

Lists all remote repositories.

```typescript
await storage.listRemotes(): Promise<{ success: boolean; remotes: RemoteInfo[]; message?: string }>
```

##### push(remote?, branch?, options?)

Pushes changes to a remote repository.

```typescript
await storage.push(remote?: string, branch?: string, options?: { force?: boolean; setUpstream?: boolean }): Promise<{ success: boolean; message: string; remote?: string; branch?: string }>
```

##### pull(remote?, branch?, options?)

Pulls changes from a remote repository.

```typescript
await storage.pull(remote?: string, branch?: string, options?: { allowUnrelatedHistories?: boolean }): Promise<{ success: boolean; message: string; remote?: string; branch?: string }>
```

##### fetch(remote?, branch?, options?)

Fetches changes from a remote repository without merging.

```typescript
await storage.fetch(remote?: string, branch?: string, options?: { prune?: boolean }): Promise<{ success: boolean; message: string; remote?: string; branch?: string }>
```

##### clone(url, targetPath?, options?)

Clones a remote repository.

```typescript
await storage.clone(url: string, targetPath?: string, options?: { bare?: boolean; branch?: string; depth?: number }): Promise<{ success: boolean; message: string; url?: string; path?: string }>
```

## Types

### GitConfig

```typescript
interface GitConfig {
  userName?: string;
  userEmail?: string;
  options?: Record<string, string>;
}
```

### RepoStatus

```typescript
interface RepoStatus {
  staged: string[];
  unstaged: string[];
  untracked: string[];
  clean: boolean;
  error?: string;
}
```

### RemoteInfo

```typescript
interface RemoteInfo {
  name: string;
  refs: string;
  pushUrl: string;
}
```

### CommitHistory

```typescript
interface CommitHistory {
  hash: string;
  message: string;
  date: string;
  author: string;
}
```

## Examples

### Basic Usage

```typescript
import { Storage } from '@scriptdb/storage';

// Create storage instance
const storage = new Storage('./my-project');
await storage.initialize();

// Configure user
await storage.setupBasicConfig('John Doe', 'john@example.com');

// Add files
await storage.addFile('README.md', '# My Project');
await storage.addFile('src/index.ts', 'console.log("Hello, World!");');

// Commit changes
await storage.commit('Initial commit');

// Update a file
await storage.updateFile('README.md', '# My Project\n\nA sample project.');
await storage.commit('Update README');

// Get file content
const readme = await storage.getFile('README.md');
console.log(readme.content);

// Get repository status
const status = await storage.getStatus();
console.log(status);
```

### Working with Remotes

```typescript
import { Storage } from '@scriptdb/storage';

// Initialize storage
const storage = new Storage('./my-project');
await storage.initialize();

// Add remote
await storage.addRemote('origin', 'https://github.com/username/my-project.git');

// Push changes
await storage.push('origin', 'main');

// Pull changes
await storage.pull('origin', 'main');

// Fetch changes without merging
await storage.fetch('origin', 'main');

// Clone a repository
const newStorage = new Storage('./cloned-project');
await newStorage.clone('https://github.com/username/another-project.git');
```

### Configuration Management

```typescript
import { Storage } from '@scriptdb/storage';

const storage = new Storage('./my-project');
await storage.initialize();

// Set user configuration
await storage.setConfig({
  userName: 'Jane Doe',
  userEmail: 'jane@example.com',
  options: {
    'core.autocrlf': 'false',
    'pull.rebase': 'true'
  }
});

// Get configuration
const userName = await storage.getConfig('user.name');
console.log(userName.value); // "Jane Doe"

// List all configuration
const config = await storage.listConfig();
console.log(config.config);
```

## Error Handling

All methods return a result object with a `success` property indicating if the operation was successful. If `success` is `false`, the `message` property contains information about the error.

```typescript
const result = await storage.addFile('test.txt', 'content');

if (result.success) {
  console.log(`File added at ${result.path}`);
} else {
  console.error(`Error: ${result.message}`);
}
```

## Security Considerations

- Ensure proper file system permissions for the repository path
- Validate file paths and content to prevent directory traversal attacks
- Use secure authentication methods for remote operations
- Consider encrypting sensitive data before storing it

## License

MIT