# Koneksi TypeScript SDK

A comprehensive TypeScript SDK for interacting with the Koneksi API. This SDK provides a clean and intuitive interface for managing directories, files, health monitoring, and peer operations in the Koneksi platform.

## Features

- 🗂️ **Directory Management** - Create, read, update, delete, rename, and move directories
- 📁 **File Operations** - Upload, download, read, update, delete, rename, move files
- 🔐 **File Access Control** - Set public, private, password, or email-based access
- 🔗 **Temporary Links** - Generate temporary access tokens and preview links
- 🏥 **Health Monitoring** - Check API service health status
- 👥 **Peer Management** - Fetch available peers
- 👤 **Profile Access** - Retrieve current user profile and settings
- 📊 **Dashboard Metrics** - Collect usage and resource metrics
- 🔒 **Encryption Support** - Upload and download encrypted files with passphrases
- 🌐 **Multi-Environment Support** - Local, staging, UAT, and production environments
- 📝 **Full TypeScript Support** - Complete type definitions and IntelliSense

## Installation

```bash
npm install koneksi-ts-sdk
```

## Quick Start

```typescript
import KoneksiSDK from "koneksi-ts-sdk";

// Initialize the SDK
const sdk = new KoneksiSDK({
  environment: "uat", // "local", "staging", "uat", "production" // optional, defaults to uat
  client_id: "your_client_id",
  client_secret: "your_client_secret",
});

// Check API health
const health = await sdk.health.check();

// Create a directory
const directory = await sdk.directory.create({
  name: "My Documents",
  directory_id: "parent_directory_id", // optional
});

// Upload a file
const uploadResult = await sdk.file.upload({
  file: "important_file.pdf", // File object, Buffer, or string path
  directory_id: directory.id,
  passphrase: "MySecret123!", // optional for encryption
});

// Download a file
const fileBuffer = await sdk.file.download({
  fileId: uploadResult.file_id,
  passphrase: "MySecret123!", // required for encrypted files
});
```

## Configuration

The SDK supports multiple environments with different API endpoints:

```typescript
const sdk = new KoneksiSDK({
  environment: "uat", // "local", "staging", "uat", "production". Optional, defaults to uat
  client_id: "your_client_id",
  client_secret: "your_client_secret",
});
```

## API Reference

### Directory Operations

The `sdk.directory` object provides methods for managing directories.

#### Create Directory

Creates a new directory in the specified parent directory.

```typescript
const directory = await sdk.directory.create({
  name: "Directory Name",
  directory_id: "parent_directory_id", // optional, defaults to root
});
```

#### Read Directory

Retrieves directory details including files and subdirectories.

```typescript
const directoryData = await sdk.directory.read("directory_id");

// Returns: DirectoryReadResponse
// {
//   directory: Directory,
//   files: FileInDirectory[],
//   subdirectories: Subdirectory[]
// }
```

#### Update Directory

Updates directory properties (name and/or parent directory).

```typescript
const message = await sdk.directory.update("directory_id", {
  name: "New Name",
  directory_id: "new_parent_directory_id", // optional
});

// Returns: Success message string
```

#### Delete Directory

Deletes a directory and all its contents.

```typescript
const message = await sdk.directory.delete("directory_id");

// Returns: Success message string
```

#### Rename Directory

Renames a directory with a new name.

```typescript
const message = await sdk.directory.rename({
  directoryId: "directory_id",
  name: "New Directory Name",
});

// Returns: Success message string
```

#### Move Directory

Moves a directory to a new parent directory.

```typescript
const message = await sdk.directory.move({
  directoryId: "directory_id",
  parentDirectoryId: "new_parent_directory_id",
});

// Returns: Success message string
```

### File Operations

The `sdk.file` object provides comprehensive file management capabilities.

#### Upload File

Uploads a file to a directory with optional encryption.

```typescript
// Browser environment - using File object
const uploadResult = await sdk.file.upload({
  file: fileInput.files[0], // File object
  directory_id: "target_directory_id", // optional
  passphrase: "MySecret123!", // optional for encryption
});

// Node.js environment - using file path
const uploadResult = await sdk.file.upload({
  file: "/path/to/file.txt", // string file path
  directory_id: "target_directory_id",
  passphrase: "MySecret123!", // required for encryption in Node.js
});

// Using Buffer
const uploadResult = await sdk.file.upload({
  file: Buffer.from("file content"),
  directory_id: "target_directory_id",
});

// Returns: UploadFileResponse
// {
//   content_type: string,
//   directory_id: string,
//   file_id: string,
//   hash: string,
//   name: string,
//   size: number
// }
```

#### Read File

Retrieves file details and metadata.

