senraa-js-sdk
v1.0.3
Published
JavaScript SDK for Senraa platform
Maintainers
Readme
Senraa JavaScript SDK
A framework-agnostic JavaScript SDK for try-on solutions. Pass a user image and a product (garment) image; the SDK sends them to the try-on API and returns the composed result to your app.
Features
- ✅ Framework-agnostic (works with React, Vue, Angular, vanilla JS, Node.js)
- ✅ TypeScript support
- ✅ Simple API
- ✅ Error handling
- ✅ Configurable timeouts
- ✅ Zero dependencies (except axios)
Installation
npm install senraa-js-sdkor
yarn add senraa-js-sdkor
pnpm add senraa-js-sdkQuick Start
Basic Usage
import { SenraaSDK } from 'senraa-js-sdk';
// Initialize the SDK
const sdk = new SenraaSDK({
apiKey: 'your-api-key-here', // Required
baseUrl: 'https://api.senraa.com', // Optional, default: https://api.senraa.com
timeout: 30000, // Optional, default: 30000ms (30 seconds)
});
// Process try-on
const result = await sdk.tryOn({
userImage: 'https://example.com/user-photo.jpg',
garmentImage: 'https://example.com/garment.png',
});
// Handle response
if (result.success) {
console.log('Result image:', result.data.resultImageUrl);
} else {
console.error('Error:', result.error.message);
}Usage Examples
Try-On with Options
import { SenraaSDK } from 'senraa-js-sdk';
const sdk = new SenraaSDK({ apiKey: 'your-api-key' });
const result = await sdk.tryOn({
userImage: 'https://example.com/user.jpg',
garmentImage: 'https://example.com/garment.png',
options: {
scale: 1.0, // Scale factor (default: 1.0)
xOffset: 0, // Horizontal offset (default: 0)
yOffset: 0, // Vertical offset (default: 0)
opacity: 1.0, // Opacity (default: 1.0)
},
});
if (result.success) {
// Display the result image
const resultImageUrl = result.data.resultImageUrl;
console.log('Try-on result:', resultImageUrl);
}React Example
import { useState } from 'react';
import { SenraaSDK } from 'senraa-js-sdk';
function TryOnComponent() {
const [sdk] = useState(() => new SenraaSDK({ apiKey: 'your-api-key' }));
const [result, setResult] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleTryOn = async () => {
setLoading(true);
setError(null);
const response = await sdk.tryOn({
userImage: 'https://example.com/user.jpg',
garmentImage: 'https://example.com/garment.png',
});
if (response.success) {
setResult(response.data.resultImageUrl);
} else {
setError(response.error.message);
}
setLoading(false);
};
return (
<div>
<button onClick={handleTryOn} disabled={loading}>
{loading ? 'Processing...' : 'Try On'}
</button>
{error && <p style={{ color: 'red' }}>Error: {error}</p>}
{result && <img src={result} alt="Try-on result" />}
</div>
);
}Vue Example
<script setup lang="ts">
import { ref } from 'vue';
import { SenraaSDK } from 'senraa-js-sdk';
const sdk = new SenraaSDK({ apiKey: 'your-api-key' });
const result = ref<string | null>(null);
const loading = ref(false);
const error = ref<string | null>(null);
const handleTryOn = async () => {
loading.value = true;
error.value = null;
const response = await sdk.tryOn({
userImage: 'https://example.com/user.jpg',
garmentImage: 'https://example.com/garment.png',
});
if (response.success) {
result.value = response.data.resultImageUrl;
} else {
error.value = response.error.message;
}
loading.value = false;
};
</script>
<template>
<div>
<button @click="handleTryOn" :disabled="loading">
{{ loading ? 'Processing...' : 'Try On' }}
</button>
<p v-if="error" style="color: red">Error: {{ error }}</p>
<img v-if="result" :src="result" alt="Try-on result" />
</div>
</template>Vanilla JavaScript Example
import { SenraaSDK } from 'senraa-js-sdk';
const sdk = new SenraaSDK({ apiKey: 'your-api-key' });
document.getElementById('tryOnBtn').addEventListener('click', async () => {
const userImage = document.getElementById('userImage').value;
const garmentImage = document.getElementById('garmentImage').value;
const result = await sdk.tryOn({
userImage,
garmentImage,
});
if (result.success) {
document.getElementById('result').src = result.data.resultImageUrl;
} else {
alert('Error: ' + result.error.message);
}
});Node.js Example
const { SenraaSDK } = require('senraa-js-sdk');
const sdk = new SenraaSDK({ apiKey: 'your-api-key' });
async function processTryOn() {
const result = await sdk.tryOn({
userImage: 'https://example.com/user.jpg',
garmentImage: 'https://example.com/garment.png',
});
if (result.success) {
console.log('Result image URL:', result.data.resultImageUrl);
} else {
console.error('Error:', result.error.message);
}
}
processTryOn();Configuration
SenraaConfig
interface SenraaConfig {
apiKey: string; // Required - Your API key
baseUrl?: string; // Optional - API base URL (default: 'https://api.senraa.com')
timeout?: number; // Optional - Request timeout in ms (default: 30000)
}API Reference
tryOn(payload: TryOnRequest): Promise<ApiResponse<TryOnResponse>>
Process a try-on request with user and garment images.
Parameters:
interface TryOnRequest {
userImage: string; // URL to user photo
garmentImage: string; // URL to garment image (PNG with transparency preferred)
options?: TryOnOptions; // Optional positioning options
}
interface TryOnOptions {
scale?: number; // Scale factor (default: 1.0)
xOffset?: number; // Horizontal offset (default: 0)
yOffset?: number; // Vertical offset (default: 0)
opacity?: number; // Opacity (default: 1.0)
}Returns:
interface ApiResponse<TryOnResponse> {
success: boolean;
data?: TryOnResponse;
error?: {
code: string;
message: string;
};
}
interface TryOnResponse {
resultImageUrl: string; // URL of the composed result image
}getHttpService(): HttpService
Get the underlying HTTP service instance for advanced usage.
Response Format
All API responses follow this structure:
{
success: boolean;
data?: T; // Present when success is true
error?: { // Present when success is false
code: string;
message: string;
};
}Success Response
{
success: true,
data: {
resultImageUrl: 'https://example.com/result.jpg'
}
}Error Response
{
success: false,
error: {
code: 'NETWORK_ERROR',
message: 'Network request failed'
}
}Error Handling
The SDK provides structured error responses. Always check the success field before accessing data:
const result = await sdk.tryOn({
userImage: 'https://example.com/user.jpg',
garmentImage: 'https://example.com/garment.png',
});
if (result.success) {
// Handle success
console.log(result.data.resultImageUrl);
} else {
// Handle error
console.error('Error code:', result.error.code);
console.error('Error message:', result.error.message);
}Error Codes
| Code | Description |
|------|-------------|
| INVALID_KEY | API key is invalid or revoked |
| SUBSCRIPTION_EXPIRED | Subscription has expired |
| SUBSCRIPTION_SUSPENDED | Subscription is suspended |
| USAGE_LIMIT_EXCEEDED | Monthly usage limit reached |
| NETWORK_ERROR | Network request failed |
| TIMEOUT | Request timeout |
| INVALID_IMAGE | Invalid image format/URL |
| API_ERROR | Backend API error |
Troubleshooting
Common Issues
1. "API key is required" error
- Ensure you're passing the
apiKeyin the configuration - Check that your API key is valid and not expired
2. Network errors
- Verify your internet connection
- Check that the
baseUrlis correct - Ensure the API endpoint is accessible
3. Timeout errors
- Increase the
timeoutvalue in the configuration - Check your network connection speed
- Verify the API server is responding
4. Invalid image errors
- Ensure image URLs are accessible (public URLs or signed URLs)
- Verify image formats are supported (JPG, PNG)
- Check that images are not corrupted
5. TypeScript errors
- Ensure you have TypeScript installed:
npm install -D typescript - Check that your TypeScript version is compatible (>= 4.0)
Requirements
- Node.js >= 16.0.0
- npm, yarn, or pnpm
Development
Prerequisites
- Node.js >= 16
- npm, yarn, or pnpm
Setup
npm installBuild
npm run buildDevelopment Mode
npm run devTesting
npm testLinting
npm run lint
npm run lint:fixPublishing
Prerequisites
Ensure you're logged into npm:
npm loginVerify your package name is available on npm (or you have access to the scoped package)
Build and Verify
Before publishing, ensure everything is built and tested:
npm run build
npm testVersion Management
Update the version before publishing:
# Patch version (1.0.0 -> 1.0.1)
npm run version:patch
# Minor version (1.0.0 -> 1.1.0)
npm run version:minor
# Major version (1.0.0 -> 2.0.0)
npm run version:majorPublishing
Publish to npm:
# Publish as public package
npm run publish:public
# Or publish as beta version
npm run publish:beta
# Or use npm publish directly
npm publishThe prepublishOnly script will automatically:
- Run type checking
- Run linting
- Run tests
- Build the package
Publishing Checklist
- [ ] Update version in
package.json - [ ] Ensure all tests pass
- [ ] Build succeeds without errors
- [ ] Verify
dist/folder contains all necessary files - [ ] Test the package locally:
npm packand install in a test project - [ ] Run verification:
npm run verify - [ ] Publish to npm
Project Structure
senraa-js-sdk/
├── src/
│ ├── __tests__/ # Test files
│ ├── sdk/ # SDK main class
│ │ ├── SenraaSDK.ts # Main SDK class
│ │ └── index.ts # SDK exports
│ ├── services/ # Business logic services
│ │ ├── http.service.ts # Axios HTTP client
│ │ ├── try-on.service.ts # Try-on API service
│ │ └── index.ts # Services exports
│ ├── config/ # Configuration
│ │ ├── endpoints.ts # API endpoints constants
│ │ ├── constants.ts # SDK constants
│ │ └── index.ts # Config exports
│ ├── errors/ # Error handling
│ │ ├── errors.ts # Custom error classes
│ │ ├── error-handler.ts # Error handler
│ │ └── index.ts # Errors exports
│ ├── types/ # TypeScript type definitions
│ │ └── index.ts # Type definitions
│ └── index.ts # Main entry point
├── docs/ # Documentation files
├── dist/ # Build output (generated)
├── scripts/ # Build scripts
├── package.json
├── tsconfig.json
├── rollup.config.js
└── README.mdLicense
MIT
