{"_id":"connectic","_rev":"4-8d4ad0e171ffa59bd0921e5c190c8764","name":"connectic","dist-tags":{"latest":"4.0.0"},"versions":{"1.0.0":{"name":"connectic","version":"1.0.0","keywords":["event-bus","microfrontend","communication","state-management","pub-sub","request-response","real-time","data-synchronization","javascript","typescript","framework-agnostic","mfe","event-driven"],"author":"","license":"MIT","_id":"connectic@1.0.0","maintainers":[{"name":"devferanmi","email":"devferanmi@gmail.com"}],"homepage":"https://github.com/spiderocious/connectic#readme","bugs":{"url":"https://github.com/spiderocious/connectic/issues"},"dist":{"shasum":"954c542dac2a0e94f070d175587eaf2648e888e8","tarball":"https://registry.npmjs.org/connectic/-/connectic-1.0.0.tgz","fileCount":9,"integrity":"sha512-x4HvPgYfSZE5nz+v2Dr7wbRBdQGKY8a2dXAdLDuLrbz84BEVCqg8vfjeTcDHOWliJ5LA2ROoJQABzuS/8tBFMw==","signatures":[{"sig":"MEYCIQDuQHMdoPU5YxBx21mYnBnVx/bryOAv79Z8drUMKXAqpgIhAO7DnJ7RCCEvkcyI+W5Fcq7U/gMBJFlk3YVTxQU00Zgz","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":1015051},"main":"dist/index.js","types":"dist/index.d.ts","module":"dist/index.mjs","gitHead":"853ea2e039edc8a6e74a2362a5e08336bfe4b512","scripts":{"dev":"vite","docs":"typedoc","lint":"eslint src/**/*.ts","test":"jest","build":"tsup","format":"prettier --write src/**/*.ts","prepare":"husky","lint:fix":"eslint src/**/*.ts --fix","test:watch":"jest --watch","type-check":"tsc --noEmit","format:check":"prettier --check src/**/*.ts","test:coverage":"jest --coverage","prepublishOnly":"npm run build && npm run test"},"_npmUser":{"name":"devferanmi","email":"devferanmi@gmail.com"},"repository":{"url":"git+https://github.com/spiderocious/connectic.git","type":"git"},"_npmVersion":"10.9.2","description":"Connectic is a javascript library for pub sub messaging, event handling, and data synchronization in real-time applications.","directories":{"doc":"docs"},"_nodeVersion":"23.6.0","_hasShrinkwrap":false,"devDependencies":{"jest":"^29.7.0","tsup":"^8.5.0","vite":"^7.0.6","husky":"^9.1.7","eslint":"^9.31.0","ts-jest":"^29.4.0","typedoc":"^0.28.7","prettier":"^3.6.2","@eslint/js":"^9.31.0","typescript":"^5.8.3","@types/jest":"^30.0.0","@types/node":"^24.1.0","@commitlint/cli":"^19.8.1","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.3","@typescript-eslint/parser":"^8.38.0","@commitlint/config-conventional":"^19.8.1","@typescript-eslint/eslint-plugin":"^8.38.0"},"_npmOperationalInternal":{"tmp":"tmp/connectic_1.0.0_1753613410427_0.8385508139712907","host":"s3://npm-registry-packages-npm-production"}},"3.0.0":{"name":"connectic","version":"3.0.0","keywords":["event-bus","microfrontend","communication","state-management","pub-sub","request-response","real-time","data-synchronization","javascript","typescript","framework-agnostic","mfe","event-driven"],"author":"","license":"MIT","_id":"connectic@3.0.0","maintainers":[{"name":"devferanmi","email":"devferanmi@gmail.com"}],"homepage":"https://github.com/spiderocious/connectic#readme","bugs":{"url":"https://github.com/spiderocious/connectic/issues"},"dist":{"shasum":"393d58d2c2b6df723f59920113a2fb39f2c1e004","tarball":"https://registry.npmjs.org/connectic/-/connectic-3.0.0.tgz","fileCount":9,"integrity":"sha512-FQYZUkyPockCeFWv6Ansi14ofQcfrmgNZvLZgqlP9WU9757Xz7j4TZmIzpzODZ9tO7/85v4LMxQSN9cDHfHDNQ==","signatures":[{"sig":"MEUCIBP1S3fD6ucwvNdogkFEzg/BNLRGjPrGXhPkTaSZqu8CAiEA0YIzBhUcDn+sOdenjed0HaOOm59HrqnNit9cUj2ytHY=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":1091305},"main":"dist/index.js","types":"dist/index.d.ts","module":"dist/index.mjs","gitHead":"a10427bf59867605f801b68a5485ae0c0b672354","scripts":{"dev":"vite","docs":"typedoc","lint":"eslint src/**/*.ts","test":"jest","build":"tsup","format":"prettier --write src/**/*.ts","prepare":"husky","lint:fix":"eslint src/**/*.ts --fix","test:watch":"jest --watch","type-check":"tsc --noEmit","format:check":"prettier --check src/**/*.ts","test:coverage":"jest --coverage","prepublishOnly":"npm run build && npm run test"},"_npmUser":{"name":"devferanmi","email":"devferanmi@gmail.com"},"repository":{"url":"git+https://github.com/spiderocious/connectic.git","type":"git"},"_npmVersion":"10.9.2","description":"Connectic is a javascript library for pub sub messaging, event handling, and data synchronization in real-time applications.","directories":{"doc":"docs"},"_nodeVersion":"23.6.0","_hasShrinkwrap":false,"devDependencies":{"jest":"^29.7.0","tsup":"^8.5.0","vite":"^7.0.6","husky":"^9.1.7","eslint":"^9.31.0","ts-jest":"^29.4.0","typedoc":"^0.28.7","prettier":"^3.6.2","@eslint/js":"^9.31.0","typescript":"^5.8.3","@types/jest":"^30.0.0","@types/node":"^24.1.0","@commitlint/cli":"^19.8.1","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.3","@typescript-eslint/parser":"^8.38.0","@commitlint/config-conventional":"^19.8.1","@typescript-eslint/eslint-plugin":"^8.38.0"},"_npmOperationalInternal":{"tmp":"tmp/connectic_3.0.0_1753636069605_0.5593738414520606","host":"s3://npm-registry-packages-npm-production"}},"3.1.0":{"name":"connectic","version":"3.1.0","keywords":["event-bus","microfrontend","communication","state-management","pub-sub","request-response","real-time","data-synchronization","javascript","typescript","framework-agnostic","mfe","event-driven"],"author":"","license":"MIT","_id":"connectic@3.1.0","maintainers":[{"name":"devferanmi","email":"devferanmi@gmail.com"}],"homepage":"https://github.com/spiderocious/connectic#readme","bugs":{"url":"https://github.com/spiderocious/connectic/issues"},"dist":{"shasum":"eb3b80770710fa5c17e7029ea7c58455e23dceab","tarball":"https://registry.npmjs.org/connectic/-/connectic-3.1.0.tgz","fileCount":9,"integrity":"sha512-qF1n5KXIwCByrqiIz6nxrzKpAH7Cl4K7/6iW6Qs9hFFDiuT1L6fml74v/sENfu7pAZR9+eiuKaXS0yNlfbEQQA==","signatures":[{"sig":"MEQCIFi+/n4K7Qpk58nTaQ1Tmu7sgftPhxjncYQRU2QYBZj0AiBzxjzXISGCEZn9+Vxdw9WK+YQo+gOBclhJ0UvF7GPtFw==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":1110380},"main":"dist/index.js","types":"dist/index.d.ts","module":"dist/index.mjs","gitHead":"f424a55fb7f96457fdc131ed7f6cbf02d9008023","scripts":{"dev":"vite","docs":"typedoc","lint":"eslint src/**/*.ts","test":"jest","build":"tsup","format":"prettier --write src/**/*.ts","prepare":"husky","lint:fix":"eslint src/**/*.ts --fix","test:watch":"jest --watch","type-check":"tsc --noEmit","format:check":"prettier --check src/**/*.ts","test:coverage":"jest --coverage","prepublishOnly":"npm run build && npm run test"},"_npmUser":{"name":"devferanmi","email":"devferanmi@gmail.com"},"repository":{"url":"git+https://github.com/spiderocious/connectic.git","type":"git"},"_npmVersion":"10.9.2","description":"Connectic is a javascript library for pub sub messaging, event handling, and data synchronization in real-time applications.","directories":{"doc":"docs"},"_nodeVersion":"23.6.0","_hasShrinkwrap":false,"devDependencies":{"jest":"^29.7.0","tsup":"^8.5.0","vite":"^7.0.6","husky":"^9.1.7","eslint":"^9.31.0","ts-jest":"^29.4.0","typedoc":"^0.28.7","prettier":"^3.6.2","@eslint/js":"^9.31.0","typescript":"^5.8.3","@types/jest":"^30.0.0","@types/node":"^24.1.0","@commitlint/cli":"^19.8.1","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.3","@typescript-eslint/parser":"^8.38.0","@commitlint/config-conventional":"^19.8.1","@typescript-eslint/eslint-plugin":"^8.38.0"},"_npmOperationalInternal":{"tmp":"tmp/connectic_3.1.0_1753676810330_0.18070623167735533","host":"s3://npm-registry-packages-npm-production"}},"4.0.0":{"name":"connectic","version":"4.0.0","description":"Connectic is a javascript library for pub sub messaging, event handling, and data synchronization in real-time applications.","main":"dist/index.js","module":"dist/index.mjs","types":"dist/index.d.ts","directories":{"doc":"docs"},"scripts":{"dev":"vite","build":"tsup","test":"jest","test:watch":"jest --watch","test:coverage":"jest --coverage","lint":"eslint src/**/*.ts","lint:fix":"eslint src/**/*.ts --fix","format":"prettier --write src/**/*.ts","format:check":"prettier --check src/**/*.ts","type-check":"tsc --noEmit","docs":"typedoc","prepare":"husky","prepublishOnly":"npm run build && npm run test"},"keywords":["event-bus","microfrontend","communication","state-management","pub-sub","request-response","real-time","data-synchronization","javascript","typescript","framework-agnostic","mfe","event-driven"],"author":"","license":"MIT","repository":{"type":"git","url":"git+https://github.com/spiderocious/connectic.git"},"bugs":{"url":"https://github.com/spiderocious/connectic/issues"},"homepage":"https://github.com/spiderocious/connectic#readme","devDependencies":{"@commitlint/cli":"^19.8.1","@commitlint/config-conventional":"^19.8.1","@eslint/js":"^9.31.0","@types/jest":"^30.0.0","@types/node":"^24.1.0","@typescript-eslint/eslint-plugin":"^8.38.0","@typescript-eslint/parser":"^8.38.0","eslint":"^9.31.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.3","husky":"^9.1.7","jest":"^29.7.0","prettier":"^3.6.2","ts-jest":"^29.4.0","tsup":"^8.5.0","typedoc":"^0.28.7","typescript":"^5.8.3","vite":"^7.0.6"},"_id":"connectic@4.0.0","gitHead":"1aef51527f43a83059cb3ab826c20a5ef97c52b7","_nodeVersion":"23.6.0","_npmVersion":"10.9.2","dist":{"integrity":"sha512-/9AE7uKKxZH6AAWOKSOkNDKKqZBZsHjhmwY0oGOMyFc9swUxUAMJN+aWlaDeG1LY3/C1YCNyWna8VMzuvUxQlw==","shasum":"0247a3318d4250cf3aa5abab1da6934630299c15","tarball":"https://registry.npmjs.org/connectic/-/connectic-4.0.0.tgz","fileCount":7,"unpackedSize":267075,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQCIldOHXG2QIdIC01/+GD3D9IfH9zqdcVOs9TiCgT53iwIgCmAsTB09EOUedNNPsMlmP621POjM/BsADJVOWbil45M="}]},"_npmUser":{"name":"devferanmi","email":"devferanmi@gmail.com"},"maintainers":[{"name":"devferanmi","email":"devferanmi@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/connectic_4.0.0_1764380543010_0.5172209583449072"},"_hasShrinkwrap":false}},"time":{"created":"2025-07-27T10:50:10.426Z","modified":"2025-11-29T01:42:23.463Z","1.0.0":"2025-07-27T10:50:10.694Z","3.0.0":"2025-07-27T17:07:49.882Z","3.1.0":"2025-07-28T04:26:50.527Z","4.0.0":"2025-11-29T01:42:23.234Z"},"bugs":{"url":"https://github.com/spiderocious/connectic/issues"},"license":"MIT","homepage":"https://github.com/spiderocious/connectic#readme","keywords":["event-bus","microfrontend","communication","state-management","pub-sub","request-response","real-time","data-synchronization","javascript","typescript","framework-agnostic","mfe","event-driven"],"repository":{"type":"git","url":"git+https://github.com/spiderocious/connectic.git"},"description":"Connectic is a javascript library for pub sub messaging, event handling, and data synchronization in real-time applications.","maintainers":[{"name":"devferanmi","email":"devferanmi@gmail.com"}],"readme":"# 🚀 connectic\n\n[![TypeScript](https://img.shields.io/badge/TypeScript-007ACC?style=flat-square&logo=typescript&logoColor=white)](https://www.typescriptlang.org/)\n\n**Framework-agnostic event-driven communication library for modern JavaScript applications.**\n\nConnectic enables seamless communication between microfrontends, components, and services through a unified API that combines event bus patterns, reactive state management, and request/response communication with full TypeScript support.\n\n## ✨ Features\n\n### 🔄 **Event-Driven Architecture**\n- **Pub/Sub messaging** with automatic cleanup and memory leak prevention\n- **Request/Response patterns** with timeout handling and caching\n- **Cross-component communication** without tight coupling\n\n### 🏗️ **Microfrontend Ready**\n- **Cross-application state sharing** between different frameworks\n- **Namespace isolation** for clean separation of concerns  \n- **Module Federation compatible** with singleton dependency management\n\n### ⚡ **Reactive State Management**\n- **Shared state** with automatic synchronization across components\n- **Computed state** with dependency tracking (experimental)\n- **Type-safe state operations** with TypeScript generics\n\n### 🔧 **Advanced Features**\n- **Middleware system** for logging, validation, and custom logic\n- **Request/Response interceptors** for data transformation\n- **Built-in caching** with TTL and pattern-based invalidation\n- **Plugin architecture** for extensibility\n- **Memory management** with automatic cleanup and statistics\n\n## 🚀 Quick Start\n\n### Installation\n\n```bash\nnpm install connectic\n# or\nyarn add connectic\n# or\npnpm add connectic\n```\n\n### Basic Usage\n\n```typescript\nimport { createBus } from 'connectic'\n\n// Define your event and request types\ninterface Events {\n  'user:login': { userId: string; email: string }\n  'cart:updated': { items: CartItem[]; total: number }\n}\n\ninterface Requests {\n  'get:user:profile': {\n    request: { userId: string }\n    response: { id: string; name: string; email: string }\n  }\n}\n\n// Create a typed bus instance\nconst bus = createBus<Events, Requests>({ \n  name: 'my-app',\n  debug: true \n})\n\n// Event communication\nbus.on('user:login', ({ userId, email }) => {\n  console.log(`User ${userId} logged in: ${email}`)\n})\n\nbus.emit('user:login', { \n  userId: '123', \n  email: 'user@example.com' \n})\n\n// Request/Response patterns\nbus.respond('get:user:profile').handler(async ({ userId }) => {\n  return await fetchUserProfile(userId)\n})\n\nconst profile = await bus.request('get:user:profile', { userId: '123' })\n```\n\n### Shared State Management\n\n```typescript\n// Create reactive shared state\nconst userState = bus.createState('user', null)\nconst cartState = bus.createState('cart', [])\n\n// Subscribe to state changes\nuserState.subscribe((user) => {\n  console.log('User changed:', user)\n})\n\n// Update state\nuserState.set({ id: '123', name: 'John Doe' })\n\n// State automatically synchronizes across components/applications\n```\n\n## 🏗️ Architecture Patterns\n\n### Microfrontend Communication\n\n```typescript\n// Shell Application\nconst globalBus = createBus({ name: 'global' })\n\n// Microfrontend A (React)\nconst mfeA = getBus('global') // Gets existing instance\nmfeA.emit('navigation:change', { route: '/products' })\n\n// Microfrontend B (Vue)  \nconst mfeB = getBus('global') // Same instance\nmfeB.on('navigation:change', ({ route }) => {\n  router.push(route)\n})\n```\n\n### Service Layer Pattern\n\n```typescript\n// API Service\nclass UserService {\n  constructor(private bus: MFEBus) {\n    this.setupResponders()\n  }\n\n  private setupResponders() {\n    this.bus.respond('user:get').handler(async ({ id }) => {\n      return await this.fetchUser(id)\n    })\n    \n    this.bus.respond('user:create').handler(async (userData) => {\n      return await this.createUser(userData)\n    })\n  }\n}\n\n// Components can now use the service via requests\nconst user = await bus.request('user:get', { id: '123' })\n```\n\n### State Management Pattern\n\n```typescript\n// Centralized state management\nconst appState = {\n  user: bus.createState('user', null),\n  cart: bus.createState('cart', []),\n  theme: bus.createState('theme', 'light')\n}\n\n// Computed state (experimental)\nconst cartTotal = bus.createComputed(() => {\n  const items = appState.cart.get()\n  return items.reduce((sum, item) => sum + item.price, 0)\n})\n\n// React Hook integration\nfunction useAppState() {\n  const [user, setUser] = useState(appState.user.get())\n  \n  useEffect(() => {\n    return appState.user.subscribe(setUser)\n  }, [])\n  \n  return user\n}\n```\n\n## 🔧 Advanced Features\n\n### Built-in Plugins\n\nConnectic comes with powerful built-in plugins for common use cases:\n\n#### Logger Plugin\n\n```typescript\nimport { createBus, Plugins } from 'connectic'\n\nconst bus = createBus({ name: 'app' })\n\n// Enable comprehensive logging\nbus.use(new Plugins.Logger({\n  logEmits: true,       // Log event emissions\n  logRequests: true,    // Log request/response requests\n  logResponses: true,   // Log request/response responses\n  prefix: '[MyApp]'     // Custom log prefix\n}))\n\n// Selective logging\nbus.use(new Plugins.Logger({\n  logEmits: false,      // Only log requests/responses\n  logRequests: true,\n  logResponses: true,\n  prefix: '[API]'\n}))\n```\n\n#### Validator Plugin\n\n```typescript\n// Schema-based request validation\nbus.use(new Plugins.Validator({\n  'user:create': (payload) => {\n    if (!payload.email) return 'Email is required'\n    if (!payload.name) return 'Name is required'\n    return true // Valid\n  },\n  'user:update': (payload) => {\n    return payload.id ? true : 'User ID is required'\n  }\n}))\n\n// Requests are automatically validated\ntry {\n  await bus.request('user:create', { name: 'John' }) // Throws validation error\n} catch (error) {\n  console.log(error.message) // \"Email is required\"\n}\n```\n\n#### Rate Limiting Plugin\n\n```typescript\n// Limit requests per event\nbus.use(new Plugins.RateLimit(\n  10,     // Max 10 requests\n  60000   // Per 60 seconds\n))\n\n// Requests exceeding limit throw BusError with code 429\n```\n\n### Middleware System\n\n```typescript\nconst bus = createBus({\n  name: 'app',\n  middleware: [\n    {\n      name: 'logger',\n      handler: async (context, next) => {\n        console.log(`[${context.eventName}] started`)\n        const result = await next()\n        console.log(`[${context.eventName}] completed`)\n        return result\n      }\n    }\n  ]\n})\n\n// Add middleware at runtime\nbus.addHook('beforeEmit', (event, payload) => {\n  console.log(`Emitting ${event}`, payload)\n})\n\nbus.addHook('afterEmit', (event, payload) => {\n  console.log(`Emitted ${event}`)\n})\n```\n\n### Built-in Middleware\n\n```typescript\nimport { BuiltinMiddleware } from 'connectic'\n\n// Pre-built middleware for common tasks\nbus.use(BuiltinMiddleware.createLogger({ prefix: '[CUSTOM]' }))\nbus.use(BuiltinMiddleware.createValidator(schemas))\nbus.use(BuiltinMiddleware.createRateLimit(5, 10000))\n```\n\n### Plugin Architecture\n\n```typescript\n// Custom plugin\nconst analyticsPlugin = {\n  name: 'Analytics',\n  version: '1.0.0',\n  init: () => Promise.resolve(),\n  onEvent: (eventName, payload) => {\n    analytics.track(eventName, payload)\n  },\n  onRequest: (eventName, payload) => {\n    analytics.track(`request:${eventName}`, payload)\n  }\n}\n\nbus.use(analyticsPlugin)\n```\n\n### Request/Response Interceptors\n\nTransform request and response data with powerful interceptor system:\n\n```typescript\n// Request interceptors - transform outgoing requests\nbus.interceptRequest((event, payload) => {\n  return {\n    ...payload,\n    timestamp: Date.now(),\n    requestId: generateId()\n  }\n})\n\n// Response interceptors - transform incoming responses\nbus.interceptResponse((event, response) => {\n  return {\n    data: response,\n    receivedAt: Date.now(),\n    event\n  }\n})\n```\n\n### Built-in Interceptors\n\n```typescript\nimport { BuiltinInterceptors } from 'connectic'\n\n// Add timestamp to all requests\nbus.interceptRequest(BuiltinInterceptors.addTimestamp())\n\n// Validate responses\nbus.interceptResponse(BuiltinInterceptors.validateResponse((event, response) => {\n  return response && response.success === true\n}))\n\n// Transform response format\nbus.interceptResponse(BuiltinInterceptors.normalizeResponse({\n  dataField: 'data',\n  errorField: 'error',\n  successField: 'success'\n}))\n\n// Filter sensitive data from requests\nbus.interceptRequest(BuiltinInterceptors.filterSensitiveData(['password', 'token']))\n\n// Add performance tracking\nbus.interceptResponse(BuiltinInterceptors.addPerformanceMetrics((event, start, end) => {\n  console.log(`${event} took ${end - start}ms`)\n}))\n\n// Rate limiting\nbus.interceptRequest(BuiltinInterceptors.rateLimit(10, 60000))\n\n// Circuit breaker pattern\nbus.interceptRequest(BuiltinInterceptors.circuitBreaker(5, 30000))\n```\n\n### Interceptor Utils\n\n```typescript\nimport { InterceptorUtils } from 'connectic'\n\n// Combine multiple interceptors\nconst combinedInterceptor = InterceptorUtils.combineRequestInterceptors([\n  InterceptorUtils.addTimestamp(),\n  InterceptorUtils.addRequestId(),\n  InterceptorUtils.addAuthentication(() => getAuthToken())\n])\n\nbus.interceptRequest(combinedInterceptor)\n\n// Conditional interceptors\nbus.interceptRequest(\n  InterceptorUtils.conditionalRequest(\n    /^user:/, // Only for user events\n    InterceptorUtils.validateRequest(userValidator)\n  )\n)\n\n// One-time interceptor\nbus.interceptRequest(\n  InterceptorUtils.once(InterceptorUtils.addTimestamp())\n)\n\n// Debounced interceptor\nbus.interceptResponse(\n  InterceptorUtils.debounce(logResponse, 1000)\n)\n```\n\n### Caching & Performance\n\n```typescript\nconst bus = createBus({\n  name: 'app',\n  cache: { \n    defaultTtl: 300000, // 5 minutes\n    maxSize: 1000\n  }\n})\n\n// Requests are automatically cached\nconst user = await bus.request('get:user', { id: '123' }) // Fetches from API\nconst userAgain = await bus.request('get:user', { id: '123' }) // Returns from cache\n\n// Manual cache control\nbus.cache.invalidate('get:user:123')\nbus.cache.invalidatePattern('get:user:*')\nbus.cache.clear()\n\n// Cache utilities\nimport { CacheUtils } from 'connectic'\n\n// Custom cache strategies\nCacheUtils.createStrategy('LRU', { maxSize: 100 })\nCacheUtils.createStrategy('TTL', { defaultTtl: 60000 })\n```\n\n### Advanced Request Methods\n\n```typescript\n// Request with multiple responders\nconst responses = await bus.requestMany('search:products', \n  { query: 'laptop' },\n  { \n    maxResponders: 3,  // Wait for up to 3 responses\n    timeout: 5000      // 5 second timeout\n  }\n)\n\n// Batch requests\nconst results = await bus.requestBatch([\n  ['get:user', { id: '1' }],\n  ['get:posts', { userId: '1' }],\n  ['get:comments', { userId: '1' }]\n])\n\n// Request with custom options\nconst user = await bus.request('get:user', { id: '123' }, {\n  timeout: 10000,     // Custom timeout\n  cache: false,       // Skip cache\n  retries: 3          // Retry on failure\n})\n```\n\n### Namespacing\n\n```typescript\nconst globalBus = createBus({ name: 'app' })\n\n// Create isolated namespaces\nconst userNamespace = globalBus.namespace('user')\nconst cartNamespace = globalBus.namespace('cart')\n\n// Events are automatically namespaced\nuserNamespace.emit('login', { userId: '123' }) // Emits 'user:login'\ncartNamespace.emit('updated', { items: [] })   // Emits 'cart:updated'\n\n// But you can listen to them from the global bus\nglobalBus.on('user:login', handler)\nglobalBus.on('cart:updated', handler)\n```\n\n### Error Handling\n\nConnectic provides comprehensive error handling with detailed error information:\n\n```typescript\nimport { BusError, BusErrorCode, BusErrorFactory, isBusError, hasBusErrorCode } from 'connectic'\n\ntry {\n  await bus.request('nonexistent:service', {})\n} catch (error) {\n  if (isBusError(error)) {\n    console.log('Bus error:', error.message)\n    console.log('Error code:', error.code)\n    console.log('Context:', error.context)\n    \n    // Check specific error types\n    if (hasBusErrorCode(error, BusErrorCode.TIMEOUT)) {\n      console.log('Request timed out')\n    }\n  }\n}\n\n// Create custom errors\nthrow BusErrorFactory.timeout('my:request', 5000)\nthrow BusErrorFactory.notFound('user:123')\nthrow BusErrorFactory.unauthorized('admin:action')\nthrow BusErrorFactory.badRequest('invalid:payload', 'Missing required field')\n```\n\n### Advanced Utilities\n\n```typescript\n// Listener management\nbus.hasListeners('user:login')           // Check if event has listeners\nbus.getListenerCount('user:login')       // Get number of listeners\nbus.removeAllListeners('user:login')     // Remove all listeners for event\nbus.removeAllListeners()                 // Remove ALL listeners\n\n// State management\nbus.removeState('user')                  // Remove shared state\nbus.getState('user')                     // Get current state value\n\n// Bus lifecycle\nbus.isDestroyedState()                   // Check if bus is destroyed\nbus.getDetailedInfo()                    // Get comprehensive bus information\nbus.destroy()                            // Clean up and destroy bus\n```\n\n## 📖 API Reference\n\n### Factory Functions\n\n```typescript\n// Create a new bus instance\ncreateBus<Events, Requests>(config: BusConfig): MFEBus<Events, Requests>\n\n// Get existing bus instance\ngetBus<Events, Requests>(name: string): MFEBus<Events, Requests> | null\n\n// Get or create bus instance  \ngetOrCreateBus<Events, Requests>(config: BusConfig): MFEBus<Events, Requests>\n\n// Remove bus instance\nremoveBus(name: string): boolean\n\n// Clear all bus instances\nclearAllBuses(): void\n```\n\n### Core Methods\n\n```typescript\ninterface MFEBus<TEventMap, TRequestMap> {\n  // Event Communication\n  emit<K extends keyof TEventMap>(event: K, payload: TEventMap[K]): void\n  on<K extends keyof TEventMap>(event: K, handler: (payload: TEventMap[K]) => void): () => void\n  once<K extends keyof TEventMap>(event: K, handler: (payload: TEventMap[K]) => void): () => void\n  off<K extends keyof TEventMap>(event: K, handler: Function): void\n  removeAllListeners<K extends keyof TEventMap>(event?: K): void\n  \n  // Request/Response  \n  request<K extends keyof TRequestMap>(event: K, payload?, options?): Promise<Response>\n  requestMany<K extends keyof TRequestMap>(event: K, payload?, options?): Promise<Response[]>\n  requestBatch(requests: BatchRequest[]): Promise<any[]>\n  respond<K extends keyof TRequestMap>(event: K): ResponderBuilder<K>\n  \n  // State Management\n  createState<T>(key: string, initialValue: T): SharedState<T>\n  createComputed<T>(computeFn: () => T): ComputedState<T>\n  setState<K extends keyof TEventMap>(key: K, value: TEventMap[K]): void\n  getState<K extends keyof TEventMap>(key: K): TEventMap[K] | undefined\n  removeState<K extends keyof TEventMap>(key: K): void\n  \n  // Advanced Features\n  use(plugin: BusPlugin): this\n  namespace(name: string): MFEBus<TEventMap, TRequestMap>\n  addHook(type: HookType, handler: HookHandler): void\n  removeHook(type: HookType, handler: HookHandler): void\n  \n  // Interceptors\n  interceptRequest(interceptor: RequestInterceptor): void\n  interceptResponse(interceptor: ResponseInterceptor): void\n  \n  // Cache Management\n  cache: {\n    get(key: string): any\n    set(key: string, value: any, ttl?: number): void\n    invalidate(key: string): boolean\n    invalidatePattern(pattern: string): number\n    clear(): void\n  }\n  \n  // Utilities\n  hasListeners<K extends keyof TEventMap>(event: K): boolean\n  getListenerCount<K extends keyof TEventMap>(event: K): number\n  getStats(): BusStats\n  getDetailedInfo(): object\n  isDestroyedState(): boolean\n  destroy(): void\n}\n```\n\n### Factory & Registry Functions\n\n```typescript\n// Core factory functions\ncreateBus<Events, Requests>(config: BusConfig): MFEBus<Events, Requests>\ngetBus<Events, Requests>(name: string): MFEBus<Events, Requests> | null\ngetOrCreateBus<Events, Requests>(config: BusConfig): MFEBus<Events, Requests>\n\n// Registry management\nremoveBus(name: string): boolean\nclearAllBuses(): void\nlistBuses(): string[]\ngetAllBusStats(): Record<string, BusStats>\ngetRegistryInfo(): object\ncleanup(): void\n```\n\n### Built-in Exports\n\n```typescript\n// Built-in plugins\nimport { Plugins } from 'connectic'\nPlugins.Logger        // Comprehensive logging plugin\nPlugins.Validator     // Schema validation plugin  \nPlugins.RateLimit     // Request rate limiting plugin\n\n// Utility classes\nimport { \n  BuiltinMiddleware,    // Pre-built middleware functions\n  BuiltinInterceptors,  // Pre-built interceptor functions\n  InterceptorUtils,     // Interceptor helper utilities\n  SharedStateUtils,     // State management utilities\n  ComputedStateUtils,   // Computed state utilities\n  CacheUtils,           // Cache management utilities\n  RequestResponseUtils  // Request/response utilities\n} from 'connectic'\n\n// Error handling\nimport {\n  BusError,             // Custom error class\n  BusErrorCode,         // Error code constants\n  BusErrorFactory,      // Error creation utilities\n  isBusError,           // Error type checking\n  hasBusErrorCode,      // Error code checking\n  wrapError            // Error wrapping utility\n} from 'connectic'\n\n// Library metadata\nimport { VERSION, META } from 'connectic'\nconsole.log(META.version)    // \"1.0.0\"\nconsole.log(META.name)       // \"connectic\"\n```\n```\n\n## 📦 Framework Integration\n\n### React\n\n```typescript\n// Custom hook for reactive state\nfunction useBusState<T>(key: string, initialValue: T) {\n  const state = bus.createState(key, initialValue)\n  const [value, setValue] = useState(state.get())\n  \n  useEffect(() => {\n    return state.subscribe(setValue)\n  }, [state])\n  \n  return [value, state.set.bind(state)] as const\n}\n\n// Usage\nfunction UserProfile() {\n  const [user, setUser] = useBusState('user', null)\n  // Component automatically re-renders when user state changes\n}\n```\n\n### Vue 3\n\n```typescript\n// Composable for reactive state\nexport function useBusState<T>(key: string, initialValue: T) {\n  const state = bus.createState(key, initialValue)\n  const value = ref(state.get())\n  \n  state.subscribe((newValue) => {\n    value.value = newValue\n  })\n  \n  return {\n    value: readonly(value),\n    setValue: state.set.bind(state)\n  }\n}\n```\n\n### Angular\n\n```typescript\n@Injectable()\nexport class BusStateService {\n  getState<T>(key: string, initialValue: T) {\n    const state = bus.createState(key, initialValue)\n    return new BehaviorSubject(state.get()).pipe(\n      tap(() => state.subscribe(value => subject.next(value)))\n    )\n  }\n}\n```\n\n## 🔧 Configuration\n\n```typescript\ninterface BusConfig {\n  name: string                    // Unique bus identifier\n  debug?: boolean                 // Enable debug logging\n  middleware?: Middleware[]       // Custom middleware stack\n  plugins?: BusPlugin[]          // Plugin instances\n  cache?: {\n    defaultTtl?: number          // Default cache TTL in ms\n    maxSize?: number             // Maximum cache entries\n    strategy?: CacheStrategy     // Cache eviction strategy\n  }\n  maxListeners?: number          // Max listeners per event (default: 100)\n  namespace?: string             // Default namespace\n  requestTimeout?: number        // Default request timeout in ms (default: 5000)\n  retryOptions?: {\n    maxRetries?: number          // Maximum retry attempts\n    retryDelay?: number          // Delay between retries in ms\n    backoffFactor?: number       // Exponential backoff multiplier\n  }\n}\n\n// Advanced configuration examples\nconst bus = createBus({\n  name: 'production-app',\n  debug: process.env.NODE_ENV === 'development',\n  cache: {\n    defaultTtl: 300000,          // 5 minutes\n    maxSize: 10000,              // 10k entries\n    strategy: 'LRU'              // Least Recently Used eviction\n  },\n  requestTimeout: 10000,         // 10 second timeout\n  maxListeners: 500,             // High listener limit\n  retryOptions: {\n    maxRetries: 3,\n    retryDelay: 1000,\n    backoffFactor: 2\n  }\n})\n```\n\n## 🚀 Real-World Examples\n\n### E-commerce Microfrontend Architecture\n\n```typescript\n// Product Catalog (React MFE)\nconst catalog = getBus('ecommerce')\ncatalog.respond('product:search').handler(async ({ query, filters }) => {\n  return await searchProducts(query, filters)\n})\n\n// Shopping Cart (Vue MFE)  \nconst cart = getBus('ecommerce')\ncart.on('product:add-to-cart', async ({ productId, quantity }) => {\n  const product = await cart.request('product:get', { id: productId })\n  cartState.update(items => [...items, { ...product, quantity }])\n  cart.emit('cart:updated', { items: cartState.get() })\n})\n\n// Checkout (Angular MFE)\nconst checkout = getBus('ecommerce')\ncheckout.on('cart:updated', ({ items }) => {\n  this.orderSummary = this.calculateOrderSummary(items)\n})\n```\n\n### Real-time Dashboard\n\n```typescript\n// Data layer\nconst dashboard = createBus({ name: 'dashboard' })\n\n// WebSocket service\ndashboard.respond('metrics:subscribe').handler(async ({ metric }) => {\n  return websocket.subscribe(metric, (data) => {\n    dashboard.emit('metrics:updated', { metric, data })\n  })\n})\n\n// Chart components automatically update\ndashboard.on('metrics:updated', ({ metric, data }) => {\n  if (metric === 'sales') {\n    updateSalesChart(data)\n  }\n})\n```\n\n## 🧪 Testing\n\n```typescript\nimport { createBus, clearAllBuses, BusError, isBusError } from 'connectic'\n\ndescribe('My Application', () => {\n  let bus: MFEBus\n  \n  beforeEach(() => {\n    bus = createBus({ name: 'test-app' })\n  })\n  \n  afterEach(() => {\n    clearAllBuses() // Clean up for next test\n  })\n  \n  it('should handle user login flow', async () => {\n    const mockUser = { id: '123', name: 'John' }\n    \n    bus.respond('auth:login').handler(async () => mockUser)\n    \n    const loginSpy = jest.fn()\n    bus.on('user:logged-in', loginSpy)\n    \n    const user = await bus.request('auth:login', { email: 'test@example.com' })\n    bus.emit('user:logged-in', user)\n    \n    expect(loginSpy).toHaveBeenCalledWith(mockUser)\n  })\n  \n  it('should handle errors properly', async () => {\n    bus.respond('failing:service').handler(() => {\n      throw new Error('Service failed')\n    })\n    \n    try {\n      await bus.request('failing:service')\n    } catch (error) {\n      expect(isBusError(error)).toBe(true)\n      expect(error.message).toContain('Service failed')\n    }\n  })\n  \n  it('should validate listener counts', () => {\n    const handler = () => {}\n    bus.on('test:event', handler)\n    \n    expect(bus.hasListeners('test:event')).toBe(true)\n    expect(bus.getListenerCount('test:event')).toBe(1)\n    \n    bus.off('test:event', handler)\n    expect(bus.hasListeners('test:event')).toBe(false)\n  })\n  \n  it('should handle batch requests', async () => {\n    bus.respond('get:user').handler(async ({ id }) => ({ id, name: `User ${id}` }))\n    bus.respond('get:posts').handler(async ({ userId }) => [{ id: 1, userId, title: 'Post 1' }])\n    \n    const results = await bus.requestBatch([\n      ['get:user', { id: '1' }],\n      ['get:posts', { userId: '1' }]\n    ])\n    \n    expect(results).toHaveLength(2)\n    expect(results[0]).toEqual({ id: '1', name: 'User 1' })\n    expect(results[1]).toHaveLength(1)\n  })\n  \n  it('should handle state management', () => {\n    const userState = bus.createState('user', null)\n    const values: any[] = []\n    \n    userState.subscribe((value) => values.push(value))\n    \n    userState.set({ id: '123', name: 'John' })\n    userState.set({ id: '456', name: 'Jane' })\n    \n    expect(values).toEqual([\n      null,\n      { id: '123', name: 'John' },\n      { id: '456', name: 'Jane' }\n    ])\n    \n    bus.removeState('user')\n    expect(bus.getState('user')).toBeUndefined()\n  })\n}\n```\n\n## 📊 Performance & Memory Management\n\n### Built-in Optimizations\n\n- **Automatic cleanup** of event listeners and state subscriptions\n- **Memory leak prevention** with configurable listener limits\n- **Efficient data structures** using Map/Set for O(1) operations\n- **Request caching** to reduce redundant API calls\n- **Dead code elimination** for smaller bundle sizes\n\n### Memory Usage Monitoring\n\n```typescript\n// Get detailed statistics\nconst stats = bus.getStats()\nconsole.log(`Active listeners: ${stats.activeListeners}`)\nconsole.log(`Total events: ${stats.totalEvents}`)\nconsole.log(`Total requests: ${stats.totalRequests}`)\nconsole.log(`Memory usage: ${stats.memoryUsage} bytes`)\nconsole.log(`Cache size: ${stats.cacheSize} entries`)\n\n// Get comprehensive component information\nconst details = bus.getDetailedInfo()\nconsole.log('Event bus:', details.eventBus)\nconsole.log('State manager:', details.stateManager)\nconsole.log('Cache manager:', details.cacheManager)\nconsole.log('Request manager:', details.requestManager)\nconsole.log('Interceptor manager:', details.interceptorManager)\n\n// Registry-wide statistics\nconst allStats = getAllBusStats()\nconsole.log('All bus instances:', allStats)\n\n// Registry health information\nconst registryInfo = getRegistryInfo()\nconsole.log('Registry status:', registryInfo)\n\n// Cleanup operations\ncleanup() // Performs maintenance on registry\n```\n\n## 🤝 Contributing\n\nWe welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.\n\n### Development Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/spiderocious/connectic.git\ncd connectic\n\n# Install dependencies\nnpm install\n\n# Run tests\nnpm test\n\n# Run tests in watch mode\nnpm run test:watch\n\n# Build the library\nnpm run build\n\n# Run type checking\nnpm run type-check\n\n# Run linting\nnpm run lint\n```\n\n### Project Structure\n\n```\nsrc/\n├── core/           # Core implementations\n│   ├── event-bus.ts      # Event system\n│   ├── registry.ts       # Bus instance management\n│   ├── middleware.ts     # Middleware & plugins\n│   ├── shared-state.ts   # State management\n│   ├── computed-state.ts # Computed state (experimental)\n│   ├── cache.ts          # Caching layer\n│   └── request-response.ts # Request/response patterns\n├── errors/         # Error handling\n├── types.ts        # TypeScript definitions\n└── index.ts        # Main exports\n```\n\n## 📄 License\n\nMIT © [connectic](LICENSE)\n\n## 🔗 Links\n\n- [Documentation](https://github.com/spiderocious/connectic/wiki)\n- [API Reference](https://github.com/spiderocious/connectic/blob/main/docs/api.md)\n- [Examples](https://github.com/spiderocious/connectic/tree/main/examples)\n- [Changelog](https://github.com/spiderocious/connectic/blob/main/CHANGELOG.md)\n- [Issues](https://github.com/spiderocious/connectic/issues)\n\n---\n\n**Made with ❤️ for the modern JavaScript ecosystem**\n\n*\"Connecting applications, components, and services with simplicity and type safety\"*\n","readmeFilename":"README.md"}