```typescript
const file = await sdk.file.read({
  fileId: "file_id",
  includeChunks: false, // optional, default: false
});

// Returns: FileData
// {
// id: string;
//  content_type: string;
//  directory_id: string;
//  hash: string;
//  name: string;
//  size: number;
//  is_shared: boolean;
//  is_encrypted: boolean;
//  access: string;
//  recipients: string[];
//  created_at: string;
//  updated_at: string;
// }
```

#### Update File

Updates file properties.

```typescript
const message = await sdk.file.update("file_id", {
  name: "New File Name",
  directory_id: "new_directory_id", // optional
});

// Returns: Success message string
```

#### Delete File

Deletes a file permanently.

```typescript
const message = await sdk.file.delete("file_id");

// Returns: Success message string
```

#### Download File (Authenticated)

Downloads a file using authenticated access (for private or encrypted files).

```typescript
const fileBuffer = await sdk.file.download({
  fileId: "file_id",
  passphrase: "MySecret123!", // required for encrypted files
});

// Returns: Buffer containing file content
```

#### Rename File

Renames a file with a new name.

```typescript
const message = await sdk.file.rename({
  fileId: "file_id",
  name: "new_file_name.txt",
});

// Returns: Success message string
```

#### Move File

Moves a file to a different directory.

```typescript
const message = await sdk.file.move({
  fileId: "file_id",
  directory_id: "target_directory_id",
});

// Returns: Success message string
```

#### Set File Access

Configures file access permissions.

```typescript
// Set to public access
await sdk.file.setAccess({
  fileId: "file_id",
  access: "public",
});

// Set to private access
await sdk.file.setAccess({
  fileId: "file_id",
  access: "private",
});

// Set password protection
await sdk.file.setAccess({
  fileId: "file_id",
  access: "password",
  value: "1234567890",
});

// Set email-based access
await sdk.file.setAccess({
  fileId: "file_id",
  access: "email",
  value: ["user1@example.com", "user2@example.com"], // existing Koneksi accounts
});

// Returns: Success message string
```

#### Generate Temporary Token

Creates a temporary access token for a file.

```typescript
const token = await sdk.file.generateTemporaryToken({
  fileId: "file_id",
  expiresIn: 3600, // optional, default: 24 hours (in seconds)
});

// Returns: GenerateTemporaryTokenResponse
// {
//   duration: "1h0m0s",
//   file_key: "file_1234567890_abc123..."
// }
```

#### Get Preview Link

Gets a permanent preview link for a file.

```typescript
const preview = await sdk.file.getPreviewLink({
  fileId: "file_id",
});

// Returns: GetPreviewLinkResponse
// {
//   previewUrl: "https://app-staging.koneksi.co.kr/preview/file_1234567890"
// }
```

#### Create Temporary Link

Creates a temporary preview link with an expiration time.

```typescript
const tempLink = await sdk.file.createTemporaryLink({
  fileId: "file_id",
  expiresIn: 3600, // optional, default: 24 hours (in seconds)
});

// Returns: CreateTemporaryLinkResponse
// {
//   temporaryPreviewUrl: "https://app-staging.koneksi.co.kr/preview/file_1234567890?token=abc123...",
//   duration: "1h0m0s",
//   file_key: "file_1234567890_abc123..."
// }
```

#### Read File Access (Public)

Gets file access information using the public endpoint.

```typescript
const accessInfo = await sdk.file.publicRead({
  fileId: "file_id",
});

// Returns: ReadFileAccessResponse
// {
//   access: "public" | "private" | "password" | "email",
//   is_encrypted: boolean,
//   id: string,
//   size: number
// }
```

#### Download File (Public)

Downloads a file using public access methods (tokens, passwords, etc.).

```typescript
// Using temporary token
const fileBuffer = await sdk.file.publicDownload({
  fileId: "file_id",
  temporaryToken: "token123",
  passphrase: "MySecret123!", // optional for encrypted files
});

// Using password protection
const fileBuffer = await sdk.file.publicDownload({
  fileId: "file_id",
  shared: {
    access: "password",
    value: "Password123!",
  },
  passphrase: "MySecret123!", // optional for encrypted files
});

// Returns: Buffer containing file content
```

### Health Operations

The `sdk.health` object provides API health monitoring.

#### Check Health

Checks the health status of the API service.

```typescript
const health = await sdk.health.check();

// Returns: HealthResponse
// {
//   data: any,
//   message: string,
//   meta: any,
//   status: string
// }
```

### Peers Operations

The `sdk.peers` object provides peer management capabilities.

#### Fetch Peers

Retrieves available peers for the authenticated client.

```typescript
const peers = await sdk.peers.read();
```

### Profile Operations

The `sdk.profile` object provides access to the current user's profile and settings.

#### Get Current User Profile

Fetches the current user's profile, role, settings, and usage limits.

