📝 See CHANGELOG.md for version history and breaking changes.
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.
- 🚀 Realtime State Sync - Bidirectional state synchronization via WebSocket
- 📁 File Synchronization - Automatic
.envand JSON file syncing across environments - 🔍 Auto-Detection - Automatically detects project root and common config files
- 🔐 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
npm install @contextplex/sdk-js
# or
yarn add @contextplex/sdk-js
# or
pnpm add @contextplex/sdk-jsimport { createClient } from '@contextplex/sdk-js';
// Option 1: Pass serverUrl directly (highest priority)
const client = createClient({
namespace: 'my-project',
apiKey: 'your-api-key',
serverUrl: 'wss://api.contextplex.com/ws'
});
// Option 2: Use environment variable
// export STATEMESH_SERVER_URL=wss://api.contextplex.com/ws
const client = createClient({
namespace: 'my-project',
apiKey: 'your-api-key'
});
// Option 3: Use default (production server)
const client = createClient({
namespace: 'my-project',
apiKey: 'your-api-key'
// Defaults to wss://api.contextplex.dev/ws
});
// 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');import { createClient, createFileSync } from '@contextplex/sdk-js';
// Create client
const client = createClient({
namespace: 'dev-environment',
apiKey: 'dev-api-key'
});
// Create file sync instance (baseDir auto-detects project root)
const fileSync = createFileSync({
client,
namespace: 'dev-environment'
// baseDir is optional - SDK auto-detects project root
});
// Connect
await fileSync.connect();
// Start syncing .env file (path auto-detected if not provided)
await fileSync.syncEnvFile({
// path is optional - SDK auto-detects .env, .env.local, .env.development, etc.
prefix: 'env.' // Optional, defaults to 'env.'
});
// Listen for sync events
fileSync.on('synced', (event) => {
console.log(`${event.type} file synced: ${event.path} (${event.direction})`);
});// Sync a JSON configuration file
// path is optional - SDK auto-detects package.json, tsconfig.json, jsconfig.json, etc.
await fileSync.syncJsonFile({
// path: 'config.json', // Optional - auto-detects if not provided
// configName: 'package.json', // Or specify which config file to find
prefix: 'config.', // Optional, defaults to 'json.'
flatten: true // Optional, flatten nested objects (default: true)
});Creates a new ContextPlex client instance.
Parameters:
options.namespace(string, required) - Namespace identifier for state isolationoptions.apiKey(string, required) - API key for authenticationoptions.serverUrl(string, optional) - Server WebSocket URL. If provided, overridesSTATEMESH_SERVER_URLenvironment variable
Priority order for server URL:
options.serverUrl(if provided)STATEMESH_SERVER_URLenvironment variable- Default:
wss://api.contextplex.dev/ws
Returns: StateMeshClient instance
Example:
// Using default/localhost
const client = createClient({
namespace: 'my-project',
apiKey: 'my-api-key'
});
// Passing server URL directly
const client = createClient({
namespace: 'my-project',
apiKey: 'my-api-key',
serverUrl: 'wss://api.contextplex.com/ws'
});
// Using environment variable
// export STATEMESH_SERVER_URL=wss://api.contextplex.com/ws
const client = createClient({
namespace: 'my-project',
apiKey: 'my-api-key'
});Main client class for ContextPlex connections.
Connects to the ContextPlex server.
await client.connect();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 }]);Deletes a value at a dot-separated path.
await client.delete('my-project', 'user.name');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 }
]);Gets the current state for a namespace.
const state = await client.getState('my-project');
// or use default namespace
const defaultState = await client.getState();Creates a snapshot of the current state.
const snapshotId = await client.snapshot('my-project', { tag: 'checkpoint-1' });Disconnects from the server.
client.disconnect();Emitted when connection is established.
client.on('connected', () => {
console.log('Connected to ContextPlex');
});Emitted when connection is closed.
client.on('disconnected', () => {
console.log('Disconnected from ContextPlex');
});Emitted when state changes (from other clients).
client.on('change', (event: ChangeEvent) => {
console.log(`Namespace ${event.namespace} changed:`, event.ops);
});Emitted when receiving state snapshot.
client.on('state', (event: StateEvent) => {
console.log(`State for ${event.namespace}:`, event.state);
});Emitted when operation is acknowledged.
client.on('ack', (event: AckEvent) => {
console.log(`Ack: ${event.namespace}, sequence: ${event.last_sequence}`);
});Emitted on errors.
client.on('error', (error: Error) => {
console.error('ContextPlex error:', error);
});Creates a new file synchronization instance.
Parameters:
options.client(StateMeshClient, required) - ContextPlex client instanceoptions.namespace(string, required) - Namespace for syncingoptions.baseDir(string, optional) - Base directory to watch (default: auto-detected project root)
Returns: FileSync instance
Note: If baseDir is not provided, the SDK automatically detects the project root by searching for package.json or node_modules in parent directories, starting from process.cwd().
Manages bidirectional synchronization of .env and JSON files.
Starts syncing a .env file.
Parameters:
config.path(string, optional) - Path to.envfile (relative tobaseDir). If not provided, auto-detects common.envfile locations (.env,.env.local,.env.development,.env.development.local)config.prefix(string, optional) - StateMesh path prefix (default:'env.')
// Auto-detect .env file location
await fileSync.syncEnvFile({
prefix: 'env.'
});
// Or specify a custom path
await fileSync.syncEnvFile({
path: '.env.production',
prefix: 'env.'
});Starts syncing a JSON file.
Parameters:
config.path(string, optional) - Path to JSON file (relative tobaseDir). If not provided, auto-detects common config files (package.json,tsconfig.json,jsconfig.json)config.configName(string, optional) - Name of config file to find (e.g.,'package.json'). Used whenpathis not providedconfig.prefix(string, optional) - StateMesh path prefix (default:'json.')config.flatten(boolean, optional) - Flatten nested JSON (default:true)
// Auto-detect package.json or other common config files
await fileSync.syncJsonFile({
prefix: 'config.',
flatten: true
});
// Or specify a custom path
await fileSync.syncJsonFile({
path: 'custom-config.json',
prefix: 'config.',
flatten: true
});
// Or specify which config file to find
await fileSync.syncJsonFile({
configName: 'tsconfig.json',
prefix: 'config.',
flatten: true
});Connects to ContextPlex.
await fileSync.connect();Stops watching files and disconnects.
await fileSync.stop();Emitted when file sync starts.
fileSync.on('syncing', (event: SyncingEvent) => {
console.log(`Syncing ${event.type} file: ${event.path}`);
});Emitted when file sync completes.
fileSync.on('synced', (event: SyncedEvent) => {
console.log(`${event.type} file synced: ${event.path} (${event.direction})`);
});Emitted when connected to ContextPlex.
Emitted when sync stops.
Emitted on errors.
The SDK supports three ways to configure the server URL, with the following priority order:
- Pass
serverUrldirectly (highest priority) - Overrides environment variable - Environment variable -
STATEMESH_SERVER_URL - Default -
wss://api.contextplex.dev/ws
const client = createClient({
namespace: 'my-project',
apiKey: 'my-api-key',
serverUrl: 'wss://api.contextplex.com/ws' // Direct override
});# Set environment variable
export STATEMESH_SERVER_URL=wss://api.contextplex.com/ws
# Then use in code
const client = createClient({
namespace: 'my-project',
apiKey: 'my-api-key'
// Uses STATEMESH_SERVER_URL automatically
});const client = createClient({
namespace: 'my-project',
apiKey: 'my-api-key'
// Defaults to wss://api.contextplex.dev/ws
});Protocols:
- Use
ws://for unencrypted connections (development) - Use
wss://for secure WebSocket connections (production)
Examples:
# Local development
ws://localhost:8080/ws
# Production server
wss://api.contextplex.com/ws
# Custom server with port
wss://your-server.com:8443/wsThe SDK exports utility functions for path detection and file parsing:
import {
findProjectRoot,
findEnvFile,
findConfigFile,
findCommonConfigFiles,
parseEnvFile,
stringifyEnvFile,
} from '@contextplex/sdk-js';
// Auto-detect project root
const projectRoot = findProjectRoot();
// Auto-detect .env file
const envFile = await findEnvFile(projectRoot);
console.log('Found .env at:', envFile); // e.g., '.env.local'
// Auto-detect config files
const configFile = await findConfigFile(projectRoot, 'package.json');
console.log('Found config at:', configFile);
// Parse .env file content
const envContent = 'KEY=value\nANOTHER_KEY=value2';
const parsed = parseEnvFile(envContent);
console.log(parsed); // { KEY: 'value', ANOTHER_KEY: 'value2' }All types are exported for TypeScript users:
import type {
StateMeshOptions,
StateOp,
SnapshotOptions,
ChangeEvent,
StateEvent,
AckEvent,
FileSyncOptions,
EnvFileConfig,
JsonFileConfig,
} from '@contextplex/sdk-js';Keep .env files synchronized across team members and machines:
const fileSync = createFileSync({
client: createClient({ namespace: 'team-dev', apiKey: 'team-key' }),
namespace: 'team-dev'
// baseDir and path auto-detected - no manual configuration needed!
});
await fileSync.connect();
// Auto-detects .env file location
await fileSync.syncEnvFile({
prefix: 'env.'
});Sync JSON configuration files across services:
// Auto-detect and sync package.json
await fileSync.syncJsonFile({
configName: 'package.json',
prefix: 'package.',
flatten: true
});
// Or sync a custom config file
await fileSync.syncJsonFile({
path: 'services/config.json',
prefix: 'services.config.',
flatten: true
});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);
});- Separation of Concerns - Clean module structure with types, DTOs, utilities, and implementations
- Auto-Detection - Intelligent path detection for project roots and common configuration files
- 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
- Node.js 14+ or modern browser with WebSocket support
- ContextPlex server running and accessible
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.
For issues, questions, or contributions, please visit the GitHub repository.
Made with ❤️ for developers