Advanced reactive data management library with state machines, blueprints, persistence, compression, networking, and multithreading support
npm install cs-element



Status: 🎯 Production Ready - Fully tested and ready for production use!
CSElement is a powerful TypeScript library for building reactive data structures with advanced features including persistence, serialization, compression, networking, state machines, blueprints, and multithreading support.
🌐 Browser Compatible - Works seamlessly in both Node.js and browser environments without any configuration!
CSElement v1.0.2 introduces a clean modular architecture:
- 🌐 Core Library - Browser-compatible, no Node.js dependencies
- 🖥️ Node.js Plugins - Separate imports for Node.js-specific features
- 📦 Tree-shakable - Import only what you need
- ⚡ Zero Configuration - Works out of the box in any environment
``bash`
npm install cs-element
Via UMD (CDN):
`html`
Via ES Modules:
`javascript
import { CSElement } from 'cs-element';
const element = new CSElement('my-element');
await element.setData('name', 'John');
console.log('Data:', element.getData('name'));
`
Core functionality:
`javascript
import { CSElement } from 'cs-element';
const element = new CSElement('my-element');
await element.setData('name', 'John');
`
Node.js specific features:
`javascript
// Separate imports for Node.js-only features
import { BackupPlugin } from 'cs-element/plugins/backup';
import { CompressionPlugin } from 'cs-element/plugins/compression';
import { SecurityPlugin } from 'cs-element/plugins/security';
import { NetworkPlugin } from 'cs-element/plugins/network';
import { SerializationPlugin } from 'cs-element/plugins/serialization';
import { WorkerManager } from 'cs-element/workers/nodejs';
// File operations, compression, etc.
const backup = new BackupPlugin();
const compression = new CompressionPlugin();
`
React/Vue/Angular:
`javascript
import { CSElement } from 'cs-element';
// Tree-shaking automatically includes only what you use
const element = new CSElement('my-element');
`
`javascript
import { CSElement } from 'cs-element';
// Create an element
const user = new CSElement('user-1');
await user.setData('name', 'John Doe');
await user.setData('email', 'john@example.com');
// Reactive queries
const activeUsers = CSElement.query()
.where('active', true)
.live();
activeUsers.subscribe(users => {
console.log(Active users: ${users.length});`
});
`javascript
import {
CSElement,
PersistenceManagerImpl,
MemoryStorageAdapter, // ✅ Универсальный адаптер
} from 'cs-element';
// 🌐 Импорт ТОЛЬКО для браузера
import { IndexedDBAdapter } from 'cs-element/browser';
// Универсальный адаптер (работает везде)
const memoryAdapter = new MemoryStorageAdapter({
name: 'my-app-storage'
});
// IndexedDB адаптер (только браузер)
const indexedAdapter = new IndexedDBAdapter('MyAppDB');
// Инициализация
await memoryAdapter.initialize();
await indexedAdapter.initialize();
// Создание элемента
const document = new CSElement({ data: { title: 'My Document' } });
// Сохранение в память (работает везде)
const saveResult = await memoryAdapter.save(document.id, document.serialize());
// Сохранение в IndexedDB (только браузер)
await indexedAdapter.save([document]);
`
`javascript
import { CSElement } from 'cs-element';
import { BackupPlugin } from 'cs-element/plugins/backup';
import { CompressionPlugin } from 'cs-element/plugins/compression';
// Node.js specific functionality
const backup = new BackupPlugin({
backupPath: './backups',
maxBackups: 10
});
const compression = new CompressionPlugin({
defaultAlgorithm: 'gzip'
});
// Create elements
const project = new CSElement('project-1');
await project.setData('name', 'My Project');
// Create backup (Node.js only)
await backup.createBackup([project], {
name: 'Project Backup',
compression: true
});
`
, data management, events
- Memory Storage - MemoryStorageAdapter (универсальный)
- Reactivity - Live queries, computed properties, watchers
- Visualization - ASCII, SVG, HTML rendering
- State Management - State machines, history, transactions
- Type Safety - Typed elements, validation, schemas
- Graph Algorithms - Path finding, analysis, navigation
- Batch Operations - Parallel/sequential execution
- Service Registry - Dependency injection$3
- IndexedDB Storage - IndexedDBAdapter (высокопроизводительное хранилище)
- LocalForage Storage - LocalForageAdapter (универсальный браузерный адаптер)
- Web Workers - Фоновая обработка данных
- DOM Integration - Прямая работа с DOM элементами$3
- File Operations - Backup/restore, archiving
- Advanced Compression - Gzip, LZ4, Brotli
- Network Operations - HTTP client, WebSocket server
- Security - Encryption, hashing, authentication
- Worker Threads - CPU-intensive background tasks
- Serialization - YAML, MessagePack, custom formats$3
`javascript
// ✅ Works everywhere (Browser + Node.js + SSR)
import {
CSElement,
PersistenceManagerImpl,
MemoryStorageAdapter, // ✅ Универсальный адаптер
VisualizationManager,
StateMachine,
GraphAlgorithms
} from 'cs-element';// 🌐 Browser only
import {
IndexedDBAdapter, // 🌐 Только для браузера
LocalForageAdapter // 🌐 Только для браузера
} from 'cs-element/browser';
// 🖥️ Node.js only
import { BackupPlugin } from 'cs-element/plugins/backup';
import { CompressionPlugin } from 'cs-element/plugins/compression';
import { SecurityPlugin } from 'cs-element/plugins/security';
import { NetworkPlugin } from 'cs-element/plugins/network';
import { SerializationPlugin } from 'cs-element/plugins/serialization';
import { WorkerManager } from 'cs-element/workers/nodejs';
`🛠️ Core Systems
$3
- SerializationPlugin - Data serialization with compression
- CompressionPlugin - Gzip, LZ4, Brotli compression
- NetworkPlugin - HTTP client and WebSocket support
- BackupPlugin - Automated backup creation
- ValidationPlugin - Schema validation and type checking
- SecurityPlugin - Encryption and access control
- MetricsPlugin - Performance monitoring
- AnalyticsPlugin - Usage analytics and tracking
- CachePlugin - Intelligent caching system
- TransformPlugin - Data transformation pipelines
- VisualizationPlugin - Data visualization
- DevToolsPlugin - Development tools integration
- LoggingPlugin - Comprehensive logging system
$3
`typescript
import { StateMachine } from 'cs-element';const element = new CSElement('order');
const stateMachine = element.createStateMachine({
initialState: 'pending',
states: {
pending: { canTransitionTo: ['processing', 'cancelled'] },
processing: { canTransitionTo: ['completed', 'failed'] },
completed: { canTransitionTo: [] },
cancelled: { canTransitionTo: [] },
failed: { canTransitionTo: ['pending'] }
},
transitions: {
process: { from: 'pending', to: 'processing' },
complete: { from: 'processing', to: 'completed' },
cancel: { from: ['pending', 'processing'], to: 'cancelled' },
fail: { from: 'processing', to: 'failed' },
retry: { from: 'failed', to: 'pending' }
}
});
await stateMachine.sendEvent('process');
console.log(stateMachine.currentState); // 'processing'
`$3
`typescript
import { Blueprint, BlueprintManager } from 'cs-element';const projectBlueprint = new Blueprint({
id: 'project-template',
name: 'Project Template',
parameters: [
{ id: 'name', type: 'string', required: true },
{ id: 'teamSize', type: 'number', default: 5 }
],
generator: async (context) => {
const project = new CSElement(context.parameters.name);
// Generate team members
for (let i = 0; i < context.parameters.teamSize; i++) {
const member = new CSElement(
member-${i});
await member.setData('role', 'developer');
await project.addElement(member);
}
return { elements: [project] };
}
});const manager = new BlueprintManager();
manager.register(projectBlueprint);
const result = await manager.generate('project-template', {
name: 'My Project',
teamSize: 3
});
`$3
`typescript
// Live queries with automatic updates
const liveQuery = CSElement.query()
.where('status', 'active')
.where('priority', '>', 5)
.orderBy('createdAt', 'desc')
.limit(10)
.live();liveQuery.subscribe(results => {
console.log('Updated results:', results);
});
// Computed properties
const totalValue = CSElement.computed(() => {
return elements
.filter(e => e.getData('active'))
.reduce((sum, e) => sum + e.getData('value'), 0);
});
totalValue.subscribe(value => {
console.log('Total value:', value);
});
`$3
`typescript
// ACID transactions
await CSElement.transaction(async (tx) => {
const user = await tx.getElementById('user-1');
const account = await tx.getElementById('account-1');
const currentBalance = account.getData('balance');
const transferAmount = 100;
if (currentBalance >= transferAmount) {
await account.setData('balance', currentBalance - transferAmount);
await user.setData('credits', user.getData('credits') + transferAmount);
} else {
throw new Error('Insufficient funds');
}
});
`$3
`typescript
import { HistoryManagerImpl } from 'cs-element';// Configure history tracking
const historyManager = new HistoryManagerImpl({
maxOperations: 100,
snapshotInterval: 10,
autoCleanup: true,
compression: true
});
// Track operations automatically
const element = new CSElement('document');
await element.setData('title', 'Original Title');
// Manual operation tracking
historyManager.addOperation({
type: 'update',
description: 'Changed document title',
before: { title: 'Original Title' },
after: { title: 'New Title' },
canUndo: true,
canRedo: true
});
// Undo/Redo operations
await historyManager.undo(); // Reverts to 'Original Title'
await historyManager.redo(); // Back to 'New Title'
// Create snapshots
const snapshot = historyManager.createSnapshot(
element.export(),
'Document checkpoint'
);
// History events
historyManager.on('undo-performed', (data) => {
console.log('Undo performed:', data.operation.description);
});
// Get history state
const state = historyManager.getState();
console.log(
Can undo: ${state.canUndo}, Can redo: ${state.canRedo});
`$3
`typescript
import { MigrationBuilder, MigrationManager } from 'cs-element';// Create migration
const migration = new MigrationBuilder()
.version('1.1.0')
.description('Add user preferences')
.up(async (context) => {
const users = context.query('user');
for (const user of users) {
await user.setData('preferences', {
theme: 'light',
notifications: true
});
}
})
.down(async (context) => {
const users = context.query('user');
for (const user of users) {
await user.deleteData('preferences');
}
})
.build();
const migrationManager = new MigrationManager();
await migrationManager.register(migration);
await migrationManager.migrate('1.1.0');
`$3
$3
Automatic memory cleanup prevents memory leaks:
`typescript
import { CSElement } from 'cs-element';// Enable auto-dispose globally
CSElement.configureReactivity({
autoDispose: true,
debug: true
});
// Create scope for automatic cleanup
const scope = CSElement.createScope();
CSElement.runInScope(scope.id, () => {
const parent = CSElement.computed(() => data.value * 2);
const child1 = CSElement.computed(() => data.value * 2);
const child2 = CSElement.computed(() => data.value * 3);
return child1.value + child2.value;
});
// Cleanup entire scope
CSElement.disposeScope(scope.id);
`$3
Sophisticated middleware with priorities and conditions:
`typescript
import { CSElement, MiddlewarePriority } from 'cs-element';// Add high-priority validation middleware
CSElement.plugins.addAdvancedMiddleware('setData', {
name: 'validation-middleware',
priority: MiddlewarePriority.HIGH,
condition: (context) => context.args.key === 'email',
timeout: 1000,
middleware: async (context, next) => {
const { key, value } = context.args;
if (key === 'email' && !isValidEmail(value)) {
throw new Error('Invalid email format');
}
return await next();
}
});
// Add logging middleware with metadata
CSElement.plugins.addAdvancedMiddleware('setData', {
name: 'audit-logger',
priority: MiddlewarePriority.LOW,
middleware: async (context, next) => {
const startTime = Date.now();
const result = await next();
console.log(
Operation ${context.operation} took ${Date.now() - startTime}ms);
return result;
}
});
`$3
Efficient bulk operations with different strategies:
`typescript
import { BatchManager, BatchExecutionStrategy, BatchPriority } from 'cs-element';const batchManager = new BatchManager();
// Create batch with parallel execution
const batchId = batchManager.createBatch({
executionStrategy: BatchExecutionStrategy.PARALLEL,
maxConcurrency: 5,
errorMode: 'COLLECT_ERRORS'
});
// Add operations with priorities and dependencies
batchManager.addOperation(batchId, {
id: 'create-users',
priority: BatchPriority.HIGH,
execute: async (context) => {
const users = await createMultipleUsers(userData);
return users;
},
validate: async (context) => ({ valid: true, errors: [] }),
maxRetries: 3
});
batchManager.addOperation(batchId, {
id: 'send-notifications',
priority: BatchPriority.NORMAL,
dependencies: ['create-users'], // Wait for users to be created
execute: async (context) => {
const users = context.previousResults.get('create-users');
return await sendWelcomeEmails(users);
}
});
// Execute batch with progress monitoring
const result = await batchManager.executeBatch(batchId);
console.log(
Batch completed: ${result.successCount}/${result.totalOperations});
`$3
Multi-format visualization with interactive features:
`typescript
import { VisualizationManager, VisualizationFormat } from 'cs-element';const visualizer = new VisualizationManager();
// Generate interactive HTML visualization
const htmlViz = await visualizer.visualize(rootElement, {
format: VisualizationFormat.HTML,
layout: 'tree',
interactive: true,
showData: true,
animations: true,
width: 1200,
height: 800,
theme: 'dark'
});
// Generate SVG for documentation
const svgViz = await visualizer.visualize(rootElement, {
format: VisualizationFormat.SVG,
layout: 'circular',
nodeStyle: {
backgroundColor: '#3498db',
textColor: '#ffffff',
borderRadius: 8
},
edgeStyle: {
color: '#2c3e50',
thickness: 2,
style: 'dashed'
}
});
// ASCII visualization for console output
const asciiViz = await visualizer.visualize(rootElement, {
format: VisualizationFormat.ASCII,
maxDepth: 5,
showIds: true,
showIndices: true
});
console.log(asciiViz.content);
`$3
Advanced graph analysis and pathfinding:
`typescript
import { CSElement } from 'cs-element';// Configure graph algorithms
CSElement.configureGraphAlgorithms({
defaultTimeout: 5000,
enableCaching: true,
enableEvents: true
});
// Find shortest path between elements
const path = await CSElement.findShortestPath(sourceElement, targetElement, {
algorithm: 'dijkstra',
weightFunction: (from, to) => calculateDistance(from, to),
maxDepth: 10
});
// Detect cycles in the graph
const cycleResult = await CSElement.detectCycles(rootElement, {
algorithm: 'dfs',
includeVisualization: true
});
if (cycleResult.hasCycles) {
console.log(
Found ${cycleResult.cycles.length} cycles);
cycleResult.cycles.forEach(cycle => {
console.log(Cycle: ${cycle.path.join(' -> ')});
});
}// Analyze graph connectivity
const components = await CSElement.findConnectedComponents(rootElement);
console.log(
Graph has ${components.componentCount} connected components);// Calculate node centrality
const centrality = await CSElement.calculateCentrality(rootElement);
const mostCentralNode = Array.from(centrality.entries())
.sort(([,a], [,b]) => b - a)[0];
console.log(
Most central node: ${mostCentralNode[0]} (${mostCentralNode[1]}));
`$3
Sophisticated comparison with multiple algorithms:
`typescript
import { DiffEngine, DiffAlgorithm, MergeStrategy } from 'cs-element';const diffEngine = new DiffEngine();
// Compare elements with different algorithms
const myersDiff = diffEngine.computeDiff(sourceElement, targetElement, {
algorithm: DiffAlgorithm.MYERS,
contextLines: 5,
includeVisualization: true
});
const patienceDiff = diffEngine.computeDiff(sourceElement, targetElement, {
algorithm: DiffAlgorithm.PATIENCE,
ignoreWhitespace: true
});
// Three-way merge for conflict resolution
const mergeResult = diffEngine.threeWayMerge(
baseElement,
branchAElement,
branchBElement,
{
strategy: MergeStrategy.AUTO,
conflictResolution: 'auto',
autoResolveThreshold: 0.8
}
);
if (mergeResult.success) {
console.log('Merge completed successfully');
} else {
console.log(
${mergeResult.conflicts.length} conflicts need manual resolution);
mergeResult.conflicts.forEach(conflict => {
console.log(Conflict at ${conflict.path.join('.')}: ${conflict.type});
});
}
`$3
Strongly typed elements with inheritance:
`typescript
import { TypedElementManager, TypedElement } from 'cs-element';const manager = new TypedElementManager();
// Define base schema
const baseSchema = {
name: 'BaseEntity',
version: '1.0.0',
fields: [
{ name: 'id', type: 'number', required: true },
{ name: 'createdAt', type: 'date', defaultValue: () => new Date() },
{ name: 'updatedAt', type: 'date', nullable: true }
]
};
// Define inherited schema
const userSchema = manager.createInheritedSchema(
'User',
'1.0.0',
'BaseEntity',
[
{ name: 'email', type: 'string', required: true, validation: isValidEmail },
{ name: 'name', type: 'string', required: true },
{ name: 'role', type: 'enum', values: ['user', 'admin'], defaultValue: 'user' }
]
);
manager.registerSchema(baseSchema);
manager.registerSchema(userSchema);
// Create typed element
const user = await manager.createElement('User', {
id: 1,
email: 'john@example.com',
name: 'John Doe',
role: 'admin'
});
// Type-safe field access
const email: string = user.getField('email');
await user.setField('role', 'user'); // Type-checked
`$3
Dependency injection and service management:
`typescript
import { services } from 'cs-element';// Access built-in services
const persistenceManager = services.persistence;
const reactivityManager = services.reactivity;
const historyManager = services.history;
// Configure services
services.configureHistory({
maxHistorySize: 1000,
enableCompression: true,
autoSnapshot: true,
snapshotInterval: 5000
});
services.configureReactivity({
autoDispose: true,
debug: false,
warnMemoryLeaks: true,
maxComputedDepth: 50
});
// Access global element registry
const allElements = services.registry.getAllElements();
const userElements = services.registry.getElementsByName('User');
const specificElement = services.registry.getElementById('element-123');
`⚛️ React Integration
`typescript
import { useCSElement } from 'cs-element/react';function MyComponent() {
const {
root,
createElement,
query,
connected,
stats
} = useCSElement({
autoConnect: true,
enableReactivity: true,
enablePersistence: true
});
const handleCreateUser = () => {
const user = createElement('user', {
name: 'New User',
email: 'user@example.com'
});
};
const users = query('user[active=true]');
return (
Users ({stats.elementCount})
{users.map(user => (
{user.getData('name')}
))}
);
}
``CSElement includes a powerful browser extension for debugging and visualization:
- Element Inspector - Inspect element hierarchies
- Performance Profiler - Monitor performance metrics
- State Visualization - Visualize state machines
- Live Query Monitor - Track live query updates
- Memory Usage - Monitor memory consumption
We welcome contributions! Please see our Contributing Guide for details.
This project is licensed under the MIT License - see the LICENSE file for details.
- Built with TypeScript for type safety
- Uses EventEmitter3 for high-performance events
- Inspired by modern reactive frameworks
- Designed for enterprise-scale applications
---
CSElement - Building the future of reactive data management 🚀