```typescript
const profile = await sdk.profile.me();

// Returns: ProfileData
// {
//   limit: { limit: number, used: number },
//   organization: any | null,
//   profile: { first_name: string, last_name: string },
//   role: { id: string, name: string },
//   settings: { ... },
//   user: { email: string, id: string, is_org_member: boolean, is_verified: boolean }
// }
```

### Dashboard Operations

The `sdk.dashboard` object provides access to usage and resource metrics for the current account.

#### Collect Dashboard Metrics

Fetches usage statistics such as byte limits, usage, and resource counts.

```typescript
const metrics = await sdk.dashboard.collectMetrics();

// Returns: DashboardMetrics
// {
//   byte_limit: number,
//   byte_usage: number,
//   directory_count: number,
//   file_count: number,
//   service_account_count: number
// }
```

## Complete Examples

### File Management Workflow

```typescript
import KoneksiSDK from "koneksi-ts-sdk";

const sdk = new KoneksiSDK({
  environment: "uat",
  client_id: "your_client_id",
  client_secret: "your_client_secret",
});

async function completeFileWorkflow() {
  try {
    // 1. Check API health
    const health = await sdk.health.check();
    console.log("API Health:", health.status);

    // 2. Create a directory structure
    const documentsDir = await sdk.directory.create({
      name: "Documents",
    });

    const projectsDir = await sdk.directory.create({
      name: "Projects",
      directory_id: documentsDir.id,
    });

    // 3. Upload an encrypted file
    const uploadResult = await sdk.file.upload({
      file: "important_file.pdf,
      directory_id: projectsDir.id,
      passphrase: "MySecret123!",
    });

    // 4. Set file access to password-protected
    await sdk.file.setAccess({
      fileId: uploadResult.file_id,
      access: "password",
      value: "FilePassword123!",
    });

    // 5. Create a temporary preview link
    const tempLink = await sdk.file.createTemporaryLink({
      fileId: uploadResult.file_id,
      expiresIn: 3600, // 1 hour
    });

    // 6. Read directory contents
    const directoryData = await sdk.directory.read(documentsDir.id);
    console.log("Files:", directoryData.files);
    console.log("Subdirectories:", directoryData.subdirectories);

    // 7. Download the file
    const fileBuffer = await sdk.file.download({
      fileId: uploadResult.file_id,
      passphrase: "MySecret123!",
    });

    // 8. Move file to different directory
    await sdk.file.move({
      fileId: uploadResult.file_id,
      directory_id: documentsDir.id,
    });

    // 9. Rename the file
    await sdk.file.rename({
      fileId: uploadResult.file_id,
      name: "Updated File Name.txt",
    });

    // 10. Clean up
    await sdk.file.delete(uploadResult.file_id);
    await sdk.directory.delete(projectsDir.id);
    await sdk.directory.delete(documentsDir.id);

    console.log("Workflow completed successfully!");
  } catch (error) {
    console.error("Error:", error.message);
  }
}
```

### Peer Management

```typescript
async function managePeers() {
  try {
    // Fetch available peers
    const peers = await sdk.peers.read();

    console.log("Available peers:");
    peers.forEach((peer) => {
      console.log(
        `- ${peer.name} (${peer.status}) - Created: ${peer.created_at}`
      );
    });
  } catch (error) {
    console.error("Failed to fetch peers:", error.message);
  }
}
```

### Health Monitoring

```typescript
async function monitorHealth() {
  try {
    const health = await sdk.health.check();

    if (health.status === "success") {
      console.log("✅ API is healthy:", health.message);
    } else {
      console.log("❌ API health check failed:", health.message);
    }
  } catch (error) {
    console.error("Health check error:", error.message);
  }
}
```

## Error Handling

The SDK provides comprehensive error handling with descriptive error messages:

```typescript
try {
  const directory = await sdk.directory.create({
    name: "Test Directory",
  });
} catch (error) {
  console.error("Failed to create directory:", error.message);
  // Error messages are descriptive and actionable
}
```

## TypeScript Support

The SDK is built with TypeScript and provides full type safety:

```typescript
import {
  Directory,
  FileData,
  UploadFileResponse,
  DirectoryReadResponse,
  CreateDirectoryRequest,
  Peer,
  HealthResponse,
} from "koneksi-ts-sdk";

// All parameters and return types are fully typed
const createParams: CreateDirectoryRequest = {
  name: "My Directory",
};

const directory: Directory = await sdk.directory.create(createParams);
const fileData: FileData = await sdk.file.read({ fileId: "file_id" });
const peers: Peer[] = await sdk.peers.read();
const health: HealthResponse = await sdk.health.check();
```

## Development

### Building the SDK

```bash
npm run build
```

### Running Tests

```bash
npm test
```

### Linting

```bash
npm run lint
```

### Formatting

```bash
npm run format
```

## License

MIT
