JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 1269
  • Score
    100M100P100Q120248F
  • License MIT

A universal message communication library for JavaScript/TypeScript that works across different environments including Worker threads, WebSocket, and other communication channels

Package Exports

  • universal-message

Readme

Universal Message

English | δΈ­ζ–‡

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-message
yarn add universal-message
pnpm add universal-message

Quick 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 response
  • on(key: string, callback: Function) - Listen for messages
  • once(key: string, callback: Function) - Listen for a message once
  • off(key: string) - Remove message listener
  • newClass(target: string | Object, data?: any[]) - Create a remote class instance
  • staticClass(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 response
  • on(key: string, callback: Function) - Listen for messages
  • once(key: string, callback: Function) - Listen for a message once
  • off(key: string) - Remove message listener
  • addClass(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); // 30

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