@entangle-matrix/client
v0.1.0
Published
TypeScript/JavaScript SDK for Entangle Matrix API
Downloads
90
Maintainers
Readme
Entangle Matrix SDK for TypeScript/JavaScript
A TypeScript/JavaScript SDK for the Entangle Matrix API with full feature parity to the Python client.
Features
- ✅ Full TypeScript support with comprehensive type definitions
- ✅ Promise-based async API for modern JavaScript/TypeScript
- ✅ Node.js 18+ support with ES modules
- ✅ Minimal dependencies (axios, form-data, zod)
- ✅ Comprehensive error handling with typed exceptions
- ✅ Input validation before API calls
- ✅ Full test coverage (64 tests passing)
- ✅ File uploads (images, audio, generic files)
- ✅ Voice calling with multiple audio sample types
- ✅ Room management (create, join, list rooms)
- ✅ Message sending with HTML formatting support
Installation
npm install @entangle-matrix/client
# or
pnpm add @entangle-matrix/client
# or
yarn add @entangle-matrix/clientQuick Start
import { EntangleMatrixClient } from '@entangle-matrix/client';
const client = new EntangleMatrixClient({
baseUrl: 'http://localhost:8000',
apiKey: 'your-api-key', // optional
});
try {
// Check API health
const health = await client.healthCheck();
console.log('API Status:', health);
// Send a text message
const message = await client.sendMessage({
roomId: '!room:example.com',
message: 'Hello from TypeScript SDK!',
});
console.log('Message sent:', message.event_id);
// List joined rooms
const rooms = await client.listRooms();
console.log(`Joined ${rooms.length} rooms`);
} catch (error) {
console.error('Error:', error);
} finally {
await client.close();
}API Reference
Client Initialization
const client = new EntangleMatrixClient({
baseUrl: string; // Required: Entangle API base URL
apiKey?: string; // Optional: API key for authentication
timeout?: number; // Optional: Request timeout in ms (default: 30000)
maxFileSizeMB?: number; // Optional: Max file upload size (default: 10)
});Messaging
Send Text Message
const message = await client.sendMessage({
roomId: string; // Matrix room ID (e.g., "!room:example.com")
message: string; // Plain text message
formattedBody?: string; // Optional: HTML formatted message
formatType?: string; // Optional: Format type (e.g., "org.matrix.custom.html")
});Returns: MatrixMessage
event_id: Event ID of the sent messageroom_id: Room ID where message was senttimestamp: Message timestampmessage: Message contentmetadata: Optional additional metadata
Upload Image
const upload = await client.sendImage({
roomId: string; // Matrix room ID
imagePath: string; // Path to image file
caption?: string; // Optional: Image caption
});Returns: MatrixUpload
event_id: Event IDroom_id: Room IDmxc_uri: Matrix content URIfile_name: Uploaded file namefile_size: File size in bytescontent_type: MIME type
Supported formats: JPG, PNG, GIF, WebP, BMP
Upload Audio
const upload = await client.sendAudio({
roomId: string; // Matrix room ID
audioPath: string; // Path to audio file
caption?: string; // Optional: Audio caption
});Supported formats: MP3, WAV, OGG, M4A, FLAC, AAC
Upload File
const upload = await client.sendFile({
roomId: string; // Matrix room ID
filePath: string; // Path to any file
caption?: string; // Optional: File caption
});Supports any file type (PDFs, documents, archives, etc.)
Voice Calling
import { CallSampleType } from '@entangle-matrix/client';
const call = await client.initiateCall({
roomId: string; // Matrix room ID
targetUser: string; // User ID to call (e.g., "@user:example.com")
sampleType?: CallSampleType; // Audio sample type (default: HUMAN)
autoHangupAfter?: number; // Auto-hangup timeout in seconds (default: 60)
callTimeout?: number; // Call timeout in milliseconds (default: 120000)
});Audio Sample Types:
CallSampleType.HUMAN- Natural human voice for normal conversationsCallSampleType.FIRE- Emergency/alert audio for urgent notificationsCallSampleType.PERSON- Person-specific voice samples
Returns: MatrixVoiceCall
call_id: Call identifierroom_id: Room IDtarget_user: Called user IDstate: Call stateaudio_source: Audio sample type usedinitiated_at: Call initiation timestamp
Room Management
Create Room
const room = await client.createRoom({
name: string; // Room name
topic?: string; // Optional: Room topic
isPublic?: boolean; // Optional: Public room (default: false)
isDirect?: boolean; // Optional: Direct message (default: false)
inviteUsers?: string[]; // Optional: Users to invite
});Join Room
const room = await client.joinRoom(roomIdOrAlias: string);
// Accepts room ID (!room:example.com) or alias (#alias:example.com)List Rooms
const rooms = await client.listRooms();
// Returns array of MatrixRoom objectsGet Room Info
const room = await client.getRoomInfo(roomId: string);Returns: MatrixRoom
room_id: Room IDname: Room name (optional)topic: Room topic (optional)avatar_url: Avatar URL (optional)member_count: Number of membersis_encrypted: Whether room is encryptedis_direct: Whether room is a direct messagemetadata: Additional metadata
Health Check
const health = await client.healthCheck();Error Handling
The SDK provides typed error classes for different failure scenarios:
import {
EntangleMatrixError, // Base error class
AuthenticationError, // 401 - Invalid API key
NotFoundError, // 404 - Resource not found
ValidationError, // 400 - Invalid input
RateLimitError, // 429 - Rate limit exceeded
ServerError, // 500+ - Server errors
NetworkError, // Network/connection failures
} from '@entangle-matrix/client';
try {
await client.sendMessage({ roomId: '!room:example.com', message: 'Hello' });
} catch (error) {
if (error instanceof ValidationError) {
console.error('Invalid input:', error.message);
} else if (error instanceof AuthenticationError) {
console.error('Authentication failed:', error.message);
} else if (error instanceof EntangleMatrixError) {
console.error('API error:', error.message, 'Status:', error.statusCode);
}
}Validation Utilities
The SDK exports utility functions for input validation:
import {
validateRoomId, // Validate Matrix room ID format
validateUserId, // Validate Matrix user ID format
formatFileSize, // Human-readable file size
getContentType, // Get MIME type from file path
isImageFile, // Check if file is an image
isAudioFile, // Check if file is audio
} from '@entangle-matrix/client';
if (!validateRoomId('!room:example.com')) {
console.error('Invalid room ID format');
}Examples
The examples/ directory contains comprehensive usage examples:
- basic-usage.ts - Health checks, messaging, room listing
- file-sharing.ts - Image, audio, and file uploads
- room-management.ts - Creating and managing rooms
- voice-calling.ts - Voice call initiation with different audio types
Running Examples
# Set environment variables
export ENTANGLE_API_URL=http://localhost:8000
export MATRIX_ROOM_ID=!your-room:example.com
export MATRIX_TARGET_USER=@user:example.com
# Run an example
npx tsx examples/basic-usage.tsDevelopment
Setup
# Clone repository
git clone https://github.com/qbit-codes/entangle-matrix-client.git
cd entangle-matrix-client
# Install dependencies
pnpm installCommands
# Build
pnpm run build
# Development build (watch mode)
pnpm run dev
# Run tests
pnpm test
# Run tests with coverage
pnpm test:coverage
# Type checking
pnpm run typecheck
# Lint code
pnpm run lint
# Fix lint issues
pnpm run lint:fix
# Format code
pnpm run formatTesting
# Run all tests
pnpm test
# Watch mode
pnpm run test:watch
# Coverage report
pnpm run test:coverage
# Open coverage/index.html to view detailed coverageRequirements
- Node.js: >= 18.0.0
- TypeScript: >= 5.3.0 (for development)
Dependencies
Runtime
axios- HTTP clientform-data- Multipart form data for file uploadszod- Runtime type validation
Development
typescript- TypeScript compilervitest- Testing frameworktsup- Build tool@biomejs/biome- Linter and formatter
Comparison with Python Client
This TypeScript SDK provides feature parity with the Python client:
| Feature | Python | TypeScript | |---------|--------|------------| | Async/await | ✅ | ✅ | | Type safety | ✅ (type hints) | ✅ (TypeScript) | | Text messaging | ✅ | ✅ | | File uploads | ✅ | ✅ | | Voice calling | ✅ | ✅ | | Room management | ✅ | ✅ | | Error handling | ✅ | ✅ | | Input validation | ✅ | ✅ | | Tests | ✅ pytest | ✅ vitest |
Contributing
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Code Style
- Use TypeScript for all new code
- Follow existing code formatting (enforced by Biome)
- Add tests for new features
- Update documentation as needed
License
MIT © QBit Codes
Links
- GitHub: https://github.com/qbit-codes/entangle-matrix-client
- npm: https://www.npmjs.com/package/@entangle-matrix/client
- Python Client: https://github.com/qbit-codes/entangle-python-client
- Issues: https://github.com/qbit-codes/entangle-matrix-client/issues
Support
For questions, issues, or feature requests:
- Open an issue on GitHub
- Email: [email protected]
