JSPM

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

ContextPlex JavaScript/TypeScript SDK - Realtime state synchronization and file sync for developers

Package Exports

  • @contextplex/sdk-js

Readme

ContextPlex JavaScript/TypeScript SDK

npm version License: MIT TypeScript

Official SDK for ContextPlex - realtime state synchronization and file sync for developers.

ContextPlex enables seamless state sharing across development environments, making it easy to keep configuration files, environment variables, and application state synchronized across multiple machines and team members.

Features

  • 🚀 Realtime State Sync - Bidirectional state synchronization via WebSocket
  • 📁 File Synchronization - Automatic .env and JSON file syncing across environments
  • 🔐 API Key Authentication - Secure, isolated namespaces per API key
  • 🔄 Auto Reconnection - Exponential backoff with automatic reconnection
  • 📦 TypeScript Support - Full type definitions and IntelliSense support
  • 🌐 Cross-Platform - Works in Node.js, browser, and any JavaScript environment
  • 🎯 Simple API - Clean, intuitive API with event-driven architecture

Installation

npm install @contextplex/sdk-js
# or
yarn add @contextplex/sdk-js
# or
pnpm add @contextplex/sdk-js

Quick Start

Basic State Synchronization

import { createClient } from '@contextplex/sdk-js';

// Create client (server URL configured via STATEMESH_SERVER_URL environment variable)
const client = createClient({
  namespace: 'my-project',
  apiKey: 'your-api-key'
});

// Connect to ContextPlex
await client.connect();

// Listen for state changes
client.on('change', (event) => {
  console.log(`State changed in ${event.namespace}:`, event.ops);
});

// Set a value
await client.set('my-project', 'user.name', 'Alice');

// Get current state
const state = await client.getState('my-project');
console.log('Current state:', state);

// Delete a value
await client.delete('my-project', 'user.name');

File Synchronization (.env files)

import { createClient, createFileSync } from '@contextplex/sdk-js';

// Create client
const client = createClient({
  namespace: 'dev-environment',
  apiKey: 'dev-api-key'
});

// Create file sync instance
const fileSync = createFileSync({
  client,
  namespace: 'dev-environment',
  baseDir: process.cwd()
});

// Connect
await fileSync.connect();

// Start syncing .env file
await fileSync.syncEnvFile({
  path: '.env',
  prefix: 'env.' // Optional, defaults to 'env.'
});

// Listen for sync events
fileSync.on('synced', (event) => {
  console.log(`${event.type} file synced: ${event.path} (${event.direction})`);
});

File Synchronization (JSON files)

// Sync a JSON configuration file
await fileSync.syncJsonFile({
  path: 'config.json',
  prefix: 'config.', // Optional, defaults to 'json.'
  flatten: true      // Optional, flatten nested objects (default: true)
});

API Reference

createClient(options: StateMeshOptions): StateMeshClient

Creates a new ContextPlex client instance.

Parameters:

  • options.namespace (string, required) - Namespace identifier for state isolation
  • options.apiKey (string, required) - API key for authentication

Returns: StateMeshClient instance

Example:

const client = createClient({
  namespace: 'my-project',
  apiKey: 'my-api-key'
});

StateMeshClient

Main client class for ContextPlex connections.

Methods

connect(): Promise<void>

Connects to the ContextPlex server.

await client.connect();
set(namespace: string, path: string, value: unknown): Promise<void>

Sets a value at a dot-separated path.

await client.set('my-project', 'user.name', 'Alice');
await client.set('my-project', 'cart.items', [{ id: 1, qty: 2 }]);
delete(namespace: string, path: string): Promise<void>

Deletes a value at a dot-separated path.

await client.delete('my-project', 'user.name');
pushOps(namespace: string, ops: StateOp[]): Promise<void>

Pushes multiple state operations atomically.

await client.pushOps('my-project', [
  { path: 'user.name', op: 'set', value: 'Alice', ts: Date.now() * 1_000_000, session_id: '...', seq: 1 },
  { path: 'user.email', op: 'set', value: 'alice@example.com', ts: Date.now() * 1_000_000, session_id: '...', seq: 2 }
]);
getState(namespace?: string): Promise<Record<string, unknown>>

Gets the current state for a namespace.

const state = await client.getState('my-project');
// or use default namespace
const defaultState = await client.getState();
snapshot(namespace: string, options?: SnapshotOptions): Promise<string>

Creates a snapshot of the current state.

const snapshotId = await client.snapshot('my-project', { tag: 'checkpoint-1' });
disconnect(): void

Disconnects from the server.

client.disconnect();

Events

'connected'

Emitted when connection is established.

client.on('connected', () => {
  console.log('Connected to ContextPlex');
});
'disconnected'

