connectic
Version:
Connectic is a javascript library for pub sub messaging, event handling, and data synchronization in real-time applications.
2 lines • 61.8 kB
JavaScript
'use strict';Object.defineProperty(exports,'__esModule',{value:true});/* connectic - description */
var E=(h=>(h[h.NOT_FOUND=404]="NOT_FOUND",h[h.FORBIDDEN=403]="FORBIDDEN",h[h.TIMEOUT=408]="TIMEOUT",h[h.CONFLICT=409]="CONFLICT",h[h.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",h[h.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",h[h.INTERNAL_ERROR=500]="INTERNAL_ERROR",h[h.BAD_REQUEST=400]="BAD_REQUEST",h[h.GONE=410]="GONE",h[h.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",h[h.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",h))(E||{}),p=class a extends Error{constructor(t,r,s){super(t);this.busCode=r;this.details=s;this.name="BusError",Object.setPrototypeOf(this,a.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,a);}toJSON(){return {name:this.name,message:this.message,busCode:this.busCode,details:this.details,stack:this.stack}}toString(){return `${this.name} [${this.busCode}]: ${this.message}`}isRetryable(){return [408,429,503,500].includes(this.busCode)}isClientError(){return this.busCode>=400&&this.busCode<500}isServerError(){return this.busCode>=500&&this.busCode<600}},u=class{static notFound(e,t){return new p(`No responders available for event: ${e}`,404,{event:e,...t})}static timeout(e,t,r){return new p(`Request timeout after ${t}ms for event: ${e}`,408,{event:e,timeoutMs:t,...r})}static forbidden(e,t,r){return new p(`Access forbidden for event: ${e}. Reason: ${t}`,403,{event:e,reason:t,...r})}static conflict(e,t,r){return new p(`Multiple responders (${t}) for event: ${e}`,409,{event:e,responderCount:t,...r})}static payloadTooLarge(e,t,r,s){return new p(`Payload size ${t} bytes exceeds limit of ${r} bytes for event: ${e}`,413,{event:e,size:t,limit:r,...s})}static tooManyRequests(e,t,r,s){return new p(`Rate limit exceeded: ${t} requests per ${r}ms for event: ${e}`,429,{event:e,limit:t,window:r,...s})}static internal(e,t,r){return new p(`Internal error: ${e}`,500,{originalError:t?.message,stack:t?.stack,...r})}static badRequest(e,t,r){return new p(`Bad request for event: ${e}. ${t}`,400,{event:e,reason:t,...r})}static gone(e,t){return new p(`Responder for event: ${e} is no longer available`,410,{event:e,...t})}static serviceUnavailable(e,t,r){let s=t?`Service unavailable for event: ${e}. Retry after ${t}ms`:`Service temporarily unavailable for event: ${e}`;return new p(s,503,{event:e,retryAfter:t,...r})}static unprocessableEntity(e,t,r){return new p(`Unprocessable request for event: ${e}. ${t}`,422,{event:e,reason:t,...r})}};function J(a){return a instanceof p}function se(a,e){return J(a)&&a.busCode===e}function c(a,e){if(J(a))return e&&!a.details?.event?new p(a.message,a.busCode,{...a.details,event:e,wrappedFrom:e}):a;if(a instanceof Error){let t=u.internal(a.message,a,{event:e});return a.stack&&(t.stack=a.stack),t}return u.internal(`Unknown error: ${String(a)}`,void 0,{event:e,originalError:a})}var ne={INVALID_EVENT_NAME:"Event name must be a non-empty string",INVALID_PAYLOAD:"Event payload must be serializable",INVALID_HANDLER:"Event handler must be a function",INVALID_TIMEOUT:"Timeout must be a positive number",INVALID_RETRIES:"Retries must be a non-negative number",BUS_DESTROYED:"Bus instance has been destroyed",MIDDLEWARE_ERROR:"Middleware execution failed",CACHE_ERROR:"Cache operation failed",STATE_NOT_FOUND:"State key not found",COMPUTED_CIRCULAR_DEPENDENCY:"Circular dependency detected in computed state"};function D(a,e,t){return u.badRequest("validation",`Invalid ${a}: expected ${t}, got ${typeof e}`,{field:a,value:e,expected:t})}function j(a=16){let e=Date.now().toString(36),t=Array.from({length:a},()=>Math.random().toString(36).charAt(2)).join("");return `${e}_${t}`}function R(a){return typeof a=="string"&&a.length>0&&a.length<=255&&!/^\s|\s$/.test(a)}function Q(a){return typeof a=="number"&&a>0&&a<=Number.MAX_SAFE_INTEGER&&Number.isFinite(a)}function X(a){return typeof a=="number"&&a>=0&&a<=100&&Number.isInteger(a)}function ie(a){return typeof a=="function"}function b(a){if(a===null||typeof a!="object")return a;if(typeof structuredClone<"u")try{return structuredClone(a)}catch{}try{return JSON.parse(JSON.stringify(a))}catch(e){throw u.internal(`Failed to clone object: ${e instanceof Error?e.message:String(e)}`,e instanceof Error?e:void 0,{originalObject:a})}}function te(){let a="__CONNECTIC_BUS_REGISTRY_v1__";return typeof window<"u"?(window[a]||(window[a]=new Map),window[a]):typeof global<"u"?(global[a]||(global[a]=new Map),global[a]):typeof globalThis<"u"?(globalThis[a]||(globalThis[a]=new Map),globalThis[a]):(W||(W=new Map),W)}var W;function T(a,e,t){try{return a()}catch(r){return console.warn(`Error in ${e}:`,r),t}}function v(a){let e=new WeakSet;function t(r){return r==null?0:typeof r=="boolean"?4:typeof r=="number"?8:typeof r=="string"?r.length*2:typeof r=="function"?r.toString().length*2:e.has(r)?0:(e.add(r),Array.isArray(r)?r.reduce((s,n)=>s+t(n),0):typeof r=="object"?Object.keys(r).reduce((s,n)=>s+n.length*2+t(r[n]),0):0)}return t(a)}function ae(a){let e=0;if(a.length===0)return e;for(let t=0;t<a.length;t++){let r=a.charCodeAt(t);e=(e<<5)-e+r,e=e&e;}return Math.abs(e)}function N(a,e){if(!e)return a;try{let t=JSON.stringify(e),r=ae(t);return `${a}:${r}`}catch{return `${a}:${Date.now()}`}}function m(a,e,t,r){if(!R(a))throw D("event",a,"non-empty string");if(e!==void 0&&!ie(e))throw D("handler",e,"function");}function Z(a){return new Promise(e=>setTimeout(e,a))}function ee(a,e=1e3,t=3e4){let r=e*Math.pow(2,a);return Math.min(r,t)}var q=class{constructor(){this.listeners=new Map;this.stats={totalEvents:0,totalSubscriptions:0,totalUnsubscriptions:0,errorCount:0};this.isDestroyed=false;this.maxListeners=100;}emit(e,t){this.throwIfDestroyed();try{m(e),this.stats.totalEvents++;let r=this.listeners.get(e);if(!r||r.size===0)return;r.forEach(s=>{T(()=>s(t),`event handler for '${e}'`);});}catch(r){throw this.stats.errorCount++,c(r,e)}}on(e,t){this.throwIfDestroyed();try{m(e,t),this.listeners.has(e)||this.listeners.set(e,new Set);let r=this.listeners.get(e);if(r.size>=this.maxListeners)throw u.internal(`Maximum listeners (${this.maxListeners}) exceeded for event: ${e}`,void 0,{event:e,currentListeners:r.size});return r.add(t),this.stats.totalSubscriptions++,()=>this.off(e,t)}catch(r){throw this.stats.errorCount++,c(r,e)}}once(e,t){this.throwIfDestroyed();let r=false,s=null,n=i=>{if(!r){r=true,s&&(s(),s=null);try{t(i);}catch(o){console.error(`Error in once handler for ${e}:`,o);}}};return s=this.on(e,n),()=>{r||(r=true,s&&(s(),s=null));}}off(e,t){this.throwIfDestroyed();try{m(e,t);let r=this.listeners.get(e);if(!r)return;r.delete(t)&&this.stats.totalUnsubscriptions++,r.size===0&&this.listeners.delete(e);}catch(r){throw this.stats.errorCount++,c(r,e)}}removeAllListeners(e){this.throwIfDestroyed();try{if(e!==void 0){m(e);let t=this.listeners.get(e);t&&(this.stats.totalUnsubscriptions+=t.size,this.listeners.delete(e));}else {let t=0;this.listeners.forEach(r=>{t+=r.size;}),this.stats.totalUnsubscriptions+=t,this.listeners.clear();}}catch(t){throw this.stats.errorCount++,c(t,e)}}getListenerCount(e){this.throwIfDestroyed();try{return m(e),this.listeners.get(e)?.size||0}catch(t){throw this.stats.errorCount++,c(t,e)}}hasListeners(e){this.throwIfDestroyed();try{return m(e),this.getListenerCount(e)>0}catch(t){throw this.stats.errorCount++,c(t,e)}}getEventNames(){return this.throwIfDestroyed(),Array.from(this.listeners.keys())}getStats(){let e=Array.from(this.listeners.values()).reduce((r,s)=>r+s.size,0),t=v(this.listeners);return {totalEvents:this.stats.totalEvents,totalRequests:0,activeListeners:e,cacheSize:0,memoryUsage:t}}getDetailedStats(){return {...this.getStats(),totalSubscriptions:this.stats.totalSubscriptions,totalUnsubscriptions:this.stats.totalUnsubscriptions,errorCount:this.stats.errorCount,eventCount:this.listeners.size,maxListenersPerEvent:this.maxListeners,isDestroyed:this.isDestroyed}}setMaxListeners(e){if(typeof e!="number"||e<1||!Number.isInteger(e))throw u.badRequest("setMaxListeners","Max listeners must be a positive integer",{provided:e});this.maxListeners=e;}getMaxListeners(){return this.maxListeners}isDestroyedState(){return this.isDestroyed}destroy(){if(!this.isDestroyed)try{this.listeners.clear(),this.stats={totalEvents:0,totalSubscriptions:0,totalUnsubscriptions:0,errorCount:0},this.isDestroyed=!0;}catch(e){throw this.isDestroyed=true,c(e,"destroy")}}createNamespace(e){if(this.throwIfDestroyed(),!R(e))throw u.badRequest("createNamespace","Namespace must be a valid event name",{namespace:e});return new O(this,e)}throwIfDestroyed(){if(this.isDestroyed)throw u.gone("event-bus","Event bus has been destroyed")}},O=class{constructor(e,t){this.eventBus=e;this.namespace=t;this.isDestroyed=false;}emit(e,t){this.eventBus.emit(`${this.namespace}:${e}`,t);}on(e,t){return this.eventBus.on(`${this.namespace}:${e}`,t)}once(e,t){this.throwIfDestroyed();let r=false,s=null,n=i=>{if(!r){r=true,s&&(s(),s=null);try{t(i);}catch(o){console.error(`Error in once handler for ${e}:`,o);}}};return s=this.on(e,n),()=>{r||(r=true,s&&(s(),s=null));}}off(e,t){this.eventBus.off(`${this.namespace}:${e}`,t);}removeAllListeners(e){if(e!==void 0)this.eventBus.removeAllListeners(`${this.namespace}:${e}`);else {let t=this.eventBus.getEventNames(),r=`${this.namespace}:`;t.filter(s=>s.startsWith(r)).forEach(s=>this.eventBus.removeAllListeners(s));}}getListenerCount(e){return this.eventBus.getListenerCount(`${this.namespace}:${e}`)}hasListeners(e){return this.eventBus.hasListeners(`${this.namespace}:${e}`)}getEventNames(){let e=this.eventBus.getEventNames(),t=`${this.namespace}:`;return e.filter(r=>r.startsWith(t)).map(r=>r.substring(t.length))}getNamespace(){return this.namespace}throwIfDestroyed(){if(this.isDestroyed)throw u.gone("event-bus","Event bus has been destroyed")}destroy(){this.isDestroyed=true,this.removeAllListeners();}};var y=class{static initialize(){if(this.isInitialized)return;let e="CONNECTIC_INITIALIZING",t="CONNECTIC_INSTANCES";try{let r=te();if(r.has(e)){let s=0;for(;r.has(e)&&s<100;){let n=Math.min(s*10,100),i=Date.now();for(;Date.now()-i<n;);s++;}if(r.has(e))throw new Error("Registry initialization deadlock detected")}r.set(e,!0);try{r.has(t)?this.instances=r.get(t):r.set(t,this.instances),this.isInitialized=!0;}finally{r.delete(e);}}catch(r){console.warn("Failed to initialize global bus registry, using fallback storage:",r),this.fallbackStore=new Map,this.isInitialized=true;}}static getStorage(){return this.initialize(),this.fallbackStore||this.instances}static create(e,t){try{if(!R(e.name))throw u.badRequest("registry.create","Bus name must be a valid identifier",{name:e.name});let r=this.getStorage();if(r.has(e.name)){let n=r.get(e.name);if(n.isDestroyedState())r.delete(e.name);else return console.warn(`Bus with name "${e.name}" already exists. Returning existing instance.`),n}let s=new t(e);return r.set(e.name,s),this.setupBusCleanup(e.name,s),s}catch(r){throw c(r,`registry.create:${e.name}`)}}static get(e){try{if(!R(e))throw u.badRequest("registry.get","Bus name must be a valid identifier",{name:e});let t=this.getStorage(),r=t.get(e);return r?r.isDestroyedState()?(t.delete(e),null):r:null}catch(t){throw c(t,`registry.get:${e}`)}}static has(e){try{if(!R(e))return !1;let t=this.getStorage(),r=t.get(e);return r?r.isDestroyedState()?(t.delete(e),!1):!0:!1}catch(t){return console.warn(`Error checking bus existence for "${e}":`,t),false}}static remove(e){try{if(!R(e))throw u.badRequest("registry.remove","Bus name must be a valid identifier",{name:e});let t=this.getStorage(),r=t.get(e);if(!r)return !1;try{r.isDestroyedState()||r.destroy();}catch(s){console.warn(`Error destroying bus "${e}":`,s);}return t.delete(e)}catch(t){throw c(t,`registry.remove:${e}`)}}static clear(){try{let e=this.getStorage();e.forEach((t,r)=>{try{t.isDestroyedState()||t.destroy();}catch(s){console.warn(`Error destroying bus "${r}" during clear:`,s);}}),e.clear();}catch(e){throw c(e,"registry.clear")}}static getAll(){try{let e=this.getStorage(),t=[];return e.forEach((r,s)=>{r.isDestroyedState()?e.delete(s):t.push(s);}),t}catch(e){throw c(e,"registry.getAll")}}static getAllStats(){try{let e=this.getStorage(),t={};return e.forEach((r,s)=>{if(!r.isDestroyedState())try{t[s]=r.getStats();}catch(n){t[s]={error:n instanceof Error?n.message:String(n)};}}),t}catch(e){throw c(e,"registry.getAllStats")}}static getRegistryInfo(){try{let e=this.getStorage(),t=0,r=0;return e.forEach(s=>{s.isDestroyedState()?r++:t++;}),{totalBuses:e.size,validBuses:t,destroyedBuses:r,isInitialized:this.isInitialized,usingFallbackStorage:this.fallbackStore!==null,storageType:this.fallbackStore?"fallback":"global"}}catch(e){return {error:e instanceof Error?e.message:String(e),isInitialized:this.isInitialized,usingFallbackStorage:this.fallbackStore!==null}}}static cleanup(){try{let e=this.getStorage(),t=[];e.forEach((r,s)=>{r.isDestroyedState()&&t.push(s);}),t.forEach(r=>{e.delete(r);}),typeof global<"u"&&global.gc&&global.gc();}catch(e){console.warn("Registry cleanup failed:",e);}}static setupBusCleanup(e,t){let r=t.destroy.bind(t);t.destroy=()=>{try{r();}finally{this.getStorage().delete(e);}};}static _reset(){this.instances.clear(),this.fallbackStore=null,this.isInitialized=false;}};y.instances=new Map,y.fallbackStore=null,y.isInitialized=false;var M=class{constructor(e){this.bus=e;this.hooks=new Map;this.isDestroyed=false;this.plugins=[];this.pluginDependencies=new Map;}addPlugin(e){this.throwIfDestroyed();try{if(!e||typeof e!="object")throw u.badRequest("addPlugin","Plugin must be an object",{plugin:e});if(typeof e.name!="string"||!e.name.trim())throw u.badRequest("addPlugin","Plugin must have a non-empty name",{plugin:e.name});if(typeof e.install!="function")throw u.badRequest("addPlugin","Plugin must have an install function",{plugin:e.name});if(this.plugins.some(r=>r.name===e.name))throw u.conflict("addPlugin",1,{message:`Plugin "${e.name}" is already installed`});let t=this.getPluginDependencies(e);this.pluginDependencies.set(e.name,t);for(let r of t)if(!this.hasPlugin(r))throw u.badRequest("addPlugin",`Plugin "${e.name}" depends on "${r}" which is not installed`,{plugin:e.name,missingDependency:r});e.install(this.bus),this.plugins.push(e);}catch(t){throw c(t,`addPlugin:${e?.name||"unknown"}`)}}removePlugin(e){this.throwIfDestroyed();try{let t=this.plugins.findIndex(s=>s.name===e);if(t===-1)return !1;let r=this.plugins[t];if(typeof r.uninstall=="function")try{r.uninstall(this.bus);}catch(s){console.warn(`Error uninstalling plugin "${e}":`,s);}return this.plugins.splice(t,1),!0}catch(t){throw c(t,`removePlugin:${e}`)}}getPlugins(){return this.plugins.map(e=>e.name)}hasPlugin(e){return this.plugins.some(t=>t.name===e)}getPluginDependencies(e){return "dependencies"in e&&Array.isArray(e.dependencies)?e.dependencies:[]}addHook(e,t){this.throwIfDestroyed();try{if(this.hooks.has(e)||this.hooks.set(e,[]),typeof t!="function")throw u.badRequest("addHook","Hook handler must be a function",{type:e,handler:typeof t});let r=this.hooks.get(e)||[];r.push(t),this.hooks.set(e,r);}catch(r){throw c(r,`addHook:${e}`)}}removeHook(e,t){this.throwIfDestroyed();try{let r=this.hooks.get(e);if(!r)return;let s=r.indexOf(t);s>-1&&(r.splice(s,1),this.hooks.set(e,r));}catch(r){throw c(r,`removeHook:${e}`)}}runHooks(e,t,r){this.throwIfDestroyed();try{let s=this.hooks.get(e);if(!s||s.length===0)return;s.forEach((n,i)=>{T(()=>n(t,r),`${e} hook #${i} for event '${t}'`);});}catch(s){throw c(s,`runHooks:${e}:${t}`)}}getStats(){return {pluginCount:this.plugins.length,plugins:this.plugins.map(e=>e.name),hookCounts:{beforeEmit:(this.hooks.get("beforeEmit")||[]).length,afterEmit:(this.hooks.get("afterEmit")||[]).length,beforeOn:(this.hooks.get("beforeOn")||[]).length,afterOn:(this.hooks.get("afterOn")||[]).length},totalHooks:Array.from(this.hooks.values()).reduce((e,t)=>e+t.length,0),isDestroyed:this.isDestroyed}}destroy(){if(!this.isDestroyed)try{this.calculateDestructionOrder().forEach(t=>{try{typeof t.uninstall=="function"&&t.uninstall(this.bus);}catch(r){console.warn(`Error uninstalling plugin "${t.name}" during destroy:`,r);}}),this.hooks.clear(),this.plugins=[],this.pluginDependencies.clear(),this.isDestroyed=!0;}catch(e){throw this.isDestroyed=true,c(e,"middleware.destroy")}}calculateDestructionOrder(){let e=[],t=new Set,r=new Set,s=n=>{if(t.has(n)||r.has(n))return;r.add(n),this.plugins.forEach(o=>{(this.pluginDependencies.get(o.name)||[]).includes(n)&&!t.has(o.name)&&s(o.name);}),r.delete(n),t.add(n);let i=this.plugins.find(o=>o.name===n);i&&e.push(i);};return this.plugins.forEach(n=>{s(n.name);}),e}isDestroyedState(){return this.isDestroyed}throwIfDestroyed(){if(this.isDestroyed)throw u.gone("middleware","Middleware manager has been destroyed")}},C=class{constructor(e,t){this.eventName=e;this.bus=t;this.middlewares=[];this.handlerFn=null;this.isInstalled=false;this.composedHandler=null;}use(e){if(this.isInstalled)throw u.badRequest("responder.use","Cannot add middleware after handler is installed",{event:this.eventName});if(typeof e!="function")throw u.badRequest("responder.use","Middleware must be a function",{event:this.eventName,middleware:typeof e});return this.middlewares.push(e),this}handler(e){if(this.isInstalled)throw u.badRequest("responder.handler","Handler already installed for this responder",{event:this.eventName});if(typeof e!="function")throw u.badRequest("responder.handler","Handler must be a function",{event:this.eventName,handler:typeof e});this.handlerFn=e,this.installResponder(),this.isInstalled=true;}destroy(){if(!this.isInstalled)throw u.badRequest("responder.destroy","Responder has not been installed yet",{event:this.eventName});if(!this.composedHandler){console.warn(`Responder for event "${this.eventName}" has no composed handler to destroy`);return}this.bus.off(this.eventName,this.composedHandler),this.isInstalled=false,this.middlewares=[],this.handlerFn=null,this.composedHandler=null;}installResponder(){let e=async t=>{try{let r=await this.executeMiddleware(t);if(this.handlerFn){let s=await this.handlerFn(r);return r.__correlationId&&this.bus.emit(`response:${r.__correlationId}`,{__correlationId:r.__correlationId,response:s}),s}throw u.internal("No handler function available",void 0,{event:this.eventName})}catch(r){throw t.__correlationId&&this.bus.emit(`response:${t.__correlationId}`,{__correlationId:t.__correlationId,__error:r}),r instanceof p?r:c(r,this.eventName)}};this.composedHandler=e,this.bus.on(this.eventName,e);}async executeMiddleware(e){if(this.middlewares.length===0)return e;let t=e,r=false,s,n={startTime:Date.now(),executedMiddleware:[]};for(let i=0;i<this.middlewares.length&&!r;i++){let o=this.middlewares[i],d=false,l=null;try{if(await new Promise((f,h)=>{let g=()=>{if(d){h(new p("next() called multiple times in middleware",429,{event:this.eventName,middlewareIndex:i,executionContext:n}));return}d=!0,f();},w=S=>{r=!0,s=S,d=!0,f();};try{let S=Promise.resolve(o(t,g,w)),I=new Promise((Y,re)=>{setTimeout(()=>{re(new p("Middleware timeout after 30 seconds",408,{event:this.eventName,middlewareIndex:i}));},3e4);});Promise.race([S,I]).catch(h);}catch(S){h(S);}}),n.executedMiddleware.push(i),r)throw u.forbidden(this.eventName,s||"Request cancelled by middleware",{middlewareIndex:i,executionContext:n});if(!d)throw u.forbidden(this.eventName,"Middleware did not call next() or cancel()",{middlewareIndex:i,executionContext:n})}catch(f){throw l=f instanceof Error?f:new Error(String(f)),console.warn(`Middleware ${i} failed for event ${this.eventName}:`,l.message),c(l,`${this.eventName}:middleware:${i}`)}}return t}getInfo(){return {eventName:this.eventName,middlewareCount:this.middlewares.length,isInstalled:this.isInstalled,hasHandler:this.handlerFn!==null}}},A=class{static logger(e={}){let{logPayload:t=true,prefix:r="[connectic]"}=e;return (s,n)=>{let i=new Date().toISOString();t?console.log(`${r} ${i} Request:`,s):console.log(`${r} ${i} Request received`),n();}}static validator(e){return (t,r,s)=>{let n=e(t);n===true?r():s(typeof n=="string"?n:"Validation failed");}}static rateLimit(e){let t=new Map,{maxRequests:r,windowMs:s}=e;return (n,i,o)=>{let d=n?.key,l=Date.now(),f=l-s,g=(t.get(d)||[]).filter(w=>w>f);if(g.length>=r){o(`Rate limit exceeded: ${r} requests per ${s}ms`);return}g.push(l),t.set(d,g),i();}}static timeout(e){return async(t,r,s)=>{let n=new Promise((o,d)=>{setTimeout(()=>{d(new p(`Middleware timeout after ${e}ms`,408));},e);}),i=new Promise(o=>{r(),o();});try{await Promise.race([i,n]);}catch(o){if(o instanceof p&&o.busCode===408)s("Middleware execution timeout");else throw o}}}};var x=class{constructor(e){this.bus=e;this.states=new Map;this.isDestroyed=false;this.dependencyGraph=new Map;this.currentAccessStack=new Set;}createState(e,t){this.throwIfDestroyed();try{if(m(e),this.states.has(e)){let s=this.states.get(e);return console.warn(`State "${e}" already exists. Returning existing instance.`),s}let r=new k(e,t,this.bus,new WeakRef(this));return this.states.set(e,r),r}catch(r){throw c(r,`createState:${e}`)}}getState(e){this.throwIfDestroyed();try{return m(e),this.states.get(e)}catch(t){throw c(t,`getState:${e}`)}}getStateValue(e){this.throwIfDestroyed();try{return this.getState(e)?.get()}catch(t){throw c(t,`getStateValue:${e}`)}}setState(e,t){this.throwIfDestroyed();try{m(e);let r=this.getState(e);r?r.set(t):r=this.createState(e,t);}catch(r){throw c(r,`setState:${e}`)}}removeState(e){this.throwIfDestroyed();try{m(e);let t=this.states.get(e);return t?(t.destroy(),this.states.delete(e),this.bus.emit(`state:${e}:removed`,void 0),!0):!1}catch(t){throw c(t,`removeState:${e}`)}}getStateKeys(){return this.throwIfDestroyed(),Array.from(this.states.keys())}getStats(){let e=this.states.size,t=0,r=0;return this.states.forEach(s=>{let n=s.getStats();t+=n.subscriberCount,r+=n.memoryUsage;}),{totalStates:e,totalSubscribers:t,totalMemoryUsage:r,averageSubscribersPerState:e>0?t/e:0,stateKeys:Array.from(this.states.keys()),isDestroyed:this.isDestroyed}}destroy(){if(!this.isDestroyed)try{this.states.forEach((e,t)=>{try{e.destroy();}catch(r){console.warn(`Error destroying state "${t}":`,r);}}),this.states.clear(),this.isDestroyed=!0;}catch(e){throw this.isDestroyed=true,c(e,"sharedStateManager.destroy")}}_handleStateDestroyed(e){this.states.delete(e),this.dependencyGraph.delete(e);for(let t of this.dependencyGraph.values())t.delete(e);}_trackStateAccess(e,t){if(e===t)return;let r=this.dependencyGraph.get(e);if(r||(r=new Set,this.dependencyGraph.set(e,r)),r.add(t),this.hasCircularDependency(e,t))throw u.badRequest("circularDependency",`Circular dependency detected: ${e} -> ${t}`,{source:e,target:t})}hasCircularDependency(e,t,r=new Set){if(r.has(t))return t===e;r.add(t);let s=this.dependencyGraph.get(t);if(s){for(let n of s)if(this.hasCircularDependency(e,n,r))return true}return r.delete(t),false}_beginStateAccess(e){if(this.currentAccessStack.has(e))throw u.badRequest("circularAccess",`Circular state access detected: ${e}`,{key:e,accessStack:Array.from(this.currentAccessStack)});this.currentAccessStack.add(e);}_endStateAccess(e){this.currentAccessStack.delete(e);}isDestroyedState(){return this.isDestroyed}throwIfDestroyed(){if(this.isDestroyed)throw u.gone("sharedStateManager","Shared state manager has been destroyed")}},k=class{constructor(e,t,r,s){this.key=e;this.bus=r;this.managerRef=s;this.subscribers=new Set;this.isDestroyed=false;this.unsubscribeFromBus=null;this.updateSequence=0;this.lastRemoteSequence=-1;this.value=this.cloneValue(t),this.setupCrossAppSynchronization();}get(){this.throwIfDestroyed();let e=this.managerRef.deref();e&&e._beginStateAccess(this.key);try{let t=globalThis.__CONNECTIC_TRACKING_CONTEXT__;return t&&t.isTracking&&t.dependencies.add(this),this.cloneValue(this.value)}finally{e&&e._endStateAccess(this.key);}}set(e){this.throwIfDestroyed();try{let t=this.value,r=this.cloneValue(e);this.valuesEqual(t,r)||(this.value=r,this.updateSequence++,this.notifySubscribers(r),this.bus.emit(`state:${this.key}:changed`,{value:r,sequence:this.updateSequence,timestamp:Date.now(),source:"local"}));}catch(t){throw c(t,`setState:${this.key}`)}}subscribe(e){this.throwIfDestroyed();try{if(typeof e!="function")throw u.badRequest("subscribe","Callback must be a function",{key:this.key,callback:typeof e});return this.subscribers.add(e),()=>{this.subscribers.delete(e);}}catch(t){throw c(t,`subscribe:${this.key}`)}}update(e){this.throwIfDestroyed();try{if(typeof e!="function")throw u.badRequest("update","Updater must be a function",{key:this.key,updater:typeof e});let t=this.get(),r=e(t);this.set(r);}catch(t){throw c(t,`update:${this.key}`)}}getStats(){return {key:this.key,subscriberCount:this.subscribers.size,memoryUsage:v(this.value)+v(this.subscribers),hasValue:this.value!==void 0&&this.value!==null,valueType:typeof this.value,isDestroyed:this.isDestroyed}}destroy(){if(!this.isDestroyed)try{try{this.bus.emit(`state:${this.key}:destroyed`,{key:this.key});}catch(r){console.warn(`Failed to emit destruction event for state ${this.key}:`,r);}this.unsubscribeFromBus&&(this.unsubscribeFromBus(),this.unsubscribeFromBus=null);let e=Array.from(this.subscribers);this.subscribers.clear(),e.forEach(r=>{try{r(void 0);}catch(s){console.warn("Error notifying subscriber during state destruction:",s);}}),this.value=void 0;let t=this.managerRef.deref();t&&t._handleStateDestroyed(this.key),this.isDestroyed=!0;}catch(e){throw this.isDestroyed=true,c(e,`destroyState:${this.key}`)}}isDestroyedState(){return this.isDestroyed}setupCrossAppSynchronization(){this.unsubscribeFromBus=this.bus.on(`state:${this.key}:changed`,e=>{let t,r,s;e&&typeof e=="object"&&"value"in e?(t=e.value,r=e.sequence||0,s=e.source||"remote"):(t=e,r=0,s="remote"),s!=="local"&&(r<=this.lastRemoteSequence||this.valuesEqual(this.value,t)||(this.value=this.cloneValue(t),this.lastRemoteSequence=r,this.notifySubscribers(t)));});}notifySubscribers(e){let t=this.cloneValue(e);this.subscribers.forEach(r=>{T(()=>r(t),`state subscriber for '${this.key}'`);});}cloneValue(e){return e==null?e:typeof e=="object"?b(e):e}valuesEqual(e,t){if(e===t)return true;if(e===null||t===null||e===void 0||t===void 0)return e===t;if(typeof e!=typeof t)return false;if(typeof e=="object"&&typeof t=="object")try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}return false}throwIfDestroyed(){if(this.isDestroyed)throw u.gone(`state:${this.key}`,"State has been destroyed")}},F=class{static createPersistedState(e,t,r,s){let n=s||`connectic_state_${t}`,i=r;if(typeof localStorage<"u")try{let d=localStorage.getItem(n);d!==null&&(i=JSON.parse(d));}catch(d){console.warn(`Failed to load persisted state for "${t}":`,d);}let o=e.createState(t,i);return typeof localStorage<"u"&&o.subscribe(d=>{try{localStorage.setItem(n,JSON.stringify(d));}catch(l){console.warn(`Failed to persist state for "${t}":`,l);}}),o}static createDerivedState(e,t,r){let s=t.map(h=>e.getStateValue(h)),n=r(...s),i=`derived_${t.join("_")}_${Date.now()}`,o=e.createState(i,n),d=[],l=()=>{try{let h=t.map(w=>e.getStateValue(w)),g=r(...h);o.set(g);}catch(h){console.warn("Error recomputing derived state:",h);}};t.forEach(h=>{let g=e.getState(h);if(g){let w=g.subscribe(()=>l());d.push(w);}});let f=o.destroy.bind(o);return o.destroy=()=>{d.forEach(h=>h()),f();},o}static createDebouncedState(e,t,r,s){let n=e.createState(t,r),i=null,o=n.set.bind(n);return n.set=d=>{i&&clearTimeout(i),i=setTimeout(()=>{o(d),i=null;},s);},n}};var $=class{constructor(){this.computedStates=new Set;this.isDestroyed=false;}createComputed(e){this.throwIfDestroyed();try{if(typeof e!="function")throw u.badRequest("createComputed","Compute function must be a function",{computeFn:typeof e});let t=new L(e,new WeakRef(this));return this.computedStates.add(t),t}catch(t){throw c(t,"createComputed")}}getStats(){let e=0,t=0,r=0,s=0;return this.computedStates.forEach(n=>{let i=n.getStats();e+=i.subscriberCount,t+=i.dependencyCount,r+=i.memoryUsage,i.isDestroyed||s++;}),{totalComputedStates:this.computedStates.size,activeComputations:s,totalSubscribers:e,totalDependencies:t,totalMemoryUsage:r,averageDependenciesPerComputed:this.computedStates.size>0?t/this.computedStates.size:0,isDestroyed:this.isDestroyed}}destroy(){if(!this.isDestroyed)try{this.computedStates.forEach(e=>{try{e.destroy();}catch(t){console.warn("Error destroying computed state:",t);}}),this.computedStates.clear(),this.isDestroyed=!0;}catch(e){throw this.isDestroyed=true,c(e,"computedStateManager.destroy")}}_handleComputedDestroyed(e){this.computedStates.delete(e);}isDestroyedState(){return this.isDestroyed}throwIfDestroyed(){if(this.isDestroyed)throw u.gone("computedStateManager","Computed state manager has been destroyed")}},L=class{constructor(e,t){this.computeFn=e;this.managerRef=t;this.isStale=true;this.isComputing=false;this.dependencies=new Set;this.dependencyUnsubscribers=new Map;this.subscribers=new Set;this.isDestroyed=false;this.computationCount=0;this.lastComputeTime=0;this.get();}get(){return this.throwIfDestroyed(),!this.isStale&&this.cachedValue!==void 0?this.cloneValue(this.cachedValue):this.recompute()}subscribe(e){this.throwIfDestroyed();try{if(typeof e!="function")throw u.badRequest("subscribe","Callback must be a function",{callback:typeof e});return this.subscribers.add(e),()=>{this.subscribers.delete(e);}}catch(t){throw c(t,"computedState.subscribe")}}refresh(){return this.throwIfDestroyed(),this.invalidate(),this.get()}getStats(){return {subscriberCount:this.subscribers.size,dependencyCount:this.dependencies.size,isStale:this.isStale,isComputing:this.isComputing,computationCount:this.computationCount,lastComputeTime:this.lastComputeTime,memoryUsage:v(this.cachedValue)+v(this.subscribers)+v(this.dependencies),hasValue:this.cachedValue!==void 0,valueType:typeof this.cachedValue,isDestroyed:this.isDestroyed}}destroy(){if(!this.isDestroyed)try{this.dependencyUnsubscribers.forEach(t=>{try{t();}catch(r){console.warn("Error unsubscribing from dependency:",r);}}),this.dependencies.clear(),this.dependencyUnsubscribers.clear(),this.subscribers.clear(),this.cachedValue=void 0;let e=this.managerRef.deref();e&&e._handleComputedDestroyed(this),this.isDestroyed=!0;}catch(e){throw this.isDestroyed=true,c(e,"computedState.destroy")}}isDestroyedState(){return this.isDestroyed}recompute(){if(this.isComputing)throw u.internal("Circular dependency detected in computed state",void 0,{computationCount:this.computationCount});try{this.isComputing=!0;let e=Date.now(),t=this.trackDependencies(),r=this.cachedValue;return this.cachedValue=t,this.isStale=!1,this.computationCount++,this.lastComputeTime=Date.now()-e,this.valuesEqual(r,t)||this.notifySubscribers(t),this.cloneValue(t)}finally{this.isComputing=false;}}trackDependencies(){let e=new Set(this.dependencies),t=new Set,r={isTracking:true,dependencies:t},s=globalThis.__CONNECTIC_TRACKING_CONTEXT__;globalThis.__CONNECTIC_TRACKING_CONTEXT__=r;try{let n=this.computeFn();return this.updateDependencies(e,t),n}finally{globalThis.__CONNECTIC_TRACKING_CONTEXT__=s;}}updateDependencies(e,t){e.forEach(r=>{if(!t.has(r)){let s=this.dependencyUnsubscribers.get(r);s&&(s(),this.dependencyUnsubscribers.delete(r)),this.dependencies.delete(r);}}),t.forEach(r=>{if(!e.has(r)){let s=r.subscribe(()=>{this.invalidate();});this.dependencyUnsubscribers.set(r,s),this.dependencies.add(r);}});}invalidate(){this.isStale||(this.isStale=true,this.subscribers.size>0&&setTimeout(()=>{!this.isDestroyed&&this.isStale&&this.recompute();},0));}notifySubscribers(e){let t=this.cloneValue(e);this.subscribers.forEach(r=>{T(()=>r(t),"computed state subscriber");});}cloneValue(e){return e==null?e:typeof e=="object"?b(e):e}valuesEqual(e,t){if(e===void 0)return false;if(e===t)return true;if(typeof e=="object"&&typeof t=="object"&&e!==null&&t!==null)try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}return false}throwIfDestroyed(){if(this.isDestroyed)throw u.gone("computedState","Computed state has been destroyed")}},V=class{static createMemoized(e,t,r){let s,n=false,i=()=>{let o=t();return n&&r&&r(s,o)?s:(s=o,n=true,o)};return e.createComputed(i)}static combine(e,t,r){return e.createComputed(()=>{let s=t.map(n=>n.get());return r(...s)})}static filter(e,t,r){return e.createComputed(()=>{let s=t.get();return Array.isArray(s)?s.filter(r):[]})}static map(e,t,r){return e.createComputed(()=>{let s=t.get();return Array.isArray(s)?s.map(r):[]})}static reduce(e,t,r,s){return e.createComputed(()=>{let n=t.get();return Array.isArray(n)?n.reduce(r,s):s})}static createAsync(e,t,r,s){let n=`async_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,i=t.createState(n,{value:s,loading:false,error:null,version:0}),o=null;return e.createComputed(()=>{let d=i.get(),l=r();return l!==o&&(o=l,i.set({value:d.value,loading:true,error:null,version:d.version+1}),l.then(f=>{l===o&&i.set({value:f,loading:false,error:null,version:d.version+1});}).catch(f=>{l===o&&i.set({value:d.value,loading:false,error:f instanceof Error?f:new Error(String(f)),version:d.version+1});})),{value:d.value,loading:d.loading,error:d.error}})}static debounce(e,t,r){let s=null,n=t.get(),i=n,o=e.createComputed(()=>i);return t.subscribe(d=>{n=d,s&&clearTimeout(s),s=setTimeout(()=>{i=n,s=null;},r);}),o}static validate(e,t,r,s){return e.createComputed(()=>{let n=t.get();return r(n)?n:s})}static cached(e,t,r,s=100){let n=new Map,i=[];return e.createComputed(()=>{let o=r();if(n.has(o))return n.get(o);let d=t();if(n.set(o,d),i.push(o),n.size>s){let l=i.shift();n.delete(l);}return d})}};var B=class{constructor(e={}){this.cache=new Map;this.accessOrder=new Map;this.accessCounter=0;this.stats={hits:0,misses:0,sets:0,evictions:0,invalidations:0};this.isDestroyed=false;this.config={defaultTtl:e.defaultTtl||3e5,maxSize:e.maxSize||1e3,strategy:e.strategy||"cache-first"},this.startCleanupTimer();}get(e){this.throwIfDestroyed();try{let t=this.cache.get(e);if(!t){this.stats.misses++;return}if(Date.now()>t.expiry){this.cache.delete(e),this.stats.misses++;return}return t.lastAccessed=Date.now(),this.accessOrder.delete(e),this.accessOrder.set(e,++this.accessCounter),this.stats.hits++,b(t.value)}catch(t){throw c(t,`cache.get:${e}`)}}set(e,t,r){this.throwIfDestroyed();try{let s=r||this.config.defaultTtl,n=Date.now()+s,i={value:b(t),expiry:n,lastAccessed:Date.now()};this.cache.size>=this.config.maxSize&&!this.cache.has(e)&&this.evictLRU(),this.cache.set(e,i),this.accessOrder.delete(e),this.accessOrder.set(e,++this.accessCounter),this.stats.sets++;}catch(s){throw c(s,`cache.set:${e}`)}}invalidate(e){this.throwIfDestroyed();try{let t=this.cache.delete(e);return t&&this.stats.invalidations++,t}catch(t){throw c(t,`cache.invalidate:${e}`)}}invalidatePattern(e){this.throwIfDestroyed();try{let t=this.patternToRegex(e),r=[];for(let s of this.cache.keys())t.test(s)&&r.push(s);return r.forEach(s=>this.cache.delete(s)),this.stats.invalidations+=r.length,r.length}catch(t){throw c(t,`cache.invalidatePattern:${e}`)}}clear(){this.throwIfDestroyed();try{let e=this.cache.size;this.cache.clear(),this.stats.invalidations+=e;}catch(e){throw c(e,"cache.clear")}}getSize(){return this.cache.size}getStats(){let e=this.stats.hits+this.stats.misses,t=e>0?this.stats.hits/e:0,r=this.estimateMemoryUsage();return {...this.stats,totalRequests:e,hitRate:Math.round(t*100)/100,size:this.cache.size,maxSize:this.config.maxSize,memoryUsage:r,defaultTtl:this.config.defaultTtl,strategy:this.config.strategy,isDestroyed:this.isDestroyed}}getDetailedInfo(){let e={},t=Date.now();return this.cache.forEach((r,s)=>{e[s]={isExpired:t>r.expiry,ttl:Math.max(0,r.expiry-t),lastAccessed:r.lastAccessed,valueType:typeof r.value,estimatedSize:v(r.value)};}),{entries:e,config:this.config,stats:this.getStats()}}async handleRequest(e,t,r=this.config.strategy,s){this.throwIfDestroyed();try{switch(r){case "cache-first":return await this.cacheFirstStrategy(e,t,s);case "network-first":return await this.networkFirstStrategy(e,t,s);case "stale-while-revalidate":return await this.staleWhileRevalidateStrategy(e,t,s);case "cache-only":return await this.cacheOnlyStrategy(e);default:throw u.badRequest("cache.handleRequest",`Unknown cache strategy: ${r}`,{strategy:r,key:e})}}catch(n){throw c(n,`cache.handleRequest:${e}:${r}`)}}createKey(e,t){return N(e,t)}destroy(){if(!this.isDestroyed)try{this.stopCleanupTimer(),this.cache.clear(),this.isDestroyed=!0;}catch(e){throw this.isDestroyed=true,c(e,"cache.destroy")}}isDestroyedState(){return this.isDestroyed}async cacheFirstStrategy(e,t,r){let s=this.get(e);if(s!==void 0)return s;let n=await t();return this.set(e,n,r),n}async networkFirstStrategy(e,t,r){try{let s=await t();return this.set(e,s,r),s}catch(s){let n=this.get(e);if(n!==void 0)return n;throw s}}async staleWhileRevalidateStrategy(e,t,r){let s=this.get(e);if(t().then(i=>{this.set(e,i,r);}).catch(i=>{console.warn("Background revalidation failed:",i);}),s!==void 0)return s;let n=await t();return this.set(e,n,r),n}async cacheOnlyStrategy(e){let t=this.get(e);if(t!==void 0)return t;throw u.notFound(e,{message:"No cached value available and cache-only strategy specified"})}evictLRU(){if(this.accessOrder.size===0)return;let e=this.accessOrder.keys().next().value;e&&this.cache.has(e)&&(this.cache.delete(e),this.accessOrder.delete(e),this.stats.evictions++);}patternToRegex(e){let r=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`)}estimateMemoryUsage(){let e=0;return this.cache.forEach((t,r)=>{e+=r.length*2,e+=v(t.value),e+=24;}),e}cleanup(){if(!this.isDestroyed)try{let e=Date.now(),t=[];for(let[r,s]of this.cache.entries())e>s.expiry&&t.push(r);t.forEach(r=>{this.cache.delete(r),this.stats.evictions++;});}catch(e){console.warn("Cache cleanup failed:",e);}}startCleanupTimer(){this.cleanupTimer=setInterval(()=>{this.cleanup();},300*1e3),this.cleanupTimer.unref&&this.cleanupTimer.unref();}stopCleanupTimer(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=void 0);}throwIfDestroyed(){if(this.isDestroyed)throw u.gone("cache","Cache manager has been destroyed")}},H=class{static createNamespacedKey(e,t,r){let s=N(t,r);return `${e}:${s}`}static extractEventFromKey(e){let t=e.split(":");return t.length>0?t[0]:null}static suggestTTL(e){let t=v(e);return t>1e5?6e4:t>1e4?3e5:9e5}static async warmCache(e,t,r){let s=t.map(async n=>{try{let i=await r(n),o=this.suggestTTL(i);e.set(n,i,o);}catch(i){console.warn(`Failed to warm cache for key "${n}":`,i);}});await Promise.all(s);}static createVersionedKey(e,t,r){let s=N(e,t);return `v${r}:${s}`}static migrateVersion(e,t,r,s){let n=`v${t}:`,i=`v${r}:`,o=0,d=e.getDetailedInfo();return Object.keys(d.entries).forEach(l=>{if(l.startsWith(n))try{let f=e.get(l);if(f!==void 0){let h=s(f),g=l.replace(n,i);e.set(g,h),e.invalidate(l),o++;}}catch(f){console.warn(`Failed to migrate cache entry "${l}":`,f);}}),o}};var _=class{constructor(e,t){this.bus=e;this.cache=t;this.pendingRequests=new Map;this.responders=new Map;this.stats={totalRequests:0,completedRequests:0,failedRequests:0,timeoutRequests:0,averageResponseTime:0,totalResponseTime:0};this.isDestroyed=false;this.defaultOptions={timeout:1e4,retries:0,priority:"normal",cache:{},signal:new AbortController().signal};this.setupRequestHandler();}async request(e,t,r){this.throwIfDestroyed();let s=Date.now(),n={...this.defaultOptions,...r};try{if(m(e),this.validateRequestOptions(n),this.stats.totalRequests++,n.cache&&Object.keys(n.cache).length>0){let o=this.cache.createKey(e,t);try{let d=await this.cache.handleRequest(o,()=>this.executeRequest(e,t,n),n.cache.strategy,n.cache.ttl);return this.updateStats(s,!0),d}catch(d){if(d instanceof p&&d.busCode===404)throw d}}let i=await this.executeRequest(e,t,n);return this.updateStats(s,!0),i}catch(i){throw this.updateStats(s,false),c(i,`request:${e}`)}}async requestMany(e,t,r){this.throwIfDestroyed();let s=Date.now(),n={...this.defaultOptions,minResponses:1,maxResponses:Number.MAX_SAFE_INTEGER,...r};try{m(e),this.validateRequestOptions(n),this.stats.totalRequests++;let i=j(),o=[],d=0,l=!1;return new Promise((f,h)=>{let g=Y=>{l||Y.__correlationId!==i||(o.push(Y.response),d++,d>=n.minResponses&&d>=n.maxResponses&&(l=!0,I(),this.updateStats(s,!0),f(o)));},w=setTimeout(()=>{l||(l=!0,I(),d>=n.minResponses?(this.updateStats(s,!0),f(o)):(this.updateStats(s,!1),h(u.timeout(e,n.timeout,{receivedResponses:d,minRequired:n.minResponses}))));},n.timeout),S=()=>{l||(l=!0,I(),this.updateStats(s,!1),h(u.internal("Request was aborted")));};if(n.signal&&!n.signal.aborted)n.signal.addEventListener("abort",S);else if(n.signal?.aborted){S();return}let I=()=>{clearTimeout(w),n.signal&&n.signal.removeEventListener("abort",S),this.bus.off(`response:${i}`,g);};this.bus.on(`response:${i}`,g),this.bus.emit(e,{...t,__correlationId:i,__expectMultiple:!0});})}catch(i){throw this.updateStats(s,false),c(i,`requestMany:${e}`)}}async requestBatch(e){this.throwIfDestroyed();try{if(!Array.isArray(e)||e.length===0)throw u.badRequest("requestBatch","Requests must be a non-empty array",{requests:e});let t=e.map(([i,o,d],l)=>this.request(i,o,d).catch(f=>({__error:f,__index:l}))),r=await Promise.all(t),s=i=>i&&typeof i=="object"&&"__error"in i,n=r.filter(s);return n.length>0&&console.warn(`Batch request had ${n.length} failures:`,n),r}catch(t){throw c(t,"requestBatch")}}respond(e){this.throwIfDestroyed();try{if(m(e),this.responders.has(e)){let r=this.responders.get(e);if(console.warn(`Responder for event "${e}" already exists. Replacing with new responder.`),r&&typeof r.destroy=="function")try{r.destroy();}catch(s){console.warn(`Error destroying existing responder for "${e}":`,s);}this.responders.delete(e);}let t=new C(e,this.bus);return this.responders.set(e,t),t}catch(t){throw c(t,`respond:${e}`)}}getStats(){return {...this.stats,pendingRequests:this.pendingRequests.size,responderCount:this.responders.size,successRate:this.stats.totalRequests>0?this.stats.completedRequests/this.stats.totalRequests:0,isDestroyed:this.isDestroyed}}getDetailedInfo(){let e={},t={};return this.pendingRequests.forEach((r,s)=>{e[s]={timeout:r.options.timeout,retries:r.options.retries,priority:r.options.priority,startTime:Date.now()-(r.options.timeout??0)};}),this.responders.forEach((r,s)=>{t[s]=r.getInfo();}),{pending:e,responders:t,stats:this.getStats()}}destroy(){if(!this.isDestroyed)try{this.pendingRequests.forEach((e,t)=>{try{clearTimeout(e.timeout),e.reject(u.gone("request-response","Manager destroyed"));}catch(r){console.warn(`Error rejecting pending request ${t}:`,r);}}),this.pendingRequests.clear(),this.responders.clear(),this.isDestroyed=!0;}catch(e){throw this.isDestroyed=true,c(e,"requestResponseManager.destroy")}}isDestroyedState(){return this.isDestroyed}async executeRequest(e,t,r){let s=null;for(let n=0;n<=r.retries;n++)try{if(n>0){let i=ee(n-1);await this.delay(i);}return await this.executeSingleRequest(e,t,r)}catch(i){if(s=i instanceof Error?i:new Error(String(i)),i instanceof p&&!i.isRetryable())throw i;if(r.signal?.aborted)throw u.internal("Request was aborted")}throw this.stats.failedRequests++,s||u.internal("Request failed after retries")}async executeSingleRequest(e,t,r){let s=j();return new Promise((n,i)=>{let o=false,d=setTimeout(()=>{if(!o){o=true;try{h();}catch(w){console.warn(`Cleanup error during timeout for ${e}:`,w);}this.stats.timeoutRequests++;let g=u.timeout(e,r.timeout,{correlationId:s,pendingRequests:this.pendingRequests.size,totalRequests:this.stats.totalRequests});i(g);}},r.timeout),l=()=>{o||(o=true,h(),i(u.internal("Request was aborted")));};if(r.signal&&!r.signal.aborted)r.signal.addEventListener("abort",l);else if(r.signal?.aborted){l();return}let f=g=>{o||g.__correlationId!==s||(o=true,h(),g.__error?i(c(g.__error,e)):n(g.response));},h=()=>{try{if(clearTimeout(d),r.signal)try{r.signal.removeEventListener("abort",l);}catch(g){console.warn("Error removing abort listener:",g);}try{this.bus.off(`response:${s}`,f);}catch(g){console.warn("Error removing response listener:",g);}this.pendingRequests.delete(s);}catch(g){console.warn(`Complete cleanup failed for request ${s}:`,g);try{this.pendingRequests.delete(s);}catch(w){console.error("Critical: Failed to remove pending request:",w);}}};this.pendingRequests.set(s,{resolve:n,reject:i,timeout:d,options:r}),this.bus.on(`response:${s}`,f),this.bus.emit(e,{...t,__correlationId:s});})}setupRequestHandler(){}validateRequestOptions(e){if(e.timeout!==void 0&&!Q(e.timeout))throw u.badRequest("request","Invalid timeout value",{timeout:e.timeout});if(e.retries!==void 0&&!X(e.retries))throw u.badRequest("request","Invalid retries value",{retries:e.retries});if(e.priority&&!["low","normal","high"].includes(e.priority))throw u.badRequest("request","Invalid priority value",{priority:e.priority})}updateStats(e,t){let r=Date.now()-e;t?this.stats.completedRequests++:this.stats.failedRequests++,this.stats.totalResponseTime+=r,this.stats.averageResponseTime=this.stats.totalResponseTime/(this.stats.completedRequests+this.stats.failedRequests);}delay(e){return Z(e)}throwIfDestroyed(){if(this.isDestroyed)throw u.gone("requestResponse","Request/response manager has been destroyed")}},U=class{static withTimeout(e,t){return async()=>Promise.race([e(),new Promise((r,s)=>{setTimeout(()=>{s(u.timeout("function",t));},t);})])}static withRetries(e,t,r=1e3){return async()=>{let s=null;for(let n=0;n<=t;n++)try{return n>0&&await Z(ee(n-1,r)),await e()}catch(i){s=i instanceof Error?i:new Error(String(i));}throw s}}static createCircuitBreaker(e,t){let r=0,s=0,n="closed";return async i=>{let o=Date.now();if(n==="open"&&o-s>t&&(n="half-open"),n==="open")throw u.serviceUnavailable("circuit-breaker",t-(o-s));try{let d=await i();return r=0,n="closed",d}catch(d){throw r++,s=o,r>=e&&(n="open"),d}}}};var P=class{constructor(){this.requestInterceptors=[];this.responseInterceptors=[];this.isDestroyed=false;this.stats={requestInterceptions:0,responseInterceptions:0,requestErrors:0,responseErrors:0};}addRequestInterceptor(e){this.throwIfDestroyed();try{if(typeof e!="function")throw u.badRequest("addRequestInterceptor","Interceptor must be a function",{interceptor:typeof e});this.requestInterceptors.push(e);}catch(t){throw c(t,"addRequestInterceptor")}}addResponseInterceptor(e){this.throwIfDestroyed();try{if(typeof e!="function")throw u.badRequest("addResponseInterceptor","Interceptor must be a function",{interceptor:typeof e});this.responseInterceptors.push(e);}catch(t){throw c(t,"addResponseInterceptor")}}removeRequestInterceptor(e){this.throwIfDestroyed();try{let t=this.requestInterceptors.indexOf(e);return t>-1?(this.requestInterceptors.splice(t,1),!0):!1}catch(t){throw c(t,"removeRequestInterceptor")}}removeResponseInterceptor(e){this.throwIfDestroyed();try{let t=this.responseInterceptors.indexOf(e);return t>-1?(this.responseInterceptors.splice(t,1),!0):!1}catch(t){throw c(t,"removeResponseInterceptor")}}applyRequestInterceptors(e,t){this.throwIfDestroyed();try{if(this.requestInterceptors.length===0)return t;let r=b(t),s=[];for(let n=0;n<this.requestInterceptors.length;n++){let i=this.requestInterceptors[n];try{let o=i(e,r);o!==void 0&&(r=o);}catch(o){console.warn(`Request interceptor #${n} failed for event '${e}':`,o),s.push({index:n,error:o}),this.stats.requestErrors++;continue}}if(this.stats.requestInterceptions++,s.length>this.requestInterceptors.length/2)throw new p(`Too many request interceptor failures (${s.length}/${this.requestInterceptors.length})`,500,{event:e,errors:s.slice(0,3)});return r}catch(r){throw r instanceof p?r:(this.stats.requestErrors++,c(r,`applyRequestInterceptors:${e}`))}}applyResponseInterceptors(e,t){this.throwIfDestroyed();try{if(this.responseInterceptors.length===0)return t;let r=b(t),s=[];for(let n=0;n<this.responseInterceptors.length;n++){let i=this.responseInterceptors[n];try{let o=i(e,r);o!==void 0&&(r=o);}catch(o){if(s.push(o),console.warn(`Response interceptor #${n} failed:`,o),s.length/this.responseInterceptors.length>.5)throw new p("Too many response interceptor failures",500,{errors:s})}}return this.stats.responseInterceptions++,r}catch(r){throw this.stats.responseErrors++,c(r,`applyResponseInterceptors:${e}`)}}getInterceptorCounts(){return {request:this.requestInterceptors.length,response:this.responseInterceptors.length}}getStats(){let e=this.getInterceptorCounts();return {...this.stats,...e,totalInterceptors:e.request+e.response,requestSuccessRate:this.stats.requestInterceptions>0?(this.stats.requestInterceptions-this.stats.requestErrors)/this.stats.requestInterceptions:1,responseSuccessRate:this.stats.responseInterceptions>0?(this.stats.responseInterceptions-this.stats.responseErrors)/this.stats.responseInterceptions:1,isDestroyed:this.isDestroyed}}clear(){this.throwIfDestroyed();try{this.requestInterceptors=[],this.responseInterceptors=[];}catch(e){throw c(e,"interceptorManager.clear")}}destroy(){if(!this.isDestroyed)try{this.clear(),this.isDestroyed=!0;}catch(e){throw this.isDestroyed=true,c(e,"interceptorManager.destroy")}}isDestroyedState(){return this.isDestroyed}throwIfDestroyed(){if(this.isDestroyed)throw u.gone("interceptorManager","Interceptor manager has been destroyed")}},z=class{static addTimestamp(e="timestamp"){return (t,r)=>{let s=new Date().toISOString();return {...r,event:t,[e]:s}}}static validateResponse(e){return (t,r)=>{let s=e(t,r);if(s===true)return r;let n=typeof s=="string"?s:"Response validation failed";throw u.unprocessableEntity(t,n,{response:r})}}static transformResponse(e){return (t,r)=>{try{return e(t,r)}catch(s){throw c(s,`transformResponse:${t}`)}}}static logResponses(e=console.log,t={}){let{includeResponse:r=true,prefix:s="[RESPONSE]"}=t;return (n,i)=>{let o=new Date().toISOString();return r?e(`${s} ${o} ${n}`,i):e(`${s} ${o} ${n}`),i}}static addResponseMetadata(e){return (t,r)=>{let s=typeof e=="function"?e(t,r):e;return {data:r,metadata:{timestamp:Date.now(),event:t,...s}}}}static normalizeResponse(e={}){let{dataField:t="data",errorField:r="error",successField:s="success"}=e;return (n,i)=>i&&typeof i=="object"&&t in i?i:{[s]:true,[t]:i,[r]:null}}static