npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@entangle-matrix/client

v0.1.0

Published

TypeScript/JavaScript SDK for Entangle Matrix API

Downloads

90

Readme

Entangle Matrix SDK for TypeScript/JavaScript

npm version TypeScript License: MIT

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/client

Quick 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 message
  • room_id: Room ID where message was sent
  • timestamp: Message timestamp
  • message: Message content
  • metadata: 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 ID
  • room_id: Room ID
  • mxc_uri: Matrix content URI
  • file_name: Uploaded file name
  • file_size: File size in bytes
  • content_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 conversations
  • CallSampleType.FIRE - Emergency/alert audio for urgent notifications
  • CallSampleType.PERSON - Person-specific voice samples

Returns: MatrixVoiceCall

  • call_id: Call identifier
  • room_id: Room ID
  • target_user: Called user ID
  • state: Call state
  • audio_source: Audio sample type used
  • initiated_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 objects

Get Room Info

const room = await client.getRoomInfo(roomId: string);

Returns: MatrixRoom

  • room_id: Room ID
  • name: Room name (optional)
  • topic: Room topic (optional)
  • avatar_url: Avatar URL (optional)
  • member_count: Number of members
  • is_encrypted: Whether room is encrypted
  • is_direct: Whether room is a direct message
  • metadata: 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:

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.ts

Development

Setup

# Clone repository
git clone https://github.com/qbit-codes/entangle-matrix-client.git
cd entangle-matrix-client

# Install dependencies
pnpm install

Commands

# 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 format

Testing

# Run all tests
pnpm test

# Watch mode
pnpm run test:watch

# Coverage report
pnpm run test:coverage
# Open coverage/index.html to view detailed coverage

Requirements

  • Node.js: >= 18.0.0
  • TypeScript: >= 5.3.0 (for development)

Dependencies

Runtime

  • axios - HTTP client
  • form-data - Multipart form data for file uploads
  • zod - Runtime type validation

Development

  • typescript - TypeScript compiler
  • vitest - Testing framework
  • tsup - 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:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. 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: