Skip to main content

Efficient Inter-Process Communication Framework with hierarchical application and channel management

Project description

IPC Framework JS

npm version License: MIT

A powerful, TypeScript-first Inter-Process Communication framework for JavaScript/TypeScript applications. Works seamlessly in both Node.js (backend) and browser (frontend) environments using WebSockets.

๐Ÿš€ Features

  • ๐ŸŒ Universal: Works in both Node.js and browser environments
  • ๐Ÿ“ TypeScript First: Full TypeScript support with comprehensive type definitions
  • ๐Ÿ”„ Real-time: WebSocket-based communication for instant message delivery
  • ๐Ÿ—๏ธ Hierarchical: Organized by applications โ†’ channels โ†’ messages
  • ๐Ÿ“ก Multiple Message Types: Request/Response, Pub/Sub, Notifications
  • ๐Ÿ”— Auto-reconnection: Built-in reconnection logic with exponential backoff
  • ๐Ÿ’— Heartbeat: Keep-alive mechanism to maintain connections
  • ๐ŸŽฏ Type-safe: Fully typed APIs for better developer experience
  • ๐Ÿ“ฆ Dual Package: Separate builds for Node.js and browsers

๐Ÿ“ฆ Installation

npm install ipc-framework-js

For Node.js usage, you'll also need the WebSocket library:

npm install ws
npm install --save-dev @types/ws  # If using TypeScript

๐ŸŽฏ Quick Start

Server (Node.js)

import { IPCServer, MessageType } from 'ipc-framework-js';

// Create server
const server = new IPCServer({
  host: 'localhost',
  port: 8888,
  maxConnections: 100
});

// Create application and channels
const chatApp = server.createApplication('chat_app', 'Chat Application');
const generalChannel = chatApp.createChannel('general');

// Set up message handler
generalChannel.setHandler(MessageType.REQUEST, (message) => {
  console.log('Received message:', message.payload);
  
  // Broadcast to all subscribers
  server.handlePublish(message, generalChannel);
});

// Start server
await server.start();
console.log('๐Ÿš€ IPC Server started on ws://localhost:8888');

Client (Node.js)

import { IPCClient, MessageType } from 'ipc-framework-js';

// Create client
const client = new IPCClient('chat_app', {
  host: 'localhost',
  port: 8888,
  reconnectAttempts: 5
});

// Connect
await client.connect();

// Subscribe to messages
client.subscribe('general', (message) => {
  console.log('Received:', message.payload);
});

// Send message
client.request('general', {
  username: 'john',
  text: 'Hello World!'
});

Client (Browser)

<!DOCTYPE html>
<html>
<head>
  <title>IPC Client</title>
  <script src="./node_modules/ipc-framework-js/dist/browser/index.js"></script>
</head>
<body>
  <script>
    // Create client
    const client = new IPCFramework.IPCClient('chat_app', {
      host: 'localhost',
      port: 8888
    });

    // Connect and use
    client.connect().then(() => {
      console.log('Connected!');
      
      // Subscribe to messages
      client.subscribe('general', (message) => {
        console.log('Received:', message.payload);
      });
      
      // Send message
      client.request('general', {
        username: 'browser_user',
        text: 'Hello from browser!'
      });
    });
  </script>
</body>
</html>

๐Ÿ“š API Reference

Server API

IPCServer

class IPCServer {
  constructor(options?: IServerOptions)
  
  // Server lifecycle
  async start(): Promise<void>
  async stop(): Promise<void>
  
  // Application management
  createApplication(appId: string, name?: string): Application
  getApplication(appId: string): Application | undefined
  removeApplication(appId: string): boolean
  
  // Statistics
  getStats(): IServerStats
  listApplications(): Map<string, any>
}

Server Options

interface IServerOptions {
  host?: string;          // Default: 'localhost'
  port?: number;          // Default: 8888
  maxConnections?: number; // Default: 100
  heartbeatInterval?: number; // Default: 30000ms
}

Client API

IPCClient

class IPCClient {
  constructor(appId: string, options?: IClientOptions)
  
  // Connection management
  async connect(): Promise<boolean>
  disconnect(): void
  isConnected(): boolean
  
  // Messaging
  subscribe(channelId: string, handler?: MessageHandler): boolean
  unsubscribe(channelId: string): boolean
  request(channelId: string, data: any): string
  notify(channelId: string, data: any): string
  publish(channelId: string, data: any): string
  
  // Advanced messaging
  async sendRequest(channelId: string, data: any, timeout?: number): Promise<Message | null>
  sendRequestAsync(channelId: string, data: any, callback: Function): string
  
  // Utilities
  async ping(timeout?: number): Promise<boolean>
  getConnectionInfo(): IConnectionInfo
  
  // Event handlers
  onConnected(handler: () => void): void
  onDisconnected(handler: () => void): void
  onError(handler: (error: Error) => void): void
}

Client Options

interface IClientOptions {
  host?: string;              // Default: 'localhost'
  port?: number;              // Default: 8888
  connectionTimeout?: number;  // Default: 10000ms
  reconnectAttempts?: number;  // Default: 5
  reconnectDelay?: number;     // Default: 1000ms
  heartbeatInterval?: number;  // Default: 30000ms
}

Message Types

enum MessageType {
  REQUEST = 'request',         // Request-response pattern
  RESPONSE = 'response',       // Response to a request
  NOTIFICATION = 'notification', // One-way message
  SUBSCRIBE = 'subscribe',     // Subscribe to channel
  UNSUBSCRIBE = 'unsubscribe', // Unsubscribe from channel
  PUBLISH = 'publish'          // Publish to subscribers
}

Core Classes

Message

class Message {
  readonly messageId: string;
  readonly appId: string;
  readonly channelId: string;
  readonly messageType: MessageType;
  readonly payload: any;
  readonly timestamp: number;
  readonly replyTo?: string;
  
