UNPKG

@syntropysoft/syntropyfront

Version:

๐Ÿš€ Observability library with automatic capture - Just 1 line of code! Automatically captures clicks, errors, HTTP calls, and console logs with flexible error handling.

555 lines (437 loc) โ€ข 16.3 kB
<p align="center"> <img src="./assets/syntropysoft-logo.png" alt="SyntropySoft Logo" width="170"/> </p> <h1 align="center">SyntropyFront</h1> <p align="center"> <strong>From Chaos to Clarity</strong> <br /> The Observability Library for High-Performance Teams </p> <p align="center"> <a href="https://www.npmjs.com/package/@syntropysoft/syntropyfront"><img src="https://img.shields.io/npm/v/@syntropysoft/syntropyfront.svg" alt="NPM Version"></a> <a href="https://github.com/Syntropysoft/syntropyfront/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/@syntropysoft/syntropyfront.svg" alt="License"></a> <a href="#"><img src="https://img.shields.io/badge/status-ready%20for%20production-brightgreen.svg" alt="Ready for Production"></a> <a href="#"><img src="https://github.com/Syntropysoft/syntropyfront/workflows/CodeQL/badge.svg" alt="CodeQL"></a> <a href="#"><img src="https://img.shields.io/badge/dependabot-enabled-brightgreen.svg" alt="Dependabot"></a> <a href="#"><img src="https://img.shields.io/badge/mutation%20score-74.96%25-brightgreen.svg" alt="Mutation Score"></a> <a href="#"><img src="https://img.shields.io/badge/test%20coverage-91.01%25-brightgreen.svg" alt="Test Coverage"></a> <a href="#"><img src="https://img.shields.io/badge/bundle%20size-4.88%20KB-brightgreen.svg" alt="Bundle Size"></a> </p> --- ๐Ÿš€ **Observability library with automatic capture - Just 1 line of code!** SyntropyFront automatically captures user interactions, errors, HTTP calls, and console logs, providing comprehensive observability for your web applications with minimal setup. ## โœจ Features - ๐ŸŽฏ **Automatic click capture** - Tracks all user interactions - ๐Ÿšจ **Error detection** - Catches uncaught exceptions and promise rejections - ๐ŸŒ **HTTP monitoring** - Intercepts fetch calls automatically - ๐Ÿ“ **Console logging** - Records console.log, console.error, console.warn - ๐Ÿ’พ **Smart storage** - Keeps the last N events (configurable) - ๐Ÿ“ค **Flexible posting** - Posts errors to your endpoint or logs to console - โšก **Zero configuration** - Works out of the box with just an import ## ๐Ÿš€ Quick Start ### Basic Usage (1 line of code!) ```javascript import syntropyFront from '@syntropysoft/syntropyfront'; // That's it! Auto-initializes and captures everything automatically ``` ### With Custom Configuration ```javascript import syntropyFront from '@syntropysoft/syntropyfront'; // Option 1: Console only (default) syntropyFront.configure({ maxEvents: 50 }); // Option 2: With endpoint (automatic fetch) syntropyFront.configure({ maxEvents: 50, fetch: { url: 'https://your-api.com/errors', options: { headers: { 'Authorization': 'Bearer your-token', 'Content-Type': 'application/json' }, mode: 'cors' } } }); // Option 3: With custom error handler (maximum flexibility) syntropyFront.configure({ maxEvents: 50, onError: (errorPayload) => { // You can do anything with the error: // - Send to your API // - Save to localStorage // - Send to a repository // - Upload to cloud // - Whatever you want! console.log('Error captured:', errorPayload); // Example: send to multiple places fetch('https://api1.com/errors', { method: 'POST', body: JSON.stringify(errorPayload) }); // Also save locally localStorage.setItem('lastError', JSON.stringify(errorPayload)); } }); ``` ## ๐Ÿ“ฆ Installation ```bash npm install @syntropysoft/syntropyfront ``` ## ๐Ÿš€ **Performance Optimizations (v0.3.0)** SyntropyFront has been optimized for maximum performance and minimal bundle size: ### **๐ŸŽฏ Testing Excellence** - **Mutation Score**: Improved from 58.14% to **74.96%** (+16.82 points!) - **Test Coverage**: **91.01%** with 488 comprehensive tests - **Database Modules**: All modules now have 77-100% mutation score - **Core Components**: 92.70% average mutation score across agent modules ### **๐Ÿ“ฆ Ultra-Lightweight Bundle** - **Only 1 Runtime Dependency**: `flatted` for circular reference handling - **45+ Dependencies Removed**: Eliminated unnecessary packages - **Bundle Size**: **4.88 KB** minified (4,884 bytes) - **ES Module**: 10.9 KB - **CommonJS**: 10.98 KB - **Faster Installation**: Reduced npm install time and disk usage ### **๐Ÿ”ง Smart Dependency Management** - **Clean Architecture**: All testing tools properly categorized as devDependencies - **Dependabot Optimized**: Smart configuration prevents incompatible updates - **Stable CI/CD**: Eliminated dependency conflicts and CI failures - **Cross-Node Compatibility**: Full support for Node.js 18, 20, 22 ### **โšก Production Ready** - **Zero Breaking Changes**: All existing code continues to work - **Same API**: Identical usage patterns and configuration - **Better Performance**: Optimized for production environments - **Maintained Security**: All security benefits preserved ## ๐ŸŽฏ How It Works SyntropyFront automatically: 1. **Captures clicks** - Records element info, coordinates, and timestamps 2. **Detects errors** - Intercepts `window.onerror` and `window.onunhandledrejection` 3. **Monitors HTTP** - Wraps `window.fetch` to track requests and responses 4. **Logs console** - Intercepts console methods to capture debug info 5. **Maintains context** - Keeps the last N events as breadcrumbs 6. **Posts errors** - Sends error data with full context to your endpoint ## ๐Ÿ“Š What Gets Captured ### Error Payload Structure ```json { "type": "uncaught_exception", "error": { "message": "Error message", "source": "file.js", "lineno": 42, "colno": 15, "stack": "Error stack trace..." }, "breadcrumbs": [ { "category": "user", "message": "click", "data": { "element": "BUTTON", "id": "submit-btn", "className": "btn-primary", "x": 100, "y": 200 }, "timestamp": "2024-01-01T12:00:00.000Z" } ], "timestamp": "2024-01-01T12:00:00.000Z" } ``` ### Breadcrumb Categories - **`user`** - Click events, form submissions, etc. - **`http`** - Fetch requests, responses, and errors - **`console`** - Console.log, console.error, console.warn - **`error`** - Manual error reports ## โš™๏ธ Configuration Options SyntropyFront uses a priority system for error handling: 1. **Custom Error Handler** (`onError`) - Maximum flexibility 2. **Endpoint** (`fetch`) - Automatic posting 3. **Console** - Default fallback ### Basic Configuration (Console Only) ```javascript syntropyFront.configure({ maxEvents: 50 // Number of events to keep in memory }); ``` ### With Endpoint (Automatic Fetch) ```javascript syntropyFront.configure({ maxEvents: 50, fetch: { url: 'https://your-api.com/errors', options: { headers: { 'Authorization': 'Bearer your-token', 'X-API-Key': 'your-api-key', 'Content-Type': 'application/json' }, mode: 'cors', credentials: 'include' } } }); ``` ### With Custom Error Handler (Maximum Flexibility) ```javascript syntropyFront.configure({ maxEvents: 50, onError: (errorPayload) => { // You have complete control over what to do with the error // Send to your API fetch('https://your-api.com/errors', { method: 'POST', body: JSON.stringify(errorPayload) }); // Save to localStorage localStorage.setItem('lastError', JSON.stringify(errorPayload)); // Send to multiple services Promise.all([ fetch('https://service1.com/errors', { method: 'POST', body: JSON.stringify(errorPayload) }), fetch('https://service2.com/errors', { method: 'POST', body: JSON.stringify(errorPayload) }) ]); // Upload to cloud storage // Send to repository // Log to file // Whatever you want! } }); ``` ## ๐Ÿ”ง API Reference ### Core Methods ```javascript // Add custom breadcrumb syntropyFront.addBreadcrumb('user', 'Custom action', { data: 'value' }); // Send manual error syntropyFront.sendError(new Error('Custom error')); // Get current breadcrumbs const breadcrumbs = syntropyFront.getBreadcrumbs(); // Clear breadcrumbs syntropyFront.clearBreadcrumbs(); // Get statistics const stats = syntropyFront.getStats(); // Returns: { breadcrumbs: 5, errors: 2, isActive: true, maxEvents: 50, endpoint: 'console' } ``` ## ๐ŸŽฏ Extending SyntropyFront SyntropyFront captures the essentials by default, but you can extend it to capture any DOM events you want: ### Adding Custom Event Capture ```javascript import syntropyFront from '@syntropysoft/syntropyfront'; // Add scroll tracking window.addEventListener('scroll', () => { syntropyFront.addBreadcrumb('user', 'scroll', { scrollY: window.scrollY, scrollX: window.scrollX }); }); // Add form submissions document.addEventListener('submit', (event) => { syntropyFront.addBreadcrumb('user', 'form_submit', { formId: event.target.id, formAction: event.target.action }); }); // Add window resize window.addEventListener('resize', () => { syntropyFront.addBreadcrumb('system', 'window_resize', { width: window.innerWidth, height: window.innerHeight }); }); // Add custom business events function trackPurchase(productId, amount) { syntropyFront.addBreadcrumb('business', 'purchase', { productId, amount, timestamp: new Date().toISOString() }); } ``` ### Common Events You Can Track - **User interactions**: `click`, `scroll`, `keydown`, `focus`, `blur` - **Form events**: `submit`, `input`, `change`, `reset` - **System events**: `resize`, `online`, `offline`, `visibilitychange` - **Custom events**: Any business logic or user actions - **Performance**: `load`, `DOMContentLoaded`, timing events ## ๐ŸŒ CORS Configuration To use with your API, ensure your server allows CORS: ```javascript // Express.js example app.use(cors({ origin: 'http://localhost:3000', credentials: true })); // Or in headers res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000'); res.setHeader('Access-Control-Allow-Methods', 'POST'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); ``` ## ๐Ÿ“ฑ Framework Support SyntropyFront works with any JavaScript framework: - โœ… **React** - Works out of the box - โœ… **Vue** - Works out of the box - โœ… **Angular** - Works out of the box - โœ… **Svelte** - Works out of the box - โœ… **Vanilla JS** - Works out of the box ## ๐ŸŽฏ Examples ### React Example ```jsx import React from 'react'; import syntropyFront from '@syntropysoft/syntropyfront'; function App() { // SyntropyFront auto-initializes on import return ( <div> <button onClick={() => console.log('Button clicked')}> Click me! </button> </div> ); } ``` ### Vue Example ```vue <template> <button @click="handleClick">Click me!</button> </template> <script> import syntropyFront from '@syntropysoft/syntropyfront'; export default { methods: { handleClick() { console.log('Button clicked'); } } } </script> ``` ### Manual Error Reporting ```javascript import syntropyFront from '@syntropysoft/syntropyfront'; try { // Your code here } catch (error) { // SyntropyFront will automatically capture this throw error; } // Or manually report syntropyFront.sendError(new Error('Something went wrong')); ``` ### Extending with Custom Events ```javascript import syntropyFront from '@syntropysoft/syntropyfront'; // Add your custom event listeners window.addEventListener('scroll', () => { syntropyFront.addBreadcrumb('user', 'scroll', { scrollY: window.scrollY, scrollX: window.scrollX }); }); // Track business events function userCompletedCheckout(orderId, total) { syntropyFront.addBreadcrumb('business', 'checkout_completed', { orderId, total, timestamp: new Date().toISOString() }); } // Track performance window.addEventListener('load', () => { syntropyFront.addBreadcrumb('performance', 'page_loaded', { loadTime: performance.now() }); }); ``` ## ๐Ÿ—๏ธ Architecture & Code Quality SyntropyFront follows SOLID principles and maintains high code quality through: ### Modular Architecture The codebase is organized into focused modules with single responsibilities: ``` src/core/ โ”œโ”€โ”€ agent/ # Core Agent components โ”‚ โ”œโ”€โ”€ Agent.js # Main coordinator โ”‚ โ”œโ”€โ”€ ConfigurationManager.js # Configuration handling โ”‚ โ”œโ”€โ”€ QueueManager.js # Batching and queuing โ”‚ โ””โ”€โ”€ HttpTransport.js # HTTP communication โ”œโ”€โ”€ database/ # IndexedDB management โ”‚ โ”œโ”€โ”€ DatabaseManager.js # Database coordinator โ”‚ โ”œโ”€โ”€ DatabaseConfigManager.js # Configuration โ”‚ โ”œโ”€โ”€ DatabaseConnectionManager.js # Connection handling โ”‚ โ”œโ”€โ”€ DatabaseTransactionManager.js # Transaction management โ”‚ โ”œโ”€โ”€ StorageManager.js # CRUD operations โ”‚ โ””โ”€โ”€ SerializationManager.js # Data serialization โ”œโ”€โ”€ retry/ # Retry system โ”‚ โ”œโ”€โ”€ RetryManager.js # Retry coordination โ”‚ โ””โ”€โ”€ RetryLogicManager.js # Retry logic โ”œโ”€โ”€ persistent/ # Persistent buffer โ”‚ โ””โ”€โ”€ PersistentBufferManager.js # Buffer management โ”œโ”€โ”€ breadcrumbs/ # Event tracking โ”‚ โ”œโ”€โ”€ BreadcrumbManager.js # Breadcrumb coordination โ”‚ โ””โ”€โ”€ BreadcrumbStore.js # Breadcrumb storage โ”œโ”€โ”€ context/ # Context collection โ”‚ โ””โ”€โ”€ ContextCollector.js # Context gathering โ””โ”€โ”€ utils/ # Utilities โ”œโ”€โ”€ Logger.js # Logging utilities โ””โ”€โ”€ ErrorManager.js # Error handling ``` ### Design Principles - **Single Responsibility Principle (SRP)**: Each class has one clear purpose - **Dependency Injection**: Components receive dependencies through constructors - **Declarative Error Handling**: Structured error responses with fallbacks - **Comprehensive Testing**: 488 tests with 74.96% mutation score - **Optimized Performance**: Timeouts optimized for faster execution ## ๐Ÿงช Testing & Quality SyntropyFront maintains high code quality through comprehensive testing: ### Test Coverage & Mutation Testing - **Mutation Score**: 74.96% - Our tests effectively detect code changes - **Test Coverage**: 91.01% - Comprehensive unit test coverage - **Key Components Performance**: - `Agent.js`: 87.23% mutation score - `ConfigurationManager.js`: 100% mutation score - `QueueManager.js`: 97.37% mutation score - `HttpTransport.js`: 86.96% mutation score - `BreadcrumbManager.js`: 100% mutation score - `BreadcrumbStore.js`: 95.00% mutation score - `SerializationManager.js`: 100% mutation score - `DatabaseTransactionManager.js`: 100% mutation score - `DatabaseConfigManager.js`: 86.89% mutation score - `DatabaseConnectionManager.js`: 85.96% mutation score - `PersistentBufferManager.js`: 77.63% mutation score ### Testing Stack - **Jest**: Unit testing framework - **Stryker**: Mutation testing for test quality validation - **IndexedDB Mocking**: Browser storage testing - **Fetch Mocking**: HTTP request testing ### Running Tests ```bash # Run all tests npm test # Run with coverage npm run test:coverage # Run mutation testing npm run test:mutation ``` ## ๐Ÿ” Debugging SyntropyFront logs helpful information to the console: ``` ๐Ÿš€ SyntropyFront: Initialized with automatic capture โœ… SyntropyFront: Configured - maxEvents: 50, endpoint: https://your-api.com/errors โŒ Error: { type: "uncaught_exception", error: {...}, breadcrumbs: [...] } ``` ## ๐Ÿ“„ License This project is licensed under the Apache License, Version 2.0 - see the [LICENSE](LICENSE) file for details. **Apache License 2.0** - A permissive license that allows for: - โœ… Commercial use - โœ… Modification - โœ… Distribution - โœ… Patent use - โœ… Private use The only requirement is that you include the original copyright notice and license text in any substantial portions of the software you distribute. For more information, visit: https://www.apache.org/licenses/LICENSE-2.0 ## ๐Ÿค Contributing Contributions are welcome! Please feel free to submit a Pull Request. --- **Made with โค๏ธ for better web observability**