Package Exports
- universal-message
Readme
Universal Message
A universal message communication library for JavaScript/TypeScript that works across different environments including Worker threads, WebSocket, and other communication channels.
Features
- π Universal: Works across different communication channels (Worker threads, WebSocket, etc.)
- π Plugin System: Extensible plugin architecture for custom message encoding/decoding
- π― Type Safe: Full TypeScript support with type definitions
- π¦ Lightweight: Minimal dependencies and small bundle size
- π Bidirectional: Support for both client-server and peer-to-peer communication
- β‘ Promise-based: Modern async/await API with Promise support
Installation
npm install universal-messageyarn add universal-messagepnpm add universal-messageQuick Start
Basic Usage
import { MessageServer, MessageClient } from 'universal-message';
// Server side
const server = new MessageServer({
on: (callback) => {
// Setup message listener (e.g., WebSocket onmessage, Worker onmessage)
worker.onmessage = callback;
},
send: (data) => {
// Setup message sender (e.g., WebSocket send, Worker postMessage)
worker.postMessage(data);
}
});
// Client side
const client = new MessageClient({
on: (callback) => {
// Setup message listener
self.onmessage = callback;
},
send: (data) => {
// Setup message sender
self.postMessage(data);
}
});Worker Thread Example
// main.ts
import { Worker } from 'worker_threads';
import { MessageServer } from 'universal-message';
const worker = new Worker('./worker.js');
const server = new MessageServer({
on: (callback) => worker.on('message', callback),
send: (data) => worker.postMessage(data)
});
// Send a message and wait for response
const result = await server.send('calculate', { a: 10, b: 20 });
console.log(result); // 30
// worker.js
import { parentPort } from 'worker_threads';
import { MessageClient } from 'universal-message';
const client = new MessageClient({
on: (callback) => parentPort?.on('message', callback),
send: (data) => parentPort?.postMessage(data)
});
// Listen for messages
client.on('calculate', ({ a, b }) => {
return a + b;
});WebSocket Example
// Server side
import { MessageServer } from 'universal-message';
const ws = new WebSocket('ws://localhost:8080');
const server = new MessageServer({
on: (callback) => {
ws.onmessage = (event) => callback(JSON.parse(event.data));
},
send: (data) => {
ws.send(JSON.stringify(data));
}
});
// Client side (similar setup with WebSocket)API Reference
MessageServer
The server-side message handler.
Methods
send<T>(key: string, data?: any, timeout?: number): Promise<T>- Send a message and wait for responseon(key: string, callback: Function)- Listen for messagesonce(key: string, callback: Function)- Listen for a message onceoff(key: string)- Remove message listenernewClass(target: string | Object, data?: any[])- Create a remote class instancestaticClass(target: string | Object)- Access static class methods
MessageClient
The client-side message handler.
Methods
send<T>(key: string, data?: any, timeout?: number): Promise<T>- Send a message and wait for responseon(key: string, callback: Function)- Listen for messagesonce(key: string, callback: Function)- Listen for a message onceoff(key: string)- Remove message listeneraddClass(className: string, target: any)- Register a class for remote access
MessageShared
Base class that provides common functionality for both server and client.
Plugin System
Universal Message supports a plugin system for extending functionality:
import { MessageEcoderPlugin } from 'universal-message';
// Custom plugin
class CustomPlugin {
name = 'custom-plugin';
beforeSend(data) {
// Modify data before sending
return data;
}
afterReceive(data) {
// Process data after receiving
return data;
}
}
// Add plugin
server.addPlugin(new CustomPlugin());Built-in Plugins
- MessageEcoderPlugin: Handles encoding/decoding of complex data types
Remote Class Usage
Universal Message supports remote class instantiation and method calling:
// Server side
class Calculator {
add(a: number, b: number) {
return a + b;
}
multiply(a: number, b: number) {
return a * b;
}
}
// Client side
client.addClass('Calculator', Calculator);
// Server side usage
const calc = await server.newClass('Calculator');
const result = await calc.call('add', 10, 20); // 30TypeScript Support
Universal Message is written in TypeScript and provides full type definitions:
interface CalculationRequest {
a: number;
b: number;
}
interface CalculationResponse {
result: number;
}
// Type-safe message handling
server.on('calculate', (data: CalculationRequest): CalculationResponse => {
return { result: data.a + data.b };
});
const response = await client.send<CalculationResponse>('calculate', { a: 10, b: 20 });Error Handling
try {
const result = await server.send('someMethod', data, 5000); // 5 second timeout
} catch (error) {
console.error('Message failed:', error);
}Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT License. See LICENSE for details.