  // Serialization
  toJSON(): string
  toObject(): IMessage
  
  // Static methods
  static fromJSON(json: string): Message
  static fromObject(data: IMessage): Message
  
  // Utility methods
  createResponse(payload: any): Message
  isResponse(): boolean
  isRequest(): boolean
  // ... more utility methods
}

Application

class Application {
  readonly appId: string;
  readonly name: string;
  readonly createdAt: number;
  
  // Channel management
  createChannel(channelId: string): Channel
  getChannel(channelId: string): Channel | undefined
  removeChannel(channelId: string): boolean
  listChannels(): string[]
  
  // Statistics
  getStats(): IApplicationStats
  getTotalConnectionCount(): number
}

Channel

class Channel {
  readonly channelId: string;
  readonly appId: string;
  readonly createdAt: number;
  
  // Subscriber management
  addSubscriber(connectionId: string): void
  removeSubscriber(connectionId: string): boolean
  getSubscribers(): string[]
  
  // Message handling
  setHandler(messageType: MessageType, handler: MessageHandler): void
  removeHandler(messageType: MessageType): boolean
  executeHandler(message: Message): Promise<boolean>
}

๐Ÿ—๏ธ Architecture

The IPC Framework follows a hierarchical structure:

Server
โ”œโ”€โ”€ Application (chat_app)
โ”‚   โ”œโ”€โ”€ Channel (general)
โ”‚   โ”œโ”€โ”€ Channel (tech_talk)
โ”‚   โ””โ”€โ”€ Channel (random)
โ”œโ”€โ”€ Application (file_share)
โ”‚   โ”œโ”€โ”€ Channel (upload)
โ”‚   โ””โ”€โ”€ Channel (download)
โ””โ”€โ”€ Application (monitoring)
    โ”œโ”€โ”€ Channel (metrics)
    โ””โ”€โ”€ Channel (alerts)

Message Flow

  1. Client connects to server with an appId
  2. Client subscribes to channels within that application
  3. Messages are routed based on appId โ†’ channelId
  4. Handlers process messages based on message type
  5. Responses/broadcasts are sent back to relevant subscribers

๐Ÿ› ๏ธ Development

Building

# Install dependencies
npm install

# Build for all environments
npm run build

# Build for specific environments
npm run build:node      # Node.js build
npm run build:browser   # Browser build
npm run build:types     # TypeScript declarations

Development Mode

# Watch mode for development
npm run dev

# Run examples
npm run example:server    # Start example server
npm run example:chat     # Start chat client
npm run example:browser  # Start browser demo

Testing

# Run tests
npm test

# Watch mode
npm run test:watch

๐Ÿ“‹ Examples

Chat Application

Complete chat application with multiple channels:

  • Server: examples/node/server.js
  • Client: examples/node/chat-client.js
  • Browser: examples/browser/index.html

File Sharing

File upload/download with progress tracking:

# Terminal 1: Start server
npm run example:server

# Terminal 2: Start file client
node examples/node/file-client.js

System Monitoring

Real-time metrics and alerting:

# Start monitoring client
node examples/node/monitoring-client.js

๐ŸŒ Browser Usage

ES Modules (Modern)

<script type="module">
  import { IPCClient } from './node_modules/ipc-framework-js/dist/browser/index.esm.js';
  
  const client = new IPCClient('my_app');
  // Use client...
</script>

UMD (Universal)

<script src="./node_modules/ipc-framework-js/dist/browser/index.js"></script>
<script>
  const client = new IPCFramework.IPCClient('my_app');
  // Use client...
</script>

With Bundlers

Works with Webpack, Rollup, Vite, etc.:

import { IPCClient } from 'ipc-framework-js';

// Bundler will automatically use browser build
const client = new IPCClient('my_app');

๐Ÿ”ง Configuration

TypeScript Configuration

{
  "compilerOptions": {
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  }
}

Environment Detection

The library automatically detects the environment and uses appropriate WebSocket implementation:

  • Node.js: Uses ws package
  • Browser: Uses native WebSocket

๐Ÿค Contributing

  1. Fork the repository
  2. Create feature branch: git checkout -b feature-name
  3. Commit changes: git commit -am 'Add feature'
  4. Push to branch: git push origin feature-name
  5. Submit pull request

๐Ÿ“„ License

MIT License - see LICENSE file for details.

๐Ÿ”— Links

๐Ÿ™ Acknowledgments

Inspired by modern real-time communication needs and built with developer experience in mind.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ipc_framework-1.0.0.tar.gz (35.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ipc_framework-1.0.0-py3-none-any.whl (28.1 kB view details)

Uploaded Python 3

File details

Details for the file ipc_framework-1.0.0.tar.gz.

File metadata

  • Download URL: ipc_framework-1.0.0.tar.gz
  • Upload date:
  • Size: 35.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.4

File hashes

Hashes for ipc_framework-1.0.0.tar.gz
Algorithm Hash digest
SHA256 533d7aba974e457c4f9231b774e9ac17f84550d963e8f0d3529714d8c9a873e8
MD5 f70da286b922fbf189190aabc01ff67f
BLAKE2b-256 fff46e6e85b5375e60cc1fb026189f41ebb258c96dd243e47722a11dac4e4538

See more details on using hashes here.

File details

Details for the file ipc_framework-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: ipc_framework-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 28.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.4

File hashes

Hashes for ipc_framework-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 915212a242df1a8883529c4fa1fa83a986c169582be5387237d2303628a63baa
MD5 259fe4601de9292b592ac5d379a9da0a
BLAKE2b-256 e7e3e8e1ee60ba6523302be538bf1666b7a33c1906c203b01b417d13bc3bfd4f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page