@bucketos/sdk
v1.0.2
Published
Official TypeScript SDK for BucketOS - Multi-tenant S3-compatible object storage platform
Downloads
10
Maintainers
Readme
@bucketos/sdk
Official TypeScript SDK for BucketOS - Multi-tenant S3-compatible object storage platform.
📦 Installation
npm install @bucketos/sdk
# or
yarn add @bucketos/sdk
# or
pnpm add @bucketos/sdk🚀 Quick Start
import { BucketOS } from '@bucketos/sdk';
// Initialize client
const client = new BucketOS({
apiUrl: 'https://api.bucketos.com',
token: 'your-jwt-token'
});
// List buckets
const buckets = await client.buckets.list();
// Create a bucket
const newBucket = await client.buckets.create({
name: 'my-bucket',
region: 'us-east-1'
});📚 API Reference
Authentication
// Get JWT token first by logging in via Portal or CLI
const client = new BucketOS({
apiUrl: 'https://api.bucketos.com',
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
timeout: 30000, // optional, default: 30000ms
// Automatic retries are enabled by default for 5xx and network errors (3 retries)
});Buckets
List Buckets
const buckets = await client.buckets.list();Create Bucket
const bucket = await client.buckets.create({
name: 'my-bucket',
region: 'us-east-1', // optional, default: 'ap-southeast-1'
isPublic: false, // optional, default: false
lifecycle: { // optional
prefix: 'logs/',
expireAfterDays: 30
}
});Update Bucket
const updated = await client.buckets.update('bucket-id', {
isPublic: true
});Delete Bucket
await client.buckets.delete('bucket-id');Lifecycle Policies
// Get lifecycle policy
const policy = await client.buckets.getLifecycle('bucket-id');
// Set lifecycle policy
await client.buckets.setLifecycle('bucket-id', {
prefix: 'logs/',
expireAfterDays: 30
});
// Delete lifecycle policy
await client.buckets.deleteLifecycle('bucket-id');Files
List Files
const { files, folders } = await client.files.list('bucket-id', {
prefix: 'folder/', // optional
delimiter: '/', // optional
maxKeys: 1000, // optional
continuationToken: '...' // optional, for pagination
});Upload File (Presigned URL)
// 1. Get presigned URL
const { url } = await client.files.getUploadUrl(
'bucket-id',
'path/to/file.txt',
'text/plain' // optional content-type
);
// 2. Upload file using the URL
await fetch(url, {
method: 'PUT',
body: fileData,
headers: {
'Content-Type': 'text/plain'
}
});Download File (Presigned URL)
// 1. Get presigned URL
const { url } = await client.files.getDownloadUrl('bucket-id', 'path/to/file.txt');
// 2. Download file using the URL
const response = await fetch(url);
const blob = await response.blob();Delete File
await client.files.delete('bucket-id', 'path/to/file.txt');Helper: Upload File (One-step)
// Automatically handles presigned URL generation and upload
await client.files.uploadFile(
'bucket-id',
'path/to/file.txt',
fileData,
'application/pdf' // optional content-type
);Helper: Download File (One-step)
// Automatically handles presigned URL generation and download
const arrayBuffer = await client.files.downloadFile('bucket-id', 'path/to/file.txt');API Keys
List API Keys
const keys = await client.apiKeys.list();Create API Key
const { apiKey, secretKey } = await client.apiKeys.create({
name: 'production-key'
});
// ⚠️ IMPORTANT: secretKey is only shown once! Save it now!
console.log('Access Key:', apiKey.accessKey);
console.log('Secret Key:', secretKey); // Save this securely!Update API Key
const updated = await client.apiKeys.update('key-id', {
name: 'new-name',
active: false // deactivate key
});Delete API Key
await client.apiKeys.delete('key-id');Users
List Users
const users = await client.users.list();Create User
const user = await client.users.create({
email: '[email protected]',
password: 'secure-password',
role: 'developer' // 'tenant_owner' | 'tenant_admin' | 'developer' | 'readonly'
});Update User
const updated = await client.users.update('user-id', {
role: 'tenant_admin'
});Delete User
await client.users.delete('user-id');Invitations
Send Invitation
const invitation = await client.invitations.send({
email: '[email protected]',
role: 'developer'
});
console.log('Invitation URL:', invitation.token);List Invitations
const invitations = await client.invitations.list();Resend Invitation
const updated = await client.invitations.resend('invitation-id');Revoke Invitation
await client.invitations.revoke('invitation-id');Usage & Quota
Get Quota Status
const quota = await client.usage.getQuota();
console.log('Storage:', quota.storage.used, '/', quota.storage.quota);
console.log('Bandwidth:', quota.bandwidth.percent, '%');
console.log('Requests:', quota.requests.exceeded ? 'EXCEEDED' : 'OK');Get Usage Summary
const summary = await client.usage.getSummary();
console.log('Storage:', summary.storage.formatted);
console.log('Bandwidth:', summary.bandwidth.formatted);
console.log('Requests:', summary.requests);Get Daily Usage
const usage = await client.usage.getDaily(30); // last 30 days
usage.forEach(day => {
console.log(day.date, day.storage, day.bandwidth, day.requests);
});Billing
List Plans
const plans = await client.billing.listPlans();
plans.forEach(plan => {
console.log(plan.name, '$' + plan.price + '/month');
});Get Subscription
const subscription = await client.billing.getSubscription();
if (subscription) {
console.log('Current plan:', subscription.plan.name);
console.log('Status:', subscription.status);
}List Invoices
const invoices = await client.billing.listInvoices();
invoices.forEach(invoice => {
console.log(invoice.invoiceNumber, invoice.status, '$' + invoice.amount);
});Cancel Subscription
const subscription = await client.billing.cancelSubscription();
console.log('Canceled, ends at:', subscription.currentPeriodEnd);Reactivate Subscription
const subscription = await client.billing.reactivateSubscription();
console.log('Reactivated!');Audit Logs
List Audit Logs
const logs = await client.auditLogs.list({
limit: 50,
offset: 0,
action: 'CREATE_BUCKET', // optional
userId: 'user-id', // optional
startDate: '2024-01-01', // optional
endDate: '2024-12-31' // optional
});
logs.forEach(log => {
console.log(log.createdAt, log.action, log.resource, log.userId);
});🔧 Error Handling
import { BucketOS, BucketOSError } from '@bucketos/sdk';
try {
const bucket = await client.buckets.create({ name: 'invalid name!' });
} catch (error) {
if (error instanceof BucketOSError) {
console.error('Status:', error.statusCode);
console.error('Errors:', error.errors);
error.errors.forEach(err => {
console.error(`[${err.code}] ${err.message}`);
});
}
}💡 Advanced Usage
Custom Request
// Make custom API requests not yet covered by SDK
const response = await client.request({
method: 'GET',
url: '/api/tenant/custom-endpoint'
});TypeScript Types
import type {
Bucket,
User,
APIKey,
Invitation,
QuotaStatus,
BucketOSConfig
} from '@bucketos/sdk';
const config: BucketOSConfig = {
apiUrl: 'https://api.bucketos.com',
token: 'your-token',
timeout: 60000
};
const bucket: Bucket = await client.buckets.create({ name: 'mybucket' });📖 Examples
Complete Upload Flow
import { BucketOS } from '@bucketos/sdk';
import fs from 'fs';
const client = new BucketOS({
apiUrl: 'https://api.bucketos.com',
token: process.env.BUCKETOS_TOKEN!
});
async function uploadFile(bucketId: string, filePath: string, key: string) {
// Read file
const fileData = fs.readFileSync(filePath);
// Get presigned URL
const { url } = await client.files.getUploadUrl(bucketId, key);
// Upload to presigned URL
await fetch(url, {
method: 'PUT',
body: fileData
});
console.log('✓ Uploaded:', key);
}
await uploadFile('bucket-id', './document.pdf', 'docs/document.pdf');Quota Monitoring
async function checkQuota() {
const quota = await client.usage.getQuota();
if (quota.storage.exceeded) {
console.warn('⚠️ Storage quota exceeded!');
}
if (quota.storage.percent > 80) {
console.warn('⚠️ Storage usage >80%');
}
if (quota.bandwidth.exceeded) {
console.warn('⚠️ Bandwidth quota exceeded!');
}
}
await checkQuota();🤝 Contributing
Contributions welcome! Please see CONTRIBUTING.md
📄 License
MIT License - see LICENSE
🔗 Links
- Documentation: https://docs.bucketos.com
- API Reference: https://api.bucketos.com/docs
- GitHub: https://github.com/pictor-network/bucketos
- Issues: https://github.com/pictor-network/bucketos/issues
Made with ❤️ by the BucketOS Team