Emitted when connection is closed.

client.on('disconnected', () => {
  console.log('Disconnected from ContextPlex');
});
'change'

Emitted when state changes (from other clients).

client.on('change', (event: ChangeEvent) => {
  console.log(`Namespace ${event.namespace} changed:`, event.ops);
});
'state'

Emitted when receiving state snapshot.

client.on('state', (event: StateEvent) => {
  console.log(`State for ${event.namespace}:`, event.state);
});
'ack'

Emitted when operation is acknowledged.

client.on('ack', (event: AckEvent) => {
  console.log(`Ack: ${event.namespace}, sequence: ${event.last_sequence}`);
});
'error'

Emitted on errors.

client.on('error', (error: Error) => {
  console.error('ContextPlex error:', error);
});

createFileSync(options: FileSyncOptions): FileSync

Creates a new file synchronization instance.

Parameters:

  • options.client (StateMeshClient, required) - ContextPlex client instance
  • options.namespace (string, required) - Namespace for syncing
  • options.baseDir (string, optional) - Base directory to watch (default: process.cwd())

Returns: FileSync instance

FileSync

Manages bidirectional synchronization of .env and JSON files.

Methods

syncEnvFile(config: EnvFileConfig): Promise<void>

Starts syncing a .env file.

Parameters:

  • config.path (string, required) - Path to .env file (relative to baseDir)
  • config.prefix (string, optional) - StateMesh path prefix (default: 'env.')
await fileSync.syncEnvFile({
  path: '.env',
  prefix: 'env.'
});
syncJsonFile(config: JsonFileConfig): Promise<void>

Starts syncing a JSON file.

Parameters:

  • config.path (string, required) - Path to JSON file (relative to baseDir)
  • config.prefix (string, optional) - StateMesh path prefix (default: 'json.')
  • config.flatten (boolean, optional) - Flatten nested JSON (default: true)
await fileSync.syncJsonFile({
  path: 'config.json',
  prefix: 'config.',
  flatten: true
});
connect(): Promise<void>

Connects to ContextPlex.

await fileSync.connect();
stop(): Promise<void>

Stops watching files and disconnects.

await fileSync.stop();

Events

'syncing'

Emitted when file sync starts.

fileSync.on('syncing', (event: SyncingEvent) => {
  console.log(`Syncing ${event.type} file: ${event.path}`);
});
'synced'

Emitted when file sync completes.

fileSync.on('synced', (event: SyncedEvent) => {
  console.log(`${event.type} file synced: ${event.path} (${event.direction})`);
});
'connected'

Emitted when connected to ContextPlex.

'stopped'

Emitted when sync stops.

'error'

Emitted on errors.

Configuration

Environment Variables

  • STATEMESH_SERVER_URL - ContextPlex server WebSocket URL (default: ws://localhost:8080/ws)

Note: The environment variable name STATEMESH_SERVER_URL is maintained for backward compatibility. It points to your ContextPlex server endpoint.

TypeScript Types

All types are exported for TypeScript users:

import type {
  StateMeshOptions,
  StateOp,
  SnapshotOptions,
  ChangeEvent,
  StateEvent,
  AckEvent,
  FileSyncOptions,
  EnvFileConfig,
  JsonFileConfig,
} from '@contextplex/sdk-js';

Use Cases

Development Environment Sync

Keep .env files synchronized across team members and machines:

const fileSync = createFileSync({
  client: createClient({ namespace: 'team-dev', apiKey: 'team-key' }),
  namespace: 'team-dev'
});

await fileSync.connect();
await fileSync.syncEnvFile({ path: '.env.local' });

Configuration Management

Sync JSON configuration files across services:

await fileSync.syncJsonFile({
  path: 'services/config.json',
  prefix: 'services.config.',
  flatten: true
});

Multi-Instance State Sharing

Share application state across multiple instances:

const client = createClient({
  namespace: 'app-instances',
  apiKey: 'instance-key'
});

client.on('change', (event) => {
  // Update local application state when remote changes occur
  applyStateChanges(event.ops);
});

Architecture

  • Separation of Concerns - Clean module structure with types, DTOs, utilities, and implementations
  • Type Safety - Full TypeScript support with comprehensive type definitions
  • Event-Driven - Built on Node.js EventEmitter for reactive programming
  • Reconnection Logic - Automatic reconnection with exponential backoff
  • File Watching - Efficient file watching with stability detection

Requirements

  • Node.js 14+ or modern browser with WebSocket support
  • ContextPlex server running and accessible

License

This project is licensed under the MIT License - see the LICENSE file for details.

MIT License

Copyright (c) 2025 ContextPlex

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Support

For issues, questions, or contributions, please visit the GitHub repository.


Made with ❤️ for developers