@kosdev-code/kos-ui-sdk 2.1.29 → 2.1.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"kos-service-request.d.ts","sourceRoot":"","sources":["../../../../../../packages/sdk/kos-ui-sdk/src/core/util/kos-service-request.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAGhD;;;;GAIG;AACH,eAAO,MAAM,cAAc;;;CAI1B,CAAC;AAIF,KAAK,YAAY,CAAC,CAAC,IAAI;KACpB,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,KAAK,GAAG,SAAS,GAAG,KAAK,GAAG,CAAC;CAC7D,CAAC,MAAM,CAAC,CAAC,CAAC;AAEX,MAAM,MAAM,gBAAgB,CAAC,CAAC,IAAI,OAAO,CACvC,YAAY,CAAC,CAAC,CAAC,EACf,YAAY,GAAG,aAAa,CAC7B,CAAC;AAEF,MAAM,MAAM,aAAa,CAAC,CAAC,IAAI;KAC5B,MAAM,IAAI,KAAK,GAAG,KAAK,GAAG,MAAM,GAAG,QAAQ,GAAG;SAC5C,CAAC,IAAI,MAAM,CAAC,GAAG,MAAM,SAAS,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK;KAClE,CAAC,MAAM,CAAC,GAAG,MAAM;SAAG,CAAC,IAAI,MAAM,CAAC,GAAG,MAAM,SAAS,MAAM,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK;KAAE,CAAC;CAC7E,CAAC;AAEF,KAAK,eAAe,CAClB,KAAK,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EACjC,CAAC,SAAS,MAAM,KAAK,IACnB,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS;IAAE,UAAU,EAAE,MAA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;AAE5D,MAAM,MAAM,UAAU,CACpB,KAAK,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EACjC,CAAC,SAAS,MAAM,KAAK,EACrB,CAAC,SAAS,gBAAgB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,IAC3C,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS;IAAE,WAAW,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC,CAAA;KAAE,CAAA;CAAE,GACzD,CAAC,CAAC,MAAM,CAAC,CAAC,GACV,KAAK,CAAC;AAEV,MAAM,MAAM,eAAe,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;AAE5D,MAAM,MAAM,YAAY,CAAC,CAAC,IAAI;KAC3B,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,MAAM,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CAClE,CAAC;AACF,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,GAAG,KAAK,CAAC;AAsD/D,KAAK,cAAc,GAAG,IAAI,CAAC,eAAe,EAAE,QAAQ,GAAG,MAAM,CAAC,CAAC;AAC/D,wBAAgB,YAAY,CAAC,KAAK,SAAS,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;sRAQ9C,cAAc;qVAOd,cAAc;gVAQd,cAAc;4VAOd,cAAc;EAU7B"}
package/index.cjs CHANGED
@@ -28,7 +28,7 @@ Caused by: ${o.stack}`)}toDetailedString(){const s=[`KosModelError: ${this.messa
28
28
  - Parent Model: ${t.modelTypeName}
29
29
  - Parent Model ID: ${t.modelId}
30
30
  - Provided Options: ${JSON.stringify(n,null,2)}
31
- - Error: ${y}`),o===Ve.FAIL?new Error(`Dependency resolution failed (policy: FAIL) - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${y}`):p}},sl=(t,e=x.READY)=>{var o;const s=((o=t.modelData)==null?void 0:o[F])||{};return Object.keys(s).length===0?(m.debug(`${t.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===e).map(n=>{const i=s[n],a=tl(t,i);if(!a.success||!a.dependentModel)return m.debug(`Skipping dependency ${i.modelType} with id ${a.dataModelId} - resolution failed with CONTINUE policy`),t.modelData[n]=void 0,null;const{dependentModel:c,dataModelId:u}=a;t.modelData[n]=c.data,m.debug(`waiting for dependent model ${i.modelType} with id ${u} - waiting for WHENREADY`);const d=async(p,y,w)=>{var E;await((E=p.whenReady)==null?void 0:E.call(p)),m.debug(`dependent model ${y} with id ${w} - READY`)},{promise:h,cancel:f}=Jc(Zc,t,t.status);return Promise.race([d(c.model,i.modelType,u).then(()=>{f()}).catch(p=>{const y=$t(p,{modelType:i.modelType,modelId:u,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:e,operation:"dependency whenReady()"});throw m.error(y.toDetailedString()),f(),y}),h])}).filter(n=>!!n)},rl=async(t,e,s,r)=>{if(m.debug(`Execute lifecycle with ${e.length} models`),e.length===0){m.debug(`${t.modelId} has no children. Returning`);return}if(!s){m.error(`${t.modelId} is not transitioning with a valid target ${s}`);return}const o=e.map(a=>{let c;return lr[s]&&a?c=lr[s](a):(a||m.error("model is undefined. This shouldn't happen"),lr[s]||m.error(`There is no promise in the Transition Map for ${s}`)),{promise:c,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(m.error(`No model found ${a.modelId}`),!1):(m.error(`No promise found ${a.modelId}`),!1)),n=await Promise.allSettled(o.map(a=>{var d;if(!a.model||!a.status)return Promise.resolve();const{promise:c,cancel:u}=Jc(Zc,a.model,a.status);return Promise.race([(d=a.promise)==null?void 0:d.then(()=>{u()}).catch(h=>{const f=$t(h,{modelType:a.type||"unknown",modelId:a.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`});throw m.error(f.toDetailedString()),u(),f}),c])})),i=n.filter(a=>a.status==="rejected");if(i.length>0){const a=i.map(c=>{const u=o[n.indexOf(c)];return{error:c.status==="rejected"?c.reason:new Error("Unknown error"),context:{modelType:u.type||"unknown",modelId:u.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`}}});Yp(a,`Model ${t.modelId} had ${i.length} failed child model(s) on ${r}`)}},ol=async(t,e,s)=>{await rl(t,t.getChildren().filter(r=>!!r),e,s)},ts=async(t,e)=>{const r=(await Promise.allSettled(sl(t,e))).filter(o=>o.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${e}`),m.error(r))};function sg(t){const e=`KosModel(${t.modelTypeName}:${t.modelId})`;try{Object.defineProperty(t,Symbol.toStringTag,{value:e,configurable:!0})}catch{t.toString=()=>e}try{Object.defineProperty(t.constructor,"name",{value:`KosModel_${t.modelTypeName}`,configurable:!0})}catch{t.constructor.name=`KosModel_${t.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in t&&Object.defineProperty(t,r,{enumerable:!1});Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:t.modelId,type:t.modelTypeName,initialized:t.initialized,loaded:t.loaded,status:t.status,onlineStatus:t.onlineStatus,activeStatus:t.activeStatus,companions:(o=(r=t.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=t.getChildren)==null?void 0:n.call(t).map(i=>i.modelId),effects:!!t.effectManager,subs:!!t.subscriptionManager}}}),rg(t.modelData,t.modelTypeName,t.modelId,t)}function rg(t,e,s,r){Object.defineProperty(t,Symbol.toStringTag,{value:`KosModelData(${e}:${s})`,configurable:!0});try{Object.defineProperty(t.constructor,"name",{value:`${e}ModelData`,configurable:!0})}catch{t.constructor.name=`${e}ModelData`}Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,u;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[F]||{};return{id:s,type:e,companions:{count:n.length,data:n.map(d=>({type:d.modelTypeName,id:d.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(d=>({id:d.id||d.modelType,type:d.modelType,options:d.options,lifecycle:d.lifecycle}))},children:{count:o.length,data:o.map(d=>({id:d.modelId,type:d.modelTypeName}))},data:((u=t.toJSON)==null?void 0:u.call(t))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(t,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(t))if(!(n.startsWith("_")||typeof t[n]=="function"))try{const i=t[n];Es(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:In(i)?o[`[KOS Container] ${n}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?o[n]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?o[n]=JSON.parse(JSON.stringify(i)):o[n]=i}catch{o[n]="[unreadable]"}return o}})}class og{constructor(e){this.model=e}resolve(){const e=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(e).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==v.FAILED).filter(r=>!!r);return s.forEach(r=>{try{Y.setParentContext(r.modelId,this.model.modelId)}catch(o){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,o)}}),s}getResolvedDecoratedChildren(){var s;const e=((s=this.model.modelData)==null?void 0:s[Ge])||{};return Object.keys(e).map(r=>el(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var e,s;return((s=(e=this.model.modelData)==null?void 0:e.getChildren)==null?void 0:s.call(e))||[]}}class ng{constructor(e){l(this,"companions",new M.ObservableMap);this.hostModel=e}add(e){this.companions.set(e.modelTypeName,e)}clear(){this.companions.clear()}get(e){return this.companions.get(e)}all(){return[...this.companions.values()]}get data(){return this.companions}}class ig{constructor(e,s,r,o){l(this,"disposers",[]);this.modelTypeName=e,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const e=((s=this.modelData)==null?void 0:s[at])||{};for(const r of Object.keys(e)){const{value:o,dependencies:n,options:i}=e[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),M.runInAction(()=>a())},u=n?M.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):M.autorun(c);this.disposers.push(u)}}disposeAll(){for(const e of this.disposers)try{e()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const ag=m.createLogger({name:"model-active-machine"}),cg=t=>{const e=b.createMachine(v.INACTIVE,{[v.FAILED]:b.state(b.transition(L.GO_ACTIVE,v.ACTIVATING)),[v.INACTIVE]:b.state(b.transition(L.GO_ACTIVE,v.ACTIVATING)),[v.ACTIVATING]:b.invoke(()=>(t.activeStatus=v.ACTIVATING,t.activate()),b.transition("done",v.ACTIVE,b.action(()=>{t.activeStatus=v.ACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED}))),[v.ACTIVE]:b.state(b.transition(L.GO_INACTIVE,v.DEACTIVATING)),[v.DEACTIVATING]:b.invoke(()=>(t.activeStatus=v.DEACTIVATING,t.deactivate()),b.transition("done",v.INACTIVE,b.action(()=>{t.activeStatus=v.INACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED})))});return{service:b.interpret(e,r=>ag.debug(r.machine.current)),machine:e}},Li=m.createLogger({name:"model-online-machine"}),lg=t=>{const e=b.createMachine(v.OFFLINE,{[v.ONLINE]:b.state(b.transition(L.GO_OFFLINE,v.OFFLINE,b.action(async()=>{await t.offline(),t.onlineStatus=v.OFFLINE}))),[v.OFFLINE]:b.state(b.transition(L.GO_ONLINE,v.ONLINE,b.action(async()=>{Li.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=v.ONLINE,await t.fsm.transitionTo(L.INITIALIZE,v.INITIALIZED)})))}),s=b.interpret(e,r=>Li.debug(r.machine.current));return{machine:e,service:s}},ug=t=>{var r;const e=cg(t).service,s=lg(t).service;return b.createMachine(v.CREATING,{[v.CREATING]:b.state(b.transition(L.CREATE,v.CREATED)),[v.CREATED]:b.state(b.immediate(v.INITIALIZING)),[v.INITIALIZING]:b.invoke(()=>(J(()=>{t.status=v.INITIALIZING}),t.init()),b.transition("done",v.INITIALIZED,b.action(()=>{t.status=v.INITIALIZED})),b.transition("error",v.FAILED,b.action(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} failed to initialize. Transitioning to FAILED state.`),t.status=v.FAILED}))),[v.INITIALIZED]:b.state(b.immediate(v.LOADING)),[v.LOADING]:b.invoke(()=>(J(()=>{t.status=v.LOADING}),t.load()),b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.LOADED]:b.state(b.immediate(v.READYING),b.transition(L.UNLOAD,v.UNLOADING)),[v.RESETTING]:b.invoke(()=>{var o;return J(()=>{t.status=v.RESETTING}),(o=t.unload)==null||o.call(t),t.load()},b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED}))),[v.READYING]:b.invoke(()=>(J(()=>{t.status=v.READYING}),t.ready()),b.transition("done",v.READY,b.action(()=>{J(()=>{t.status=v.READY}),s.send(L.GO_ONLINE)})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.READY]:b.state(b.transition(L.UNLOAD,v.UNLOADED,b.action((r=t.unload)==null?void 0:r.bind(t))),b.transition(L.RESET,v.RESETTING),b.transition(L.GO_ONLINE,v.READY,b.action(()=>{s.send(L.GO_ONLINE)})),b.transition(L.GO_OFFLINE,v.READY,b.action(()=>{s.send(L.GO_OFFLINE)})),b.transition(L.GO_ACTIVE,v.READY,b.action(()=>{e.send(L.GO_ACTIVE)})),b.transition(L.GO_INACTIVE,v.READY,b.action(()=>{e.send(L.GO_INACTIVE)}))),[v.UNLOADED]:b.state(),[v.FAILED]:b.state()})},dg=m.createLogger({name:"kos-model-lifecycle"}),hg=t=>({service:b.interpret(ug(t),s=>dg.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class fg{constructor(e,s){l(this,"disposer");l(this,"service");this.model=e,this.log=s;const r=hg(e);this.service=r.service,this.service.send(L.CREATE)}get current(){return this.service.machine.current}async transitionTo(e,s,r=v.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${e} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=M.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${e}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(e)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(e){return[v.ACTIVE,v.INACTIVE].includes(e)?this.model.activeStatus:this.model.status}}const nl="browser-router-model";class On{constructor(e,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=e,this.logger=s}registerAll(){var s;if(!mr(this.model))return;let e=this.model.__httpBrowserRouter;if(!e)for(const r of Object.keys(this.model)){const o=this.model[r];if(o&&typeof o=="object"&&"use"in o&&typeof o.use=="function"){e=o;break}}if(e||(e=(s=$e(nl))==null?void 0:s.model),!e)throw this.logger.error("Cannot register HTTP routes: BrowserRouter not found. The HTTP decorators should have auto-injected it, but something went wrong."),new Error("BrowserRouter is required for HTTP route decorators but was not found. This should not happen as HTTP decorators auto-inject the dependency.");this.setRouter(e)}setRouter(e){this.router=e,this.registered||this.registerRoutes()}hasRoutes(){return mr(this.model)}registerRoutes(){if(!this.router){this.logger.warn("Cannot register routes: router not set");return}if(this.registered){this.logger.debug("Routes already registered");return}const e=Dc(this.model);e.length!==0&&(this.logger.debug(`Registering ${e.length} HTTP routes`),e.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(e){const s=/\{PROP_([^}]+)\}/g;let r=e;if(r.includes("{MODEL_ID}")){const n=this.model.id||this.model._id||"unknown";r=r.replace(/\{MODEL_ID\}/g,n)}let o;for(;(o=s.exec(e))!==null;){const n=o[1];if(n in this.model){const i=this.model[n];r=r.replace(o[0],String(i))}else this.logger.warn(`Property '${n}' not found on model for PropKey resolution in path: ${e}`)}return r}registerRoute(e){if(!this.router)return;const s=this.model[e.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${e.handler}' not found on model`);return}const r=this.resolvePropKey(e.path);this.logger.debug(`Registering ${e.method} ${r} -> ${e.handler}`+(r!==e.path?` (resolved from ${e.path})`:""));const o=async(n,i)=>{var a;try{await s.call(this.model,n,i)}catch(c){this.logger.error(`Error in route handler ${e.method} ${r}:`,c),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:c instanceof Error?c.message:String(c)})}};this.checkForDuplicateRoute(e.method,r),this.router.use(e.method,r,o),this.registeredRoutes.push({method:e.method,path:r})}checkForDuplicateRoute(e,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===e&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${e} ${s}. This route is already registered by another model. The new handler from model '${this.model.id||"unknown"}' will override the existing one. Only the last registered handler will receive requests. Consider using different paths or namespacing to avoid conflicts.`)}dispose(){if(this.router&&this.registeredRoutes.length>0){this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id||"unknown"}`);let e=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);e+=r,r>0?this.logger.debug(`Removed route: ${s.method} ${s.path}`):this.logger.warn(`Failed to remove route: ${s.method} ${s.path} (not found)`)}this.logger.debug(`Successfully removed ${e} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function pg(t,e){if(!mr(t))return;const s=$e(nl);if(!(s!=null&&s.model))throw e.error("Cannot register HTTP routes: BrowserRouter not found. Make sure to include BrowserRouter in your model dependencies or create an instance."),new Error("BrowserRouter is required for HTTP route decorators but was not found. Add it as a dependency using @kosDependency or ensure an instance exists.");new On(t,e).setRouter(s.model)}class gg{constructor(e){l(this,"queue",[]);this.log=e}enqueue(e,s,r){this.queue.push({handler:e,receivedAt:Date.now(),topic:s,payload:r})}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const e of this.queue)try{e.handler()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}flushWithStrategy(e,s,r){if(this.queue.length===0)return;const o=this.queue.length,n=this.filterEventsByStrategy(e,s,r),i=o-n.length;this.log.warn(`Processing ${n.length}/${o} offline message(s) with strategy: ${e}`);for(const a of n)try{a.handler()}catch(c){this.log.error(`Error while processing offline message for topic ${a.topic}:`,c)}this.queue=[],this.log.info(`Offline queue flushed with strategy ${e}. Replayed: ${n.length}, Discarded: ${i}`)}filterEventsByStrategy(e,s,r){switch(e){case it.ALL:return[...this.queue];case it.AFTER_REQUEST:return s===void 0?(this.log.warn("AFTER_REQUEST strategy requires baselineRequestedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=s);case it.AFTER_RESPONSE:return r===void 0?(this.log.warn("AFTER_RESPONSE strategy requires baselineReceivedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=r);case it.NONE:return[];default:return this.log.warn(`Unknown replay strategy: ${e}, replaying all`),[...this.queue]}}getStatistics(e,s){if(this.queue.length===0)return{total:0};const r=this.queue.map(n=>n.receivedAt),o={total:this.queue.length,oldestEventAt:Math.min(...r),newestEventAt:Math.max(...r)};return e!==void 0&&(o.afterRequest=this.queue.filter(n=>n.receivedAt>=e).length),s!==void 0&&(o.afterResponse=this.queue.filter(n=>n.receivedAt>=s).length),o}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class mg{constructor(e,s){l(this,"unsubscribers",[]);this.model=e,this.log=s}register(){const e=this.model.modelId,s=C("/kosCore/online",async()=>{this.log.debug(`Online event received for ${e}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${e} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(L.GO_ONLINE,v.ONLINE)}),r=C("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${e} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(L.GO_OFFLINE,v.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}const il=()=>({isMock:!1,URL:exports.BASE_URL}),yg=m.createLogger({name:"kos-service-request"}),bg="errUnknown";async function Js(t,e,s,r,o){const n=r!=null&&r.path?Object.keys(r.path).reduce((h,f)=>String(h).replace(`{${f}}`,r==null?void 0:r.path[f]),String(t)):String(t),i=r!=null&&r.query?Object.keys(r.query).map(h=>`${h}=${r.query[h]}`).join("&"):"",a=`${il().URL}${n}${i?`?${encodeURIComponent(i)}`:""}`;yg.debug(`fullUrl: ${a}`);const c={method:String(e).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));const u=await exports.kosFetch(a,c);return u.status<200||u.status>=400?[`${u.statusText||bg}`,null]:[null,(await u.json()).data]}function Be(){return{get:(t,e,s)=>Js(t,"get",s,e),post:(t,e,s,r)=>Js(t,"post",r,e,s),put:(t,e,s,r)=>Js(t,"put",r,e,s),delete:(t,e,s,r)=>Js(t,"delete",r,e,s)}}const Ae=Be(),al=Object.freeze(Object.defineProperty({__proto__:null,default:Ae},Symbol.toStringTag,{value:"Module"})),st=m.createLogger({name:"kos-service-request-manager",group:"Model"});function vg(t,e){return!t.condition||t.condition(e)}function wg(t,e){return Me({value:t.path,modelId:e.id,modelData:e})}function Eg(t,e){if(t.pathParams)return Me({value:typeof t.pathParams=="function"?t.pathParams(e):t.pathParams,modelId:e.id,modelData:e})}function Mg(t,e){if(t.queryParams)return Me({value:typeof t.queryParams=="function"?t.queryParams(e):t.queryParams,modelId:e.id,modelData:e})}function Tg(t,e){if(t.body)return Me({value:typeof t.body=="function"?t.body(e):t.body,modelId:e.id,modelData:e})}function _g(t){return(t||"get").toLowerCase()}function Fi(t,e){return`${e.toUpperCase()}:${t}`}function cl(t){return t==null}function Sg(t,e,s,r){r&&cl(t)&&st.warn(`Required field '${e}' is missing in response for ${s}`)}function Ig(t,e){return cl(t)&&e!==void 0?e:t}class Og{constructor(e,s){l(this,"model");l(this,"responseStore");l(this,"handlers");this.model=e,this.responseStore=s,this.handlers=new Map,this.discoverHandlers()}discoverHandlers(){const s=Object.getPrototypeOf(this.model)[ct]||{};Object.values(s).forEach(r=>{const o=r.lifecycle;this.handlers.has(o)||this.handlers.set(o,[]),this.handlers.get(o).push(r)}),Object.keys(s).length>0&&st.debug(`Discovered ${Object.keys(s).length} service request handlers for model ${this.model.id}`)}async executeForLifecycle(e){const s=this.handlers.get(e);!s||s.length===0||(st.debug(`Executing ${s.length} service requests for lifecycle ${e}`),await Promise.all(s.map(r=>this.executeHandler(r))))}async executeHandler(e){try{if(!this.shouldProcessRequest(e))return;const s=await this.prepareAndExecuteRequest(e);await this.processAndStoreResponse(s,e)}catch(s){const r=s instanceof Error?s:new Error(String(s));await this.handleError(r,e)}}shouldProcessRequest(e){return vg(e,this.model)?!0:(st.debug(`Skipping request ${e.path} - condition returned false`),!1)}async prepareAndExecuteRequest(e){const s=this.prepareRequest(e),r=this.captureRequestTiming(),[o,n]=await this.performRequest(s),i=this.captureResponseTiming();return{requestContext:s,error:o,response:n,requestedAt:r.requestedAt,receivedAt:i.receivedAt}}captureRequestTiming(){return{requestedAt:Date.now()}}captureResponseTiming(){return{receivedAt:Date.now()}}async processAndStoreResponse(e,s){if(e.error){await this.handleError(new Error(e.error),s);return}const r=await this.processResponse(e.response,s);await this.storeAndInvokeHandler(r,s,e.requestContext.resolvedPath,e.requestedAt,e.receivedAt)}prepareRequest(e){const s=wg(e,this.model),r=Eg(e,this.model),o=Mg(e,this.model),n=Tg(e,this.model),i=_g(e.method);return{resolvedPath:s,method:i,pathParams:r,queryParams:o,body:n}}async performRequest(e){return await this.makeRequest(e.resolvedPath,e.method,{path:e.pathParams,query:e.queryParams},e.body)}async processResponse(e,s){let r=e;return s.transform&&(r=s.transform(e)),s.mappings&&s.mappings.length>0&&(r=this.applyMappings(r,s)),s.iterateOver&&(r=await this.handleIteration(r,s)),r}async storeAndInvokeHandler(e,s,r,o,n){const i=s.cache||{retention:de.SINGLE},a=Fi(r,s.method||"get");this.responseStore.set(a,e,i,o,n),await s.originalHandler.call(this.model,e),this.triggerBaselineQueueFlush(r),this.responseStore.shouldCleanupAfterHandler(a)&&this.responseStore.delete(a)}triggerBaselineQueueFlush(e){const s=this.model.subscriptionManager;!s||!s.flushQueueForBaseline||s.flushQueueForBaseline(e)}async makeRequest(e,s,r,o){const n=Ae;switch(s){case"get":return await n.get(e,r);case"post":return await n.post(e,r,o);case"put":return await n.put(e,r,o);case"delete":return await n.delete(e,r,o);default:return[`Unsupported HTTP method: ${s}`,null]}}applyMappings(e,s){if(!s.mappings||s.mappings.length===0)return e;const r={};return s.mappings.forEach(o=>{const n=this.getNestedValue(e,o.from),i=o.transform?this.applyTransform(n,o.transform):n;Sg(i,o.from,s.path,o.required||!1);const a=Ig(i,o.default);r[o.to]=a}),r}getNestedValue(e,s){return s.split(".").reduce((r,o)=>r==null?void 0:r[o],e)}applyTransform(e,s){if(typeof s=="function")return s(e);switch(s){case"string":return String(e);case"number":return Number(e);case"boolean":return!!e;case"date":return e?new Date(e):void 0;case"json":return typeof e=="string"?JSON.parse(e):e;default:return st.warn(`Unknown transformer: ${s}`),e}}async handleIteration(e,s){if(!s.iterateOver)return e;const r=this.getNestedValue(e,s.iterateOver);return Array.isArray(r)?s.modelFactory?r.map(o=>{const n=s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o,i=s.idExtractor?s.idExtractor(n):n.id;if(!i)throw new Error("Cannot create model instance: no ID found in response data. Provide an 'idExtractor' function or ensure response items have an 'id' field.");const a=s.modelFactory;return typeof a=="function"?a(i)(n):a.instance(i).options(n).build()}):r.map(o=>s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o):(st.warn(`iterateOver path '${s.iterateOver}' did not resolve to an array`),[])}async handleError(e,s){const r=s.errorHandler||{strategy:"throw"};switch(r.onError&&r.onError(e,this.model),r.strategy){case"throw":throw e;case"log":st.error(`Service request failed for ${s.path}:`,e.message);break;case"ignore":break;case"default":if(r.defaultValue!==void 0){const o=Fi(s.path,s.method||"get");this.responseStore.set(o,r.defaultValue,s.cache||{retention:de.SINGLE})}break}}}class $g{constructor(e){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=e,this.subscription={queue:[],resolvers:[],closed:!1};const s=C(e,r=>{if(!this.subscription.closed&&r!==void 0){const o=this.subscription.resolvers.shift();o?o(r):this.subscription.queue.push(r)}});this.unsubscribe=s.unsubscribe}async next(){return this.subscription.closed&&this.subscription.queue.length===0?{done:!0,value:void 0}:this.subscription.queue.length>0?{done:!1,value:this.subscription.queue.shift()}:new Promise(e=>{this.subscription.closed?e({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{e({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(e=>{e(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(e){throw this.subscription.closed=!0,this.unsubscribe(),e}[Symbol.asyncIterator](){return this}}function Ni(t){return new $g(t)}const ll=({path:t,requestId:e,method:s,destinationAddress:r})=>{let o=`${Kr}:${s}
31
+ - Error: ${y}`),o===Ve.FAIL?new Error(`Dependency resolution failed (policy: FAIL) - Model ${t.modelId} cannot resolve dependency ${e.modelType} [${r}]: ${y}`):p}},sl=(t,e=x.READY)=>{var o;const s=((o=t.modelData)==null?void 0:o[F])||{};return Object.keys(s).length===0?(m.debug(`${t.modelId} has no dependencies. Returning`),[]):Object.keys(s).filter(n=>s[n].lifecycle===e).map(n=>{const i=s[n],a=tl(t,i);if(!a.success||!a.dependentModel)return m.debug(`Skipping dependency ${i.modelType} with id ${a.dataModelId} - resolution failed with CONTINUE policy`),t.modelData[n]=void 0,null;const{dependentModel:c,dataModelId:u}=a;t.modelData[n]=c.data,m.debug(`waiting for dependent model ${i.modelType} with id ${u} - waiting for WHENREADY`);const d=async(p,y,w)=>{var E;await((E=p.whenReady)==null?void 0:E.call(p)),m.debug(`dependent model ${y} with id ${w} - READY`)},{promise:h,cancel:f}=Jc(Zc,t,t.status);return Promise.race([d(c.model,i.modelType,u).then(()=>{f()}).catch(p=>{const y=$t(p,{modelType:i.modelType,modelId:u,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:e,operation:"dependency whenReady()"});throw m.error(y.toDetailedString()),f(),y}),h])}).filter(n=>!!n)},rl=async(t,e,s,r)=>{if(m.debug(`Execute lifecycle with ${e.length} models`),e.length===0){m.debug(`${t.modelId} has no children. Returning`);return}if(!s){m.error(`${t.modelId} is not transitioning with a valid target ${s}`);return}const o=e.map(a=>{let c;return lr[s]&&a?c=lr[s](a):(a||m.error("model is undefined. This shouldn't happen"),lr[s]||m.error(`There is no promise in the Transition Map for ${s}`)),{promise:c,modelId:a==null?void 0:a.modelId,model:a,type:a==null?void 0:a.modelTypeName,status:a==null?void 0:a.status}}).filter(a=>a.promise?a.model?!0:(m.error(`No model found ${a.modelId}`),!1):(m.error(`No promise found ${a.modelId}`),!1)),n=await Promise.allSettled(o.map(a=>{var d;if(!a.model||!a.status)return Promise.resolve();const{promise:c,cancel:u}=Jc(Zc,a.model,a.status);return Promise.race([(d=a.promise)==null?void 0:d.then(()=>{u()}).catch(h=>{const f=$t(h,{modelType:a.type||"unknown",modelId:a.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`});throw m.error(f.toDetailedString()),u(),f}),c])})),i=n.filter(a=>a.status==="rejected");if(i.length>0){const a=i.map(c=>{const u=o[n.indexOf(c)];return{error:c.status==="rejected"?c.reason:new Error("Unknown error"),context:{modelType:u.type||"unknown",modelId:u.modelId,parentModel:{type:t.modelTypeName,id:t.modelId},lifecycle:r,operation:`transition to ${s}`}}});Yp(a,`Model ${t.modelId} had ${i.length} failed child model(s) on ${r}`)}},ol=async(t,e,s)=>{await rl(t,t.getChildren().filter(r=>!!r),e,s)},ts=async(t,e)=>{const r=(await Promise.allSettled(sl(t,e))).filter(o=>o.status==="rejected");r.length&&(m.error(`There were ${r.length} failed dependent models on ${e}`),m.error(r))};function sg(t){const e=`KosModel(${t.modelTypeName}:${t.modelId})`;try{Object.defineProperty(t,Symbol.toStringTag,{value:e,configurable:!0})}catch{t.toString=()=>e}try{Object.defineProperty(t.constructor,"name",{value:`KosModel_${t.modelTypeName}`,configurable:!0})}catch{t.constructor.name=`KosModel_${t.modelTypeName}`}const s=["fsm","effectManager","subscriptionManager","onlineLifecycleManager","companionManager","childResolver","_offlineQueue"];for(const r of s)r in t&&Object.defineProperty(t,r,{enumerable:!1});Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var r,o,n;return{id:t.modelId,type:t.modelTypeName,initialized:t.initialized,loaded:t.loaded,status:t.status,onlineStatus:t.onlineStatus,activeStatus:t.activeStatus,companions:(o=(r=t.companionManager)==null?void 0:r.all())==null?void 0:o.map(i=>i.modelTypeName),children:(n=t.getChildren)==null?void 0:n.call(t).map(i=>i.modelId),effects:!!t.effectManager,subs:!!t.subscriptionManager}}}),rg(t.modelData,t.modelTypeName,t.modelId,t)}function rg(t,e,s,r){Object.defineProperty(t,Symbol.toStringTag,{value:`KosModelData(${e}:${s})`,configurable:!0});try{Object.defineProperty(t.constructor,"name",{value:`${e}ModelData`,configurable:!0})}catch{t.constructor.name=`${e}ModelData`}Object.defineProperty(t,"debugState",{enumerable:!1,configurable:!0,get(){var a,c,u;const o=((a=r.getChildren)==null?void 0:a.call(r))||[],n=((c=r.companionManager)==null?void 0:c.all())||[],i=r.modelData[F]||{};return{id:s,type:e,companions:{count:n.length,data:n.map(d=>({type:d.modelTypeName,id:d.modelId}))},dependencies:{count:Object.keys(i).length,data:Object.values(i).map(d=>({id:d.id||d.modelType,type:d.modelType,options:d.options,lifecycle:d.lifecycle}))},children:{count:o.length,data:o.map(d=>({id:d.modelId,type:d.modelTypeName}))},data:((u=t.toJSON)==null?void 0:u.call(t))||{},subs:!!r.subscriptionManager}}}),Object.defineProperty(t,"toJSON",{configurable:!0,enumerable:!1,writable:!0,value:()=>{const o={};for(const n of Object.keys(t))if(!(n.startsWith("_")||typeof t[n]=="function"))try{const i=t[n];Es(i)?o[`[KOS Model] ${n}`]=typeof i.toJSON=="function"?i.toJSON():{id:i.id,type:i.constructor.name}:In(i)?o[`[KOS Container] ${n}`]=typeof i.toJSON=="function"?i.toJSON():["Container"]:Array.isArray(i)?o[n]=`[Array(${i.length})]`:typeof i=="object"&&i!==null?o[n]=JSON.parse(JSON.stringify(i)):o[n]=i}catch{o[n]="[unreadable]"}return o}})}class og{constructor(e){this.model=e}resolve(){const e=new Set([...this.getResolvedDecoratedChildren(),...this.getAdditionalChildren(),...this.model.companionModels.all()]),s=Array.from(e).map(r=>this.model.modelManager.getModelById(r.id||"")).filter(r=>r&&r.status!==v.FAILED).filter(r=>!!r);return s.forEach(r=>{try{Y.setParentContext(r.modelId,this.model.modelId)}catch(o){console.error(`Failed to set parent context for ${r.modelId} under ${this.model.modelId}`,o)}}),s}getResolvedDecoratedChildren(){var s;const e=((s=this.model.modelData)==null?void 0:s[Ge])||{};return Object.keys(e).map(r=>el(this.model.modelData[r])).filter(r=>!!r).flat()}getAdditionalChildren(){var e,s;return((s=(e=this.model.modelData)==null?void 0:e.getChildren)==null?void 0:s.call(e))||[]}}class ng{constructor(e){l(this,"companions",new M.ObservableMap);this.hostModel=e}add(e){this.companions.set(e.modelTypeName,e)}clear(){this.companions.clear()}get(e){return this.companions.get(e)}all(){return[...this.companions.values()]}get data(){return this.companions}}class ig{constructor(e,s,r,o){l(this,"disposers",[]);this.modelTypeName=e,this.modelId=s,this.modelData=r,this.log=o}setup(){var s;const e=((s=this.modelData)==null?void 0:s[at])||{};for(const r of Object.keys(e)){const{value:o,dependencies:n,options:i}=e[r],a=o.bind(this.modelData),c=()=>{this.log.info(`Running effect ${r} for ${this.modelTypeName} (${this.modelId})`),M.runInAction(()=>a())},u=n?M.reaction(()=>n(this.modelData),c,{fireImmediately:!!(i!=null&&i.fireImmediately)}):M.autorun(c);this.disposers.push(u)}}disposeAll(){for(const e of this.disposers)try{e()}catch(s){this.log.info(`Failed to dispose effect for ${this.modelId}`,s)}this.disposers=[]}}const ag=m.createLogger({name:"model-active-machine"}),cg=t=>{const e=b.createMachine(v.INACTIVE,{[v.FAILED]:b.state(b.transition(L.GO_ACTIVE,v.ACTIVATING)),[v.INACTIVE]:b.state(b.transition(L.GO_ACTIVE,v.ACTIVATING)),[v.ACTIVATING]:b.invoke(()=>(t.activeStatus=v.ACTIVATING,t.activate()),b.transition("done",v.ACTIVE,b.action(()=>{t.activeStatus=v.ACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED}))),[v.ACTIVE]:b.state(b.transition(L.GO_INACTIVE,v.DEACTIVATING)),[v.DEACTIVATING]:b.invoke(()=>(t.activeStatus=v.DEACTIVATING,t.deactivate()),b.transition("done",v.INACTIVE,b.action(()=>{t.activeStatus=v.INACTIVE})),b.transition("error",v.FAILED,b.action(()=>{t.activeStatus=v.FAILED})))});return{service:b.interpret(e,r=>ag.debug(r.machine.current)),machine:e}},Li=m.createLogger({name:"model-online-machine"}),lg=t=>{const e=b.createMachine(v.OFFLINE,{[v.ONLINE]:b.state(b.transition(L.GO_OFFLINE,v.OFFLINE,b.action(async()=>{await t.offline(),t.onlineStatus=v.OFFLINE}))),[v.OFFLINE]:b.state(b.transition(L.GO_ONLINE,v.ONLINE,b.action(async()=>{Li.debug(`Going online with model ${t.modelId}`),await t.online(),t.onlineStatus=v.ONLINE,await t.fsm.transitionTo(L.INITIALIZE,v.INITIALIZED)})))}),s=b.interpret(e,r=>Li.debug(r.machine.current));return{machine:e,service:s}},ug=t=>{var r;const e=cg(t).service,s=lg(t).service;return b.createMachine(v.CREATING,{[v.CREATING]:b.state(b.transition(L.CREATE,v.CREATED)),[v.CREATED]:b.state(b.immediate(v.INITIALIZING)),[v.INITIALIZING]:b.invoke(()=>(J(()=>{t.status=v.INITIALIZING}),t.init()),b.transition("done",v.INITIALIZED,b.action(()=>{t.status=v.INITIALIZED})),b.transition("error",v.FAILED,b.action(()=>{m.error(`Model ${t.modelId} - ${t.modelTypeName} failed to initialize. Transitioning to FAILED state.`),t.status=v.FAILED}))),[v.INITIALIZED]:b.state(b.immediate(v.LOADING)),[v.LOADING]:b.invoke(()=>(J(()=>{t.status=v.LOADING}),t.load()),b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.LOADED]:b.state(b.immediate(v.READYING),b.transition(L.UNLOAD,v.UNLOADING)),[v.RESETTING]:b.invoke(()=>{var o;return J(()=>{t.status=v.RESETTING}),(o=t.unload)==null||o.call(t),t.load()},b.transition("done",v.LOADED,b.action(()=>{t.status=v.LOADED}))),[v.READYING]:b.invoke(()=>(J(()=>{t.status=v.READYING}),t.ready()),b.transition("done",v.READY,b.action(()=>{J(()=>{t.status=v.READY}),s.send(L.GO_ONLINE)})),b.transition("error",v.FAILED,b.action(()=>{t.status=v.FAILED}))),[v.READY]:b.state(b.transition(L.UNLOAD,v.UNLOADED,b.action((r=t.unload)==null?void 0:r.bind(t))),b.transition(L.RESET,v.RESETTING),b.transition(L.GO_ONLINE,v.READY,b.action(()=>{s.send(L.GO_ONLINE)})),b.transition(L.GO_OFFLINE,v.READY,b.action(()=>{s.send(L.GO_OFFLINE)})),b.transition(L.GO_ACTIVE,v.READY,b.action(()=>{e.send(L.GO_ACTIVE)})),b.transition(L.GO_INACTIVE,v.READY,b.action(()=>{e.send(L.GO_INACTIVE)}))),[v.UNLOADED]:b.state(),[v.FAILED]:b.state()})},dg=m.createLogger({name:"kos-model-lifecycle"}),hg=t=>({service:b.interpret(ug(t),s=>dg.debug(`state machine for model ${t.modelId}: ${s.machine.current});`))});class fg{constructor(e,s){l(this,"disposer");l(this,"service");this.model=e,this.log=s;const r=hg(e);this.service=r.service,this.service.send(L.CREATE)}get current(){return this.service.machine.current}async transitionTo(e,s,r=v.FAILED){return this.getTransitionStatusFor(s)===s?(this.log.debug(`Model ${this.model.modelId} already in state ${s}, skipping transition`),Promise.resolve()):(this.log.debug(`Transitioning model ${this.model.modelId} with event ${e} toward target ${s}`),new Promise((n,i)=>{var a;(a=this.disposer)==null||a.call(this),this.disposer=M.when(()=>{const c=this.getTransitionStatusFor(s);return c===s||c===r},()=>{this.getTransitionStatusFor(s)===r?(this.log.error(`Model ${this.model.modelId} entered error state ${r} during transition`),i(new Error(`FSM transition failed for model ${this.model.modelId} with event ${e}`))):(this.log.debug(`Model ${this.model.modelId} reached target state ${s}`),n())}),this.service.send(e)}).finally(()=>{var n;(n=this.disposer)==null||n.call(this),this.disposer=void 0}))}getTransitionStatusFor(e){return[v.ACTIVE,v.INACTIVE].includes(e)?this.model.activeStatus:this.model.status}}const nl="browser-router-model";class On{constructor(e,s){l(this,"logger");l(this,"model");l(this,"router",null);l(this,"registered",!1);l(this,"registeredRoutes",[]);this.model=e,this.logger=s}registerAll(){var s;if(!mr(this.model))return;let e=this.model.__httpBrowserRouter;if(!e)for(const r of Object.keys(this.model)){const o=this.model[r];if(o&&typeof o=="object"&&"use"in o&&typeof o.use=="function"){e=o;break}}if(e||(e=(s=$e(nl))==null?void 0:s.model),!e)throw this.logger.error("Cannot register HTTP routes: BrowserRouter not found. The HTTP decorators should have auto-injected it, but something went wrong."),new Error("BrowserRouter is required for HTTP route decorators but was not found. This should not happen as HTTP decorators auto-inject the dependency.");this.setRouter(e)}setRouter(e){this.router=e,this.registered||this.registerRoutes()}hasRoutes(){return mr(this.model)}registerRoutes(){if(!this.router){this.logger.warn("Cannot register routes: router not set");return}if(this.registered){this.logger.debug("Routes already registered");return}const e=Dc(this.model);e.length!==0&&(this.logger.debug(`Registering ${e.length} HTTP routes`),e.forEach(s=>{this.registerRoute(s)}),this.registered=!0)}resolvePropKey(e){const s=/\{PROP_([^}]+)\}/g;let r=e;if(r.includes("{MODEL_ID}")){const n=this.model.id||this.model._id||"unknown";r=r.replace(/\{MODEL_ID\}/g,n)}let o;for(;(o=s.exec(e))!==null;){const n=o[1];if(n in this.model){const i=this.model[n];r=r.replace(o[0],String(i))}else this.logger.warn(`Property '${n}' not found on model for PropKey resolution in path: ${e}`)}return r}registerRoute(e){if(!this.router)return;const s=this.model[e.handler];if(!s||typeof s!="function"){this.logger.error(`Handler method '${e.handler}' not found on model`);return}const r=this.resolvePropKey(e.path);this.logger.debug(`Registering ${e.method} ${r} -> ${e.handler}`+(r!==e.path?` (resolved from ${e.path})`:""));const o=async(n,i)=>{var a;try{await s.call(this.model,n,i)}catch(c){this.logger.error(`Error in route handler ${e.method} ${r}:`,c),(a=i.status)==null||a.call(i,500).send({error:"Internal server error",message:c instanceof Error?c.message:String(c)})}};this.checkForDuplicateRoute(e.method,r),this.router.use(e.method,r,o),this.registeredRoutes.push({method:e.method,path:r})}checkForDuplicateRoute(e,s){if(!this.router)return;this.router.getRoutes().find(n=>n.method===e&&n.path===s)&&this.logger.warn(`Duplicate route detected: ${e} ${s}. This route is already registered by another model. The new handler from model '${this.model.id||"unknown"}' will override the existing one. Only the last registered handler will receive requests. Consider using different paths or namespacing to avoid conflicts.`)}dispose(){if(this.router&&this.registeredRoutes.length>0){this.logger.debug(`Removing ${this.registeredRoutes.length} HTTP routes for model ${this.model.id||"unknown"}`);let e=0;for(const s of this.registeredRoutes){const r=this.router.remove(s.method,s.path);e+=r,r>0?this.logger.debug(`Removed route: ${s.method} ${s.path}`):this.logger.warn(`Failed to remove route: ${s.method} ${s.path} (not found)`)}this.logger.debug(`Successfully removed ${e} routes from browser router`)}this.registered=!1,this.registeredRoutes=[],this.router=null}getRegisteredRoutes(){return[...this.registeredRoutes]}}function pg(t,e){if(!mr(t))return;const s=$e(nl);if(!(s!=null&&s.model))throw e.error("Cannot register HTTP routes: BrowserRouter not found. Make sure to include BrowserRouter in your model dependencies or create an instance."),new Error("BrowserRouter is required for HTTP route decorators but was not found. Add it as a dependency using @kosDependency or ensure an instance exists.");new On(t,e).setRouter(s.model)}class gg{constructor(e){l(this,"queue",[]);this.log=e}enqueue(e,s,r){this.queue.push({handler:e,receivedAt:Date.now(),topic:s,payload:r})}flush(){if(this.queue.length!==0){this.log.warn(`Processing ${this.queue.length} offline message(s)`);for(const e of this.queue)try{e.handler()}catch(s){this.log.error("Error while processing offline message:",s)}this.queue=[],this.log.info("Offline queue flushed")}}flushWithStrategy(e,s,r){if(this.queue.length===0)return;const o=this.queue.length,n=this.filterEventsByStrategy(e,s,r),i=o-n.length;this.log.warn(`Processing ${n.length}/${o} offline message(s) with strategy: ${e}`);for(const a of n)try{a.handler()}catch(c){this.log.error(`Error while processing offline message for topic ${a.topic}:`,c)}this.queue=[],this.log.info(`Offline queue flushed with strategy ${e}. Replayed: ${n.length}, Discarded: ${i}`)}filterEventsByStrategy(e,s,r){switch(e){case it.ALL:return[...this.queue];case it.AFTER_REQUEST:return s===void 0?(this.log.warn("AFTER_REQUEST strategy requires baselineRequestedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=s);case it.AFTER_RESPONSE:return r===void 0?(this.log.warn("AFTER_RESPONSE strategy requires baselineReceivedAt, replaying all events"),[...this.queue]):this.queue.filter(o=>o.receivedAt>=r);case it.NONE:return[];default:return this.log.warn(`Unknown replay strategy: ${e}, replaying all`),[...this.queue]}}getStatistics(e,s){if(this.queue.length===0)return{total:0};const r=this.queue.map(n=>n.receivedAt),o={total:this.queue.length,oldestEventAt:Math.min(...r),newestEventAt:Math.max(...r)};return e!==void 0&&(o.afterRequest=this.queue.filter(n=>n.receivedAt>=e).length),s!==void 0&&(o.afterResponse=this.queue.filter(n=>n.receivedAt>=s).length),o}clear(){this.queue=[]}get length(){return this.queue.length}get isEmpty(){return this.queue.length===0}}class mg{constructor(e,s){l(this,"unsubscribers",[]);this.model=e,this.log=s}register(){const e=this.model.modelId,s=C("/kosCore/online",async()=>{this.log.debug(`Online event received for ${e}, waiting for readiness...`),await this.model.whenReady(),this.log.debug(`${e} is ready — sending GO_ONLINE`),await this.model.fsm.transitionTo(L.GO_ONLINE,v.ONLINE)}),r=C("/kosCore/offline",async()=>{this.log.debug(`Offline event received for ${e} — sending GO_OFFLINE`),await this.model.fsm.transitionTo(L.GO_OFFLINE,v.OFFLINE)});this.unsubscribers.push(s.unsubscribe),this.unsubscribers.push(r.unsubscribe)}dispose(){this.unsubscribers.forEach(e=>e()),this.unsubscribers=[]}}const il=()=>({isMock:!1,URL:exports.BASE_URL}),yg=m.createLogger({name:"kos-service-request"}),bg="errUnknown";async function Js(t,e,s,r,o){const n=r!=null&&r.path?Object.keys(r.path).reduce((h,f)=>String(h).replace(`{${f}}`,r==null?void 0:r.path[f]),String(t)):String(t),i=r!=null&&r.query?Object.keys(r.query).map(h=>`${encodeURIComponent(h)}=${encodeURIComponent(r.query[h])}`).join("&"):"",a=`${il().URL}${n}${i?`?${i}`:""}`;yg.debug(`fullUrl: ${a}`);const c={method:String(e).toUpperCase(),body:null,...s};o&&(c.body=JSON.stringify(o));const u=await exports.kosFetch(a,c);return u.status<200||u.status>=400?[`${u.statusText||bg}`,null]:[null,(await u.json()).data]}function Be(){return{get:(t,e,s)=>Js(t,"get",s,e),post:(t,e,s,r)=>Js(t,"post",r,e,s),put:(t,e,s,r)=>Js(t,"put",r,e,s),delete:(t,e,s,r)=>Js(t,"delete",r,e,s)}}const Ae=Be(),al=Object.freeze(Object.defineProperty({__proto__:null,default:Ae},Symbol.toStringTag,{value:"Module"})),st=m.createLogger({name:"kos-service-request-manager",group:"Model"});function vg(t,e){return!t.condition||t.condition(e)}function wg(t,e){return Me({value:t.path,modelId:e.id,modelData:e})}function Eg(t,e){if(t.pathParams)return Me({value:typeof t.pathParams=="function"?t.pathParams(e):t.pathParams,modelId:e.id,modelData:e})}function Mg(t,e){if(t.queryParams)return Me({value:typeof t.queryParams=="function"?t.queryParams(e):t.queryParams,modelId:e.id,modelData:e})}function Tg(t,e){if(t.body)return Me({value:typeof t.body=="function"?t.body(e):t.body,modelId:e.id,modelData:e})}function _g(t){return(t||"get").toLowerCase()}function Fi(t,e){return`${e.toUpperCase()}:${t}`}function cl(t){return t==null}function Sg(t,e,s,r){r&&cl(t)&&st.warn(`Required field '${e}' is missing in response for ${s}`)}function Ig(t,e){return cl(t)&&e!==void 0?e:t}class Og{constructor(e,s){l(this,"model");l(this,"responseStore");l(this,"handlers");this.model=e,this.responseStore=s,this.handlers=new Map,this.discoverHandlers()}discoverHandlers(){const s=Object.getPrototypeOf(this.model)[ct]||{};Object.values(s).forEach(r=>{const o=r.lifecycle;this.handlers.has(o)||this.handlers.set(o,[]),this.handlers.get(o).push(r)}),Object.keys(s).length>0&&st.debug(`Discovered ${Object.keys(s).length} service request handlers for model ${this.model.id}`)}async executeForLifecycle(e){const s=this.handlers.get(e);!s||s.length===0||(st.debug(`Executing ${s.length} service requests for lifecycle ${e}`),await Promise.all(s.map(r=>this.executeHandler(r))))}async executeHandler(e){try{if(!this.shouldProcessRequest(e))return;const s=await this.prepareAndExecuteRequest(e);await this.processAndStoreResponse(s,e)}catch(s){const r=s instanceof Error?s:new Error(String(s));await this.handleError(r,e)}}shouldProcessRequest(e){return vg(e,this.model)?!0:(st.debug(`Skipping request ${e.path} - condition returned false`),!1)}async prepareAndExecuteRequest(e){const s=this.prepareRequest(e),r=this.captureRequestTiming(),[o,n]=await this.performRequest(s),i=this.captureResponseTiming();return{requestContext:s,error:o,response:n,requestedAt:r.requestedAt,receivedAt:i.receivedAt}}captureRequestTiming(){return{requestedAt:Date.now()}}captureResponseTiming(){return{receivedAt:Date.now()}}async processAndStoreResponse(e,s){if(e.error){await this.handleError(new Error(e.error),s);return}const r=await this.processResponse(e.response,s);await this.storeAndInvokeHandler(r,s,e.requestContext.resolvedPath,e.requestedAt,e.receivedAt)}prepareRequest(e){const s=wg(e,this.model),r=Eg(e,this.model),o=Mg(e,this.model),n=Tg(e,this.model),i=_g(e.method);return{resolvedPath:s,method:i,pathParams:r,queryParams:o,body:n}}async performRequest(e){return await this.makeRequest(e.resolvedPath,e.method,{path:e.pathParams,query:e.queryParams},e.body)}async processResponse(e,s){let r=e;return s.transform&&(r=s.transform(e)),s.mappings&&s.mappings.length>0&&(r=this.applyMappings(r,s)),s.iterateOver&&(r=await this.handleIteration(r,s)),r}async storeAndInvokeHandler(e,s,r,o,n){const i=s.cache||{retention:de.SINGLE},a=Fi(r,s.method||"get");this.responseStore.set(a,e,i,o,n),await s.originalHandler.call(this.model,e),this.triggerBaselineQueueFlush(r),this.responseStore.shouldCleanupAfterHandler(a)&&this.responseStore.delete(a)}triggerBaselineQueueFlush(e){const s=this.model.subscriptionManager;!s||!s.flushQueueForBaseline||s.flushQueueForBaseline(e)}async makeRequest(e,s,r,o){const n=Ae;switch(s){case"get":return await n.get(e,r);case"post":return await n.post(e,r,o);case"put":return await n.put(e,r,o);case"delete":return await n.delete(e,r,o);default:return[`Unsupported HTTP method: ${s}`,null]}}applyMappings(e,s){if(!s.mappings||s.mappings.length===0)return e;const r={};return s.mappings.forEach(o=>{const n=this.getNestedValue(e,o.from),i=o.transform?this.applyTransform(n,o.transform):n;Sg(i,o.from,s.path,o.required||!1);const a=Ig(i,o.default);r[o.to]=a}),r}getNestedValue(e,s){return s.split(".").reduce((r,o)=>r==null?void 0:r[o],e)}applyTransform(e,s){if(typeof s=="function")return s(e);switch(s){case"string":return String(e);case"number":return Number(e);case"boolean":return!!e;case"date":return e?new Date(e):void 0;case"json":return typeof e=="string"?JSON.parse(e):e;default:return st.warn(`Unknown transformer: ${s}`),e}}async handleIteration(e,s){if(!s.iterateOver)return e;const r=this.getNestedValue(e,s.iterateOver);return Array.isArray(r)?s.modelFactory?r.map(o=>{const n=s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o,i=s.idExtractor?s.idExtractor(n):n.id;if(!i)throw new Error("Cannot create model instance: no ID found in response data. Provide an 'idExtractor' function or ensure response items have an 'id' field.");const a=s.modelFactory;return typeof a=="function"?a(i)(n):a.instance(i).options(n).build()}):r.map(o=>s.mappings&&s.mappings.length>0?this.applyMappings(o,s):o):(st.warn(`iterateOver path '${s.iterateOver}' did not resolve to an array`),[])}async handleError(e,s){const r=s.errorHandler||{strategy:"throw"};switch(r.onError&&r.onError(e,this.model),r.strategy){case"throw":throw e;case"log":st.error(`Service request failed for ${s.path}:`,e.message);break;case"ignore":break;case"default":if(r.defaultValue!==void 0){const o=Fi(s.path,s.method||"get");this.responseStore.set(o,r.defaultValue,s.cache||{retention:de.SINGLE})}break}}}class $g{constructor(e){l(this,"subscription");l(this,"unsubscribe");l(this,"eventType");this.eventType=e,this.subscription={queue:[],resolvers:[],closed:!1};const s=C(e,r=>{if(!this.subscription.closed&&r!==void 0){const o=this.subscription.resolvers.shift();o?o(r):this.subscription.queue.push(r)}});this.unsubscribe=s.unsubscribe}async next(){return this.subscription.closed&&this.subscription.queue.length===0?{done:!0,value:void 0}:this.subscription.queue.length>0?{done:!1,value:this.subscription.queue.shift()}:new Promise(e=>{this.subscription.closed?e({done:!0,value:void 0}):this.subscription.resolvers.push(s=>{e({done:!1,value:s})})})}async return(){return this.subscription.closed=!0,this.unsubscribe(),this.subscription.resolvers.forEach(e=>{e(void 0)}),this.subscription.resolvers=[],{done:!0,value:void 0}}async throw(e){throw this.subscription.closed=!0,this.unsubscribe(),e}[Symbol.asyncIterator](){return this}}function Ni(t){return new $g(t)}const ll=({path:t,requestId:e,method:s,destinationAddress:r})=>{let o=`${Kr}:${s}
32
32
  `;return o+=`topic:${t}
33
33
  `,o+=`${Kt}:${t}
34
34
  `,o+=`${Ns}:${e}