# Gitea TypeScript/JavaScript SDK

Official TypeScript/JavaScript SDK for the Gitea API with chunked upload support for large files.

## Installation

```bash
npm install @gitea/sdk
# or
yarn add @gitea/sdk
# or
pnpm add @gitea/sdk
```

## Quick Start

```typescript
import { GiteaClient } from '@gitea/sdk';

// Create client
const client = new GiteaClient({
  baseUrl: 'https://gitea.example.com',
  token: 'your_token'
});

// Get current user
const user = await client.getCurrentUser();
console.log(`Logged in as ${user.login}`);

// Get a repository
const repo = await client.getRepository('owner', 'repo');
console.log(`Repository: ${repo.full_name}`);
```

## Chunked Upload

Upload large files with progress tracking:

```typescript
import { GiteaClient } from '@gitea/sdk';

const client = new GiteaClient({
  baseUrl: 'https://gitea.example.com',
  token: 'your_token'
});

// Upload a release asset with progress
const file = new File([...], 'large-file.tar.gz');

const result = await client.uploadReleaseAsset({
  owner: 'myorg',
  repo: 'myrepo',
  releaseId: 123,
  file,
  chunkSize: 50 * 1024 * 1024, // 50MB chunks
  parallel: 4,
  verifyChecksum: true,
  onProgress: (p) => {
    console.log(`Progress: ${p.percent.toFixed(1)}%`);
    console.log(`Speed: ${formatBytes(p.speed)}/s`);
    console.log(`ETA: ${formatDuration(p.eta)}`);
  }
});

console.log(`Uploaded: ${result.browser_download_url}`);
```

## Using ChunkedUpload Directly

For more control over the upload process:

```typescript
import { GiteaClient, ChunkedUpload } from '@gitea/sdk';

const client = new GiteaClient({
  baseUrl: 'https://gitea.example.com',
  token: 'your_token'
});

const upload = client.createChunkedUpload('owner', 'repo', 123, {
  chunkSize: 50 * 1024 * 1024,
  parallel: 4,
  onProgress: (p) => console.log(`${p.percent.toFixed(1)}%`)
});

try {
  const result = await upload.upload(file, 'filename.tar.gz');
  console.log(`Success: ${result.browser_download_url}`);
} catch (error) {
  // Upload failed, can retry later
  const session = upload.getSession();
  console.log(`Resume with session: ${session?.id}`);
}
```

## API Reference

### GiteaClient

#### Constructor

```typescript
const client = new GiteaClient({
  baseUrl: 'https://gitea.example.com',
  token: 'your_api_token',
  timeout: 30000, // Request timeout in milliseconds
});
```

#### User Methods

- `getCurrentUser()` - Get authenticated user
- `getUser(username)` - Get user by username

#### Repository Methods

- `getRepository(owner, repo)` - Get repository
- `listUserRepos(username)` - List user's repositories

#### Release Methods

- `getRelease(owner, repo, releaseId)` - Get release by ID
- `getReleaseByTag(owner, repo, tag)` - Get release by tag
- `listReleases(owner, repo)` - List all releases

#### Upload Methods

- `uploadReleaseAsset(options)` - Upload release asset with chunked upload
- `createChunkedUpload(owner, repo, releaseId, options)` - Create upload handler
- `getUploadSession(sessionId)` - Get upload session status
- `cancelUpload(sessionId)` - Cancel upload session

## Error Handling

```typescript
import {
  GiteaClient,
  APIError,
  AuthenticationError,
  NotFoundError,
  UploadError
} from '@gitea/sdk';

const client = new GiteaClient({
  baseUrl: 'https://gitea.example.com',
  token: 'your_token'
});

try {
  const repo = await client.getRepository('owner', 'nonexistent');
} catch (error) {
  if (error instanceof NotFoundError) {
    console.log(`Repository not found: ${error.message}`);
  } else if (error instanceof AuthenticationError) {
    console.log(`Authentication failed: ${error.message}`);
  } else if (error instanceof UploadError) {
    console.log(`Upload failed: ${error.message}`);
    console.log(`Session: ${error.sessionId}, Chunk: ${error.chunk}`);
  } else if (error instanceof APIError) {
    console.log(`API error [${error.code}]: ${error.message}`);
  }
}
```

## Browser Support

This SDK works in modern browsers that support:
- `fetch` API
- `crypto.subtle` for SHA-256 checksum
- `File` and `Blob` APIs

For Node.js, you may need to polyfill `fetch` for versions < 18.

## License

MIT License - See LICENSE file for details.
