@zenflux/core 0.1.11 → 0.1.13

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.
Files changed (50) hide show
  1. package/dist/zenflux-core.cjs +5 -5
  2. package/dist/zenflux-core.mjs +5 -5
  3. package/package.json +3 -4
  4. package/src/bases/controller-base.ts +0 -96
  5. package/src/bases/index.ts +0 -6
  6. package/src/bases/initialize-base.ts +0 -32
  7. package/src/bases/object-base.ts +0 -55
  8. package/src/clients/http.ts +0 -152
  9. package/src/command-bases/command-base.ts +0 -82
  10. package/src/command-bases/command-internal.ts +0 -11
  11. package/src/command-bases/command-public.ts +0 -12
  12. package/src/command-bases/command-restful.ts +0 -55
  13. package/src/command-bases/index.ts +0 -8
  14. package/src/errors/command-already-registered.ts +0 -13
  15. package/src/errors/command-not-found.ts +0 -12
  16. package/src/errors/controller-already-registered.ts +0 -13
  17. package/src/errors/controller-already-set.ts +0 -13
  18. package/src/errors/error-with-metadata.ts +0 -14
  19. package/src/errors/force-method-implementation.ts +0 -15
  20. package/src/errors/index-public.ts +0 -1
  21. package/src/errors/index.ts +0 -10
  22. package/src/exports-index.ts +0 -13
  23. package/src/exports.ts +0 -58
  24. package/src/index.ts +0 -18
  25. package/src/interfaces/commands.ts +0 -17
  26. package/src/interfaces/config.ts +0 -23
  27. package/src/interfaces/index.ts +0 -8
  28. package/src/interfaces/logger.ts +0 -19
  29. package/src/interfaces/restful.ts +0 -23
  30. package/src/managers/commands.ts +0 -268
  31. package/src/managers/controllers.ts +0 -40
  32. package/src/managers/export.ts +0 -30
  33. package/src/managers/index.ts +0 -8
  34. package/src/managers/internal.ts +0 -11
  35. package/src/managers/restful.ts +0 -117
  36. package/src/modules/debugger.ts +0 -89
  37. package/src/modules/event-bus/event-bus.ts +0 -204
  38. package/src/modules/logger/config.ts +0 -44
  39. package/src/modules/logger/implementation.ts +0 -287
  40. package/src/modules/logger/index.ts +0 -2
  41. package/src/modules/logger/logger-browser-infra.ts +0 -344
  42. package/src/modules/logger/types/picocolors.d.ts +0 -15
  43. package/src/modules/logger/utils/index.ts +0 -3
  44. package/src/modules/logger/utils/object.ts +0 -19
  45. package/src/modules/logger/utils/rgb.ts +0 -34
  46. package/src/modules/mcp-server/mcp-server.ts +0 -139
  47. package/src/modules/mcp-server/mcp-service.ts +0 -80
  48. package/src/modules/service/service-base.ts +0 -55
  49. package/src/modules/service/service-locator.ts +0 -205
  50. package/src/modules/service/service-with-dependencies-base.ts +0 -51
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Bundled with love using the help of @zenflux/cli toolkit v0.1.31
3
- * Bundle name: @zenflux/core fileName: 'zenflux-core', built at Thu Nov 20 2025 07:17:31 GMT+0200 (Israel Standard Time)
2
+ * Bundled with love using the help of @zenflux/cli toolkit v0.1.33
3
+ * Bundle name: @zenflux/core fileName: 'zenflux-core', built at Thu Nov 20 2025 07:26:23 GMT+0200 (Israel Standard Time)
4
4
  */
5
5
 
6
6
  'use strict';
@@ -109,13 +109,13 @@ class EventBus extends ObjectBase{static instance=null;objects=new Map;eventEmit
109
109
  * @copyright http://jsfiddle.net/96sME/
110
110
  */const getHexColorDelta=function(hex1,hex2){hex1=hex1.replace("#","");hex2=hex2.replace("#","");const r1=parseInt(hex1.substring(0,2),16);const g1=parseInt(hex1.substring(2,4),16);const b1=parseInt(hex1.substring(4,6),16);const r2=parseInt(hex2.substring(0,2),16);const g2=parseInt(hex2.substring(2,4),16);const b2=parseInt(hex2.substring(4,6),16);let r=255-Math.abs(r1-r2);let g=255-Math.abs(g1-g2);let b=255-Math.abs(b1-b2);r/=255;g/=255;b/=255;return (r+g+b)/3};
111
111
 
112
- const MAX_MAPPING_RECURSIVE_DEPTH=4,UNKNOWN_CALLER_NAME="anonymous function",MAX_COLOR_ATTEMPTS=25;Error.stackTraceLimit=50;class LoggerBrowserInfra extends ObjectBase{static mappers=[];static mapperDepth=0;static colorsOwners={};static colorsUsed=[];defaultStyle;owner;args;color;outputHandler=console.log;static getName(){return "ZenFlux/Logging/Modules/LoggerBrowserInfra"}static reset(){LoggerBrowserInfra.mappers=[];LoggerBrowserInfra.mapperDepth=0;LoggerBrowserInfra.colorsUsed=[];LoggerBrowserInfra.colorsOwners={};}static createObjectMapper(callback){LoggerBrowserInfra.mappers.push(callback);}static useObjectMapper(obj,shouldHandleChildren=true){if(!obj||Array.isArray(obj)||"object"!==typeof obj){return obj}LoggerBrowserInfra.mapperDepth++;let result={...obj};LoggerBrowserInfra.mappers.forEach(mapper=>{result=mapper(obj)||result;});if(LoggerBrowserInfra.mapperDepth>=MAX_MAPPING_RECURSIVE_DEPTH){LoggerBrowserInfra.mapperDepth--;return result}if(shouldHandleChildren&&result){Object.entries(result).forEach(([key,value])=>{result[key]=this.useObjectMapper(value,true);});}LoggerBrowserInfra.mapperDepth--;return result}constructor(owner,args={}){super();this.args={repeatedly:false,...args};this.owner=owner;this.initialize();}getOwnerName(){if(typeof this.owner==="string"){return this.owner}if(this.owner instanceof ObjectBase){return this.owner.getName()}if(this.owner&&typeof this.owner.getName==="function"){return this.owner.getName()}return "UnknownOwner"}initialize(){const ownerName=this.getOwnerName();if(this.args.repeatedly&&LoggerBrowserInfra.colorsOwners[ownerName]){this.color=LoggerBrowserInfra.colorsOwners[ownerName];}else {this.color=this.getRandomColor();LoggerBrowserInfra.colorsUsed.push(this.color);}LoggerBrowserInfra.colorsOwners[ownerName]=this.color;this.defaultStyle=["color: grey;font-size:7px","display: block",`color: ${this.color}`,"color: grey","font-weight: bold","color: #607D8B","font-size: 16px;color: red;font-weight:800"];}output(...args){this.outputHandler.apply(this,args);}setOutputHandler(outputHandler){this.outputHandler=outputHandler;}printFunctionNotify(prefix,caller,output){const callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c() ${output}%c`].concat(this.defaultStyle));}printObjectEfficient(prefix,caller,params){params=Object.assign({},params);if(typeof params==="string"){this.printInLineString(prefix,caller,params);return}if(Object.keys(params).length===1){const key=Object.keys(params)[0];let value=Object.values(params)[0];if("object"===typeof value){this.printInNextLineObject(prefix,caller,key,value||{});}else if("function"===typeof value){this.printInLineFunction(prefix,caller,key,value);}else {this.printInLineElement(prefix,caller,key,value);}return}this.printMultiLineObject(prefix,caller,params);}printInLineElement(prefix,caller,key,value,notice=""){const callerName=this.getCallerName(caller),ownerName=this.getOwnerName(),format=notice.length?`%c(${prefix})-> %c%c${ownerName}%c::%c${callerName}%c() ->> [${notice}] ->> ${key}: '${value}'%c`:`%c(${prefix})-> %c%c${ownerName}%c::%c${callerName}%c() ->> ${key}: '${value}'%c`;this.output.apply(this,[format].concat(this.defaultStyle));}printInLineFunction(prefix,caller,key,fn){fn=this.getFunctionView(fn);this.printInLineElement(prefix,caller,key,fn);}printInLineString(prefix,caller,string){this.printInLineElement(prefix,caller,"(string)",string);}printInNextLineObject(prefix,caller,key,obj){const mapped=LoggerBrowserInfra.useObjectMapper(obj),callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c() ->> ${key} %c↓`].concat(this.defaultStyle));this.output(mapped);}printMultiLineObject(prefix,caller,obj){const callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c(${Object.keys(obj).join(", ")}) %c↓`].concat(this.defaultStyle));for(let key in obj){let value=obj[key];if(typeof value==="object"){const mapped=LoggerBrowserInfra.useObjectMapper(value);value=JSON.stringify(mapped,reduceCircularReferences());}else if(typeof obj[key]=="function"){value=this.getFunctionView(value);}this.output.apply(this,["%c"+key+": `"+value+"`","color: #a3a3a3"]);}}getRandomColor(){const hex="0123456789ABCDEF";let attempt=0;let similarityThreshold=.8;let lastTried="#000000";while(attempt<MAX_COLOR_ATTEMPTS){let color="#";for(let i=0;i<6;i++){color+=hex[Math.floor(Math.random()*16)];}lastTried=color;const similar=LoggerBrowserInfra.colorsUsed.some(value=>{return getHexColorDelta(color,value)>=similarityThreshold});if(!similar){return color}attempt++;if(attempt%5===0&&similarityThreshold>.6){similarityThreshold-=.05;}}return lastTried}getCallerName(caller){if("function"===typeof caller){return caller.prototype instanceof ObjectBase?"constructor":caller.name}throw new Error("Invalid caller")}getFunctionView(fn){let fReturn=UNKNOWN_CALLER_NAME;if(typeof fn!=="string"&&fn.name.length!==0){fReturn=fn.name.split(" ")[1]+"()";}return fReturn}}
112
+ const MAX_MAPPING_RECURSIVE_DEPTH=4,UNKNOWN_CALLER_NAME="anonymous function",MAX_COLOR_ATTEMPTS=25,FALLBACK_PALETTE=["#EF4444","#F59E0B","#10B981","#3B82F6","#6366F1","#EC4899","#8B5CF6","#14B8A6","#F97316","#A855F7","#22D3EE","#84CC16"];Error.stackTraceLimit=50;class LoggerBrowserInfra extends ObjectBase{static mappers=[];static mapperDepth=0;static colorsOwners={};static colorsUsed=[];defaultStyle;owner;args;color;outputHandler=console.log;static getName(){return "ZenFlux/Logging/Modules/LoggerBrowserInfra"}static reset(){LoggerBrowserInfra.mappers=[];LoggerBrowserInfra.mapperDepth=0;LoggerBrowserInfra.colorsUsed=[];LoggerBrowserInfra.colorsOwners={};}static createObjectMapper(callback){LoggerBrowserInfra.mappers.push(callback);}static useObjectMapper(obj,shouldHandleChildren=true){if(!obj||Array.isArray(obj)||"object"!==typeof obj){return obj}LoggerBrowserInfra.mapperDepth++;let result={...obj};LoggerBrowserInfra.mappers.forEach(mapper=>{result=mapper(obj)||result;});if(LoggerBrowserInfra.mapperDepth>=MAX_MAPPING_RECURSIVE_DEPTH){LoggerBrowserInfra.mapperDepth--;return result}if(shouldHandleChildren&&result){Object.entries(result).forEach(([key,value])=>{result[key]=this.useObjectMapper(value,true);});}LoggerBrowserInfra.mapperDepth--;return result}constructor(owner,args={}){super();this.args={repeatedly:false,...args};this.owner=owner;this.initialize();}getOwnerName(){if(typeof this.owner==="string"){return this.owner}if(this.owner instanceof ObjectBase){return this.owner.getName()}if(this.owner&&typeof this.owner.getName==="function"){return this.owner.getName()}return "UnknownOwner"}initialize(){const ownerName=this.getOwnerName();if(this.args.repeatedly&&LoggerBrowserInfra.colorsOwners[ownerName]){this.color=LoggerBrowserInfra.colorsOwners[ownerName];}else {this.color=this.getRandomColor();LoggerBrowserInfra.colorsUsed.push(this.color);}LoggerBrowserInfra.colorsOwners[ownerName]=this.color;this.defaultStyle=["color: grey;font-size:7px","display: block",`color: ${this.color}`,"color: grey","font-weight: bold","color: #607D8B","font-size: 16px;color: red;font-weight:800"];}output(...args){this.outputHandler.apply(this,args);}setOutputHandler(outputHandler){this.outputHandler=outputHandler;}printFunctionNotify(prefix,caller,output){const callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c() ${output}%c`].concat(this.defaultStyle));}printObjectEfficient(prefix,caller,params){params=Object.assign({},params);if(typeof params==="string"){this.printInLineString(prefix,caller,params);return}if(Object.keys(params).length===1){const key=Object.keys(params)[0];let value=Object.values(params)[0];if("object"===typeof value){this.printInNextLineObject(prefix,caller,key,value||{});}else if("function"===typeof value){this.printInLineFunction(prefix,caller,key,value);}else {this.printInLineElement(prefix,caller,key,value);}return}this.printMultiLineObject(prefix,caller,params);}printInLineElement(prefix,caller,key,value,notice=""){const callerName=this.getCallerName(caller),ownerName=this.getOwnerName(),format=notice.length?`%c(${prefix})-> %c%c${ownerName}%c::%c${callerName}%c() ->> [${notice}] ->> ${key}: '${value}'%c`:`%c(${prefix})-> %c%c${ownerName}%c::%c${callerName}%c() ->> ${key}: '${value}'%c`;this.output.apply(this,[format].concat(this.defaultStyle));}printInLineFunction(prefix,caller,key,fn){fn=this.getFunctionView(fn);this.printInLineElement(prefix,caller,key,fn);}printInLineString(prefix,caller,string){this.printInLineElement(prefix,caller,"(string)",string);}printInNextLineObject(prefix,caller,key,obj){const mapped=LoggerBrowserInfra.useObjectMapper(obj),callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c() ->> ${key} %c↓`].concat(this.defaultStyle));this.output(mapped);}printMultiLineObject(prefix,caller,obj){const callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c(${Object.keys(obj).join(", ")}) %c↓`].concat(this.defaultStyle));for(let key in obj){let value=obj[key];if(typeof value==="object"){const mapped=LoggerBrowserInfra.useObjectMapper(value);value=JSON.stringify(mapped,reduceCircularReferences());}else if(typeof obj[key]=="function"){value=this.getFunctionView(value);}this.output.apply(this,["%c"+key+": `"+value+"`","color: #a3a3a3"]);}}getRandomColor(){const hex="0123456789ABCDEF";let attempt=0;let similarityThreshold=.8;let lastTried="#000000";while(attempt<MAX_COLOR_ATTEMPTS){let color="#";for(let i=0;i<6;i++){color+=hex[Math.floor(Math.random()*16)];}lastTried=color;const similar=LoggerBrowserInfra.colorsUsed.some(value=>{return getHexColorDelta(color,value)>=similarityThreshold});if(!similar){return color}attempt++;if(attempt%5===0&&similarityThreshold>.6){similarityThreshold-=.05;}}const unusedPaletteColor=FALLBACK_PALETTE.find(paletteColor=>{return !LoggerBrowserInfra.colorsUsed.includes(paletteColor)});if(unusedPaletteColor){return unusedPaletteColor}return FALLBACK_PALETTE[LoggerBrowserInfra.colorsUsed.length%FALLBACK_PALETTE.length]||lastTried}getCallerName(caller){if("function"===typeof caller){return caller.prototype instanceof ObjectBase?"constructor":caller.name}throw new Error("Invalid caller")}getFunctionView(fn){let fReturn=UNKNOWN_CALLER_NAME;if(typeof fn!=="string"&&fn.name.length!==0){fReturn=fn.name.split(" ")[1]+"()";}return fReturn}}
113
113
 
114
114
  const DEFAULT_LOG_PREFIX=pc.white("⚪ - [LOG]"),DEFAULT_INFO_PREFIX=pc.blue("🔵 - [INFO]"),DEFAULT_DEBUG_PREFIX=pc.gray("🟤 - [DEBUG]"),DEFAULT_WARN_PREFIX=pc.yellow("🟡 - [WARN]"),DEFAULT_ERROR_PREFIX=pc.red("🔴 - [ERROR]"),DEFAULT_ADMIN_PREFIX=pc.bold("🟣 - [ADMIN]");const registeredNames={};class Logger extends LoggerBrowserInfra{static lastLogTime=Date.now();ownerName;messagePrefixes=[];config={};static getName(){return "ZenFlux/Core/Modules/Logger"}static getLogLevelString(){return getLoggerLogLevelString()}static getLogLevel(){return getLoggerLogLevel()}static isDebugEnabled(){return isLoggerDebugEnabled()}constructor(owner,options){const{repeatedly=false,skipEventBusHook}=options||{};super(owner,{repeatedly});this.config={skipEventBusHook};this.ownerName=Logger.resolveOwnerName(owner);if(registeredNames[this.ownerName]){throw new Error(`Logger for '${this.ownerName}' already exists`)}registeredNames[this.ownerName]=true;if(isLoggerDisabled()){this.disableLoggers();return}if(isLoggerPreviousSourceDisabled()){this.getPreviousSource=()=>"";}switch(getLoggerLogLevel()){case 0:this.error=()=>{};case 1:this.warn=()=>{};case 2:this.admin=()=>{};case 3:this.info=()=>{};case 4:this.log=()=>{};case 5:this.debug=()=>{};}if(!this.config.skipEventBusHook){EventBus.$.registerMultiInstances(this,[this.outputEvent]);}}addMessagePrefix(prefix){this.messagePrefixes.push(prefix);}log(caller,message,...params){this.writeLog(DEFAULT_LOG_PREFIX,caller,message,...params);}info(caller,message,...params){this.writeLog(DEFAULT_INFO_PREFIX,caller,message,...params);}debug(caller,message,...params){this.writeLog(DEFAULT_DEBUG_PREFIX,caller,message,...params);}warn(caller,message,...params){this.writeLog(DEFAULT_WARN_PREFIX,caller,message,...params);}error(caller,message,...params){this.writeLog(DEFAULT_ERROR_PREFIX,caller,message,...params);}admin(caller,message,...params){this.writeLog(DEFAULT_ADMIN_PREFIX,caller,message,...params);}startsEmpty(caller){this.printFunctionNotify("▶",caller,"");}startsWith(caller,params){this.printObjectEfficient("▶",caller,params);}dump(caller,params={},notice=""){for(const key in params){if(typeof params[key]==="object"){params[key]=JSON.stringify(LoggerBrowserInfra.useObjectMapper(params[key]),reduceCircularReferences());}this.printInLineElement("dp",caller,key,params[key],notice);}}drop(caller,according,data){for(const key in according){this.printInLineElement("dr",caller,key,according[key],"corresponding");}this.output(data);}throw(caller,output,name="null",params={}){this.printFunctionNotify("tw",caller,output);if(params){this.printInNextLineObject("tw",caller,name,params);}throw new Error().stack}beep(){console.log("\x07");}clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}outputEvent(_prefix,_timeDiff,_source,_messagePrefix,_message,_params){}static resolveOwnerName(owner){if(typeof owner==="string"){return owner}if(owner instanceof ObjectBase){return owner.getName()}if(owner&&typeof owner.getName==="function"){return owner.getName()}return "UnknownOwner"}disableLoggers(){this.error=()=>{};this.warn=()=>{};this.admin=()=>{};this.info=()=>{};this.log=()=>{};this.debug=()=>{};}getStackTrace(){const stackTrace=(new Error().stack||"").split("\n");const stackLines=stackTrace.slice(1);const stackRegex=/ at (.+?) \((.+?)\)/;const result=[];for(const line of stackLines){const match=line.match(stackRegex);if(match){const[,context,file]=match;const parsedLine={context,file};if(line.startsWith("new")){parsedLine.isNew=true;parsedLine.object=context.split(" ")[1];}else if(context!=="Object.<anonymous>"){parsedLine.object=context;}result.push(parsedLine);}}return result}getPreviousSource(){const stack=this.getStackTrace().filter(line=>line.file.includes("/src/")).filter(line=>!line.file.includes("logger.ts")).filter(line=>!line.file.includes("debugger.ts")).filter(line=>!line.file.includes("/node_modules/"));let previousSource="";const previousCaller=stack[1]?.object?.split(".");if(previousCaller?.length>1){const previousCallerName=previousCaller[0],previousCallerMethod=previousCaller[1];previousSource=`${previousCallerName}::${previousCallerMethod}]`+"[";}return previousSource}writeLog(prefix,caller,message,...params){const source=this.getPreviousSource()+pc.white(`${this.ownerName}::${this.getCallerName(caller)}`);let messagePrefix="";if(this.messagePrefixes.length){messagePrefix=`[${this.messagePrefixes.join("][")}]`;}const timeDiff=(Date.now()-Logger.lastLogTime).toString().padStart(4,"0");this.outputEvent(prefix,timeDiff,source,messagePrefix,message,params);const output=`${prefix}[+${timeDiff}ms][${source}]${messagePrefix}: ${message}`;console.log(output,...params);Logger.lastLogTime=Date.now();}}
115
115
 
116
116
  var _package = {
117
117
  "name": "@zenflux/core",
118
- "version": "0.1.9",
118
+ "version": "0.1.11",
119
119
  "types": "dist/zenflux-core.d.ts",
120
120
  "type": "module",
121
121
  "files": [
@@ -161,7 +161,7 @@ var _package = {
161
161
  }
162
162
  };
163
163
  const name = "@zenflux/core";
164
- const version = "0.1.9";
164
+ const version = "0.1.11";
165
165
  const types = "dist/zenflux-core.d.ts";
166
166
  const type = "module";
167
167
  const files = ["dist","src","types"];
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Bundled with love using the help of @zenflux/cli toolkit v0.1.31
3
- * Bundle name: @zenflux/core fileName: 'zenflux-core', built at Thu Nov 20 2025 07:17:31 GMT+0200 (Israel Standard Time)
2
+ * Bundled with love using the help of @zenflux/cli toolkit v0.1.33
3
+ * Bundle name: @zenflux/core fileName: 'zenflux-core', built at Thu Nov 20 2025 07:26:23 GMT+0200 (Israel Standard Time)
4
4
  */
5
5
 
6
6
  import util from 'node:util';
@@ -105,13 +105,13 @@ class EventBus extends ObjectBase{static instance=null;objects=new Map;eventEmit
105
105
  * @copyright http://jsfiddle.net/96sME/
106
106
  */const getHexColorDelta=function(hex1,hex2){hex1=hex1.replace("#","");hex2=hex2.replace("#","");const r1=parseInt(hex1.substring(0,2),16);const g1=parseInt(hex1.substring(2,4),16);const b1=parseInt(hex1.substring(4,6),16);const r2=parseInt(hex2.substring(0,2),16);const g2=parseInt(hex2.substring(2,4),16);const b2=parseInt(hex2.substring(4,6),16);let r=255-Math.abs(r1-r2);let g=255-Math.abs(g1-g2);let b=255-Math.abs(b1-b2);r/=255;g/=255;b/=255;return (r+g+b)/3};
107
107
 
108
- const MAX_MAPPING_RECURSIVE_DEPTH=4,UNKNOWN_CALLER_NAME="anonymous function",MAX_COLOR_ATTEMPTS=25;Error.stackTraceLimit=50;class LoggerBrowserInfra extends ObjectBase{static mappers=[];static mapperDepth=0;static colorsOwners={};static colorsUsed=[];defaultStyle;owner;args;color;outputHandler=console.log;static getName(){return "ZenFlux/Logging/Modules/LoggerBrowserInfra"}static reset(){LoggerBrowserInfra.mappers=[];LoggerBrowserInfra.mapperDepth=0;LoggerBrowserInfra.colorsUsed=[];LoggerBrowserInfra.colorsOwners={};}static createObjectMapper(callback){LoggerBrowserInfra.mappers.push(callback);}static useObjectMapper(obj,shouldHandleChildren=true){if(!obj||Array.isArray(obj)||"object"!==typeof obj){return obj}LoggerBrowserInfra.mapperDepth++;let result={...obj};LoggerBrowserInfra.mappers.forEach(mapper=>{result=mapper(obj)||result;});if(LoggerBrowserInfra.mapperDepth>=MAX_MAPPING_RECURSIVE_DEPTH){LoggerBrowserInfra.mapperDepth--;return result}if(shouldHandleChildren&&result){Object.entries(result).forEach(([key,value])=>{result[key]=this.useObjectMapper(value,true);});}LoggerBrowserInfra.mapperDepth--;return result}constructor(owner,args={}){super();this.args={repeatedly:false,...args};this.owner=owner;this.initialize();}getOwnerName(){if(typeof this.owner==="string"){return this.owner}if(this.owner instanceof ObjectBase){return this.owner.getName()}if(this.owner&&typeof this.owner.getName==="function"){return this.owner.getName()}return "UnknownOwner"}initialize(){const ownerName=this.getOwnerName();if(this.args.repeatedly&&LoggerBrowserInfra.colorsOwners[ownerName]){this.color=LoggerBrowserInfra.colorsOwners[ownerName];}else {this.color=this.getRandomColor();LoggerBrowserInfra.colorsUsed.push(this.color);}LoggerBrowserInfra.colorsOwners[ownerName]=this.color;this.defaultStyle=["color: grey;font-size:7px","display: block",`color: ${this.color}`,"color: grey","font-weight: bold","color: #607D8B","font-size: 16px;color: red;font-weight:800"];}output(...args){this.outputHandler.apply(this,args);}setOutputHandler(outputHandler){this.outputHandler=outputHandler;}printFunctionNotify(prefix,caller,output){const callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c() ${output}%c`].concat(this.defaultStyle));}printObjectEfficient(prefix,caller,params){params=Object.assign({},params);if(typeof params==="string"){this.printInLineString(prefix,caller,params);return}if(Object.keys(params).length===1){const key=Object.keys(params)[0];let value=Object.values(params)[0];if("object"===typeof value){this.printInNextLineObject(prefix,caller,key,value||{});}else if("function"===typeof value){this.printInLineFunction(prefix,caller,key,value);}else {this.printInLineElement(prefix,caller,key,value);}return}this.printMultiLineObject(prefix,caller,params);}printInLineElement(prefix,caller,key,value,notice=""){const callerName=this.getCallerName(caller),ownerName=this.getOwnerName(),format=notice.length?`%c(${prefix})-> %c%c${ownerName}%c::%c${callerName}%c() ->> [${notice}] ->> ${key}: '${value}'%c`:`%c(${prefix})-> %c%c${ownerName}%c::%c${callerName}%c() ->> ${key}: '${value}'%c`;this.output.apply(this,[format].concat(this.defaultStyle));}printInLineFunction(prefix,caller,key,fn){fn=this.getFunctionView(fn);this.printInLineElement(prefix,caller,key,fn);}printInLineString(prefix,caller,string){this.printInLineElement(prefix,caller,"(string)",string);}printInNextLineObject(prefix,caller,key,obj){const mapped=LoggerBrowserInfra.useObjectMapper(obj),callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c() ->> ${key} %c↓`].concat(this.defaultStyle));this.output(mapped);}printMultiLineObject(prefix,caller,obj){const callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c(${Object.keys(obj).join(", ")}) %c↓`].concat(this.defaultStyle));for(let key in obj){let value=obj[key];if(typeof value==="object"){const mapped=LoggerBrowserInfra.useObjectMapper(value);value=JSON.stringify(mapped,reduceCircularReferences());}else if(typeof obj[key]=="function"){value=this.getFunctionView(value);}this.output.apply(this,["%c"+key+": `"+value+"`","color: #a3a3a3"]);}}getRandomColor(){const hex="0123456789ABCDEF";let attempt=0;let similarityThreshold=.8;let lastTried="#000000";while(attempt<MAX_COLOR_ATTEMPTS){let color="#";for(let i=0;i<6;i++){color+=hex[Math.floor(Math.random()*16)];}lastTried=color;const similar=LoggerBrowserInfra.colorsUsed.some(value=>{return getHexColorDelta(color,value)>=similarityThreshold});if(!similar){return color}attempt++;if(attempt%5===0&&similarityThreshold>.6){similarityThreshold-=.05;}}return lastTried}getCallerName(caller){if("function"===typeof caller){return caller.prototype instanceof ObjectBase?"constructor":caller.name}throw new Error("Invalid caller")}getFunctionView(fn){let fReturn=UNKNOWN_CALLER_NAME;if(typeof fn!=="string"&&fn.name.length!==0){fReturn=fn.name.split(" ")[1]+"()";}return fReturn}}
108
+ const MAX_MAPPING_RECURSIVE_DEPTH=4,UNKNOWN_CALLER_NAME="anonymous function",MAX_COLOR_ATTEMPTS=25,FALLBACK_PALETTE=["#EF4444","#F59E0B","#10B981","#3B82F6","#6366F1","#EC4899","#8B5CF6","#14B8A6","#F97316","#A855F7","#22D3EE","#84CC16"];Error.stackTraceLimit=50;class LoggerBrowserInfra extends ObjectBase{static mappers=[];static mapperDepth=0;static colorsOwners={};static colorsUsed=[];defaultStyle;owner;args;color;outputHandler=console.log;static getName(){return "ZenFlux/Logging/Modules/LoggerBrowserInfra"}static reset(){LoggerBrowserInfra.mappers=[];LoggerBrowserInfra.mapperDepth=0;LoggerBrowserInfra.colorsUsed=[];LoggerBrowserInfra.colorsOwners={};}static createObjectMapper(callback){LoggerBrowserInfra.mappers.push(callback);}static useObjectMapper(obj,shouldHandleChildren=true){if(!obj||Array.isArray(obj)||"object"!==typeof obj){return obj}LoggerBrowserInfra.mapperDepth++;let result={...obj};LoggerBrowserInfra.mappers.forEach(mapper=>{result=mapper(obj)||result;});if(LoggerBrowserInfra.mapperDepth>=MAX_MAPPING_RECURSIVE_DEPTH){LoggerBrowserInfra.mapperDepth--;return result}if(shouldHandleChildren&&result){Object.entries(result).forEach(([key,value])=>{result[key]=this.useObjectMapper(value,true);});}LoggerBrowserInfra.mapperDepth--;return result}constructor(owner,args={}){super();this.args={repeatedly:false,...args};this.owner=owner;this.initialize();}getOwnerName(){if(typeof this.owner==="string"){return this.owner}if(this.owner instanceof ObjectBase){return this.owner.getName()}if(this.owner&&typeof this.owner.getName==="function"){return this.owner.getName()}return "UnknownOwner"}initialize(){const ownerName=this.getOwnerName();if(this.args.repeatedly&&LoggerBrowserInfra.colorsOwners[ownerName]){this.color=LoggerBrowserInfra.colorsOwners[ownerName];}else {this.color=this.getRandomColor();LoggerBrowserInfra.colorsUsed.push(this.color);}LoggerBrowserInfra.colorsOwners[ownerName]=this.color;this.defaultStyle=["color: grey;font-size:7px","display: block",`color: ${this.color}`,"color: grey","font-weight: bold","color: #607D8B","font-size: 16px;color: red;font-weight:800"];}output(...args){this.outputHandler.apply(this,args);}setOutputHandler(outputHandler){this.outputHandler=outputHandler;}printFunctionNotify(prefix,caller,output){const callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c() ${output}%c`].concat(this.defaultStyle));}printObjectEfficient(prefix,caller,params){params=Object.assign({},params);if(typeof params==="string"){this.printInLineString(prefix,caller,params);return}if(Object.keys(params).length===1){const key=Object.keys(params)[0];let value=Object.values(params)[0];if("object"===typeof value){this.printInNextLineObject(prefix,caller,key,value||{});}else if("function"===typeof value){this.printInLineFunction(prefix,caller,key,value);}else {this.printInLineElement(prefix,caller,key,value);}return}this.printMultiLineObject(prefix,caller,params);}printInLineElement(prefix,caller,key,value,notice=""){const callerName=this.getCallerName(caller),ownerName=this.getOwnerName(),format=notice.length?`%c(${prefix})-> %c%c${ownerName}%c::%c${callerName}%c() ->> [${notice}] ->> ${key}: '${value}'%c`:`%c(${prefix})-> %c%c${ownerName}%c::%c${callerName}%c() ->> ${key}: '${value}'%c`;this.output.apply(this,[format].concat(this.defaultStyle));}printInLineFunction(prefix,caller,key,fn){fn=this.getFunctionView(fn);this.printInLineElement(prefix,caller,key,fn);}printInLineString(prefix,caller,string){this.printInLineElement(prefix,caller,"(string)",string);}printInNextLineObject(prefix,caller,key,obj){const mapped=LoggerBrowserInfra.useObjectMapper(obj),callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c() ->> ${key} %c↓`].concat(this.defaultStyle));this.output(mapped);}printMultiLineObject(prefix,caller,obj){const callerName=this.getCallerName(caller);this.output.apply(this,[`%c(${prefix})-> %c%c${this.getOwnerName()}%c::%c${callerName}%c(${Object.keys(obj).join(", ")}) %c↓`].concat(this.defaultStyle));for(let key in obj){let value=obj[key];if(typeof value==="object"){const mapped=LoggerBrowserInfra.useObjectMapper(value);value=JSON.stringify(mapped,reduceCircularReferences());}else if(typeof obj[key]=="function"){value=this.getFunctionView(value);}this.output.apply(this,["%c"+key+": `"+value+"`","color: #a3a3a3"]);}}getRandomColor(){const hex="0123456789ABCDEF";let attempt=0;let similarityThreshold=.8;let lastTried="#000000";while(attempt<MAX_COLOR_ATTEMPTS){let color="#";for(let i=0;i<6;i++){color+=hex[Math.floor(Math.random()*16)];}lastTried=color;const similar=LoggerBrowserInfra.colorsUsed.some(value=>{return getHexColorDelta(color,value)>=similarityThreshold});if(!similar){return color}attempt++;if(attempt%5===0&&similarityThreshold>.6){similarityThreshold-=.05;}}const unusedPaletteColor=FALLBACK_PALETTE.find(paletteColor=>{return !LoggerBrowserInfra.colorsUsed.includes(paletteColor)});if(unusedPaletteColor){return unusedPaletteColor}return FALLBACK_PALETTE[LoggerBrowserInfra.colorsUsed.length%FALLBACK_PALETTE.length]||lastTried}getCallerName(caller){if("function"===typeof caller){return caller.prototype instanceof ObjectBase?"constructor":caller.name}throw new Error("Invalid caller")}getFunctionView(fn){let fReturn=UNKNOWN_CALLER_NAME;if(typeof fn!=="string"&&fn.name.length!==0){fReturn=fn.name.split(" ")[1]+"()";}return fReturn}}
109
109
 
110
110
  const DEFAULT_LOG_PREFIX=pc.white("⚪ - [LOG]"),DEFAULT_INFO_PREFIX=pc.blue("🔵 - [INFO]"),DEFAULT_DEBUG_PREFIX=pc.gray("🟤 - [DEBUG]"),DEFAULT_WARN_PREFIX=pc.yellow("🟡 - [WARN]"),DEFAULT_ERROR_PREFIX=pc.red("🔴 - [ERROR]"),DEFAULT_ADMIN_PREFIX=pc.bold("🟣 - [ADMIN]");const registeredNames={};class Logger extends LoggerBrowserInfra{static lastLogTime=Date.now();ownerName;messagePrefixes=[];config={};static getName(){return "ZenFlux/Core/Modules/Logger"}static getLogLevelString(){return getLoggerLogLevelString()}static getLogLevel(){return getLoggerLogLevel()}static isDebugEnabled(){return isLoggerDebugEnabled()}constructor(owner,options){const{repeatedly=false,skipEventBusHook}=options||{};super(owner,{repeatedly});this.config={skipEventBusHook};this.ownerName=Logger.resolveOwnerName(owner);if(registeredNames[this.ownerName]){throw new Error(`Logger for '${this.ownerName}' already exists`)}registeredNames[this.ownerName]=true;if(isLoggerDisabled()){this.disableLoggers();return}if(isLoggerPreviousSourceDisabled()){this.getPreviousSource=()=>"";}switch(getLoggerLogLevel()){case 0:this.error=()=>{};case 1:this.warn=()=>{};case 2:this.admin=()=>{};case 3:this.info=()=>{};case 4:this.log=()=>{};case 5:this.debug=()=>{};}if(!this.config.skipEventBusHook){EventBus.$.registerMultiInstances(this,[this.outputEvent]);}}addMessagePrefix(prefix){this.messagePrefixes.push(prefix);}log(caller,message,...params){this.writeLog(DEFAULT_LOG_PREFIX,caller,message,...params);}info(caller,message,...params){this.writeLog(DEFAULT_INFO_PREFIX,caller,message,...params);}debug(caller,message,...params){this.writeLog(DEFAULT_DEBUG_PREFIX,caller,message,...params);}warn(caller,message,...params){this.writeLog(DEFAULT_WARN_PREFIX,caller,message,...params);}error(caller,message,...params){this.writeLog(DEFAULT_ERROR_PREFIX,caller,message,...params);}admin(caller,message,...params){this.writeLog(DEFAULT_ADMIN_PREFIX,caller,message,...params);}startsEmpty(caller){this.printFunctionNotify("▶",caller,"");}startsWith(caller,params){this.printObjectEfficient("▶",caller,params);}dump(caller,params={},notice=""){for(const key in params){if(typeof params[key]==="object"){params[key]=JSON.stringify(LoggerBrowserInfra.useObjectMapper(params[key]),reduceCircularReferences());}this.printInLineElement("dp",caller,key,params[key],notice);}}drop(caller,according,data){for(const key in according){this.printInLineElement("dr",caller,key,according[key],"corresponding");}this.output(data);}throw(caller,output,name="null",params={}){this.printFunctionNotify("tw",caller,output);if(params){this.printInNextLineObject("tw",caller,name,params);}throw new Error().stack}beep(){console.log("\x07");}clone(){return Object.assign(Object.create(Object.getPrototypeOf(this)),this)}outputEvent(_prefix,_timeDiff,_source,_messagePrefix,_message,_params){}static resolveOwnerName(owner){if(typeof owner==="string"){return owner}if(owner instanceof ObjectBase){return owner.getName()}if(owner&&typeof owner.getName==="function"){return owner.getName()}return "UnknownOwner"}disableLoggers(){this.error=()=>{};this.warn=()=>{};this.admin=()=>{};this.info=()=>{};this.log=()=>{};this.debug=()=>{};}getStackTrace(){const stackTrace=(new Error().stack||"").split("\n");const stackLines=stackTrace.slice(1);const stackRegex=/ at (.+?) \((.+?)\)/;const result=[];for(const line of stackLines){const match=line.match(stackRegex);if(match){const[,context,file]=match;const parsedLine={context,file};if(line.startsWith("new")){parsedLine.isNew=true;parsedLine.object=context.split(" ")[1];}else if(context!=="Object.<anonymous>"){parsedLine.object=context;}result.push(parsedLine);}}return result}getPreviousSource(){const stack=this.getStackTrace().filter(line=>line.file.includes("/src/")).filter(line=>!line.file.includes("logger.ts")).filter(line=>!line.file.includes("debugger.ts")).filter(line=>!line.file.includes("/node_modules/"));let previousSource="";const previousCaller=stack[1]?.object?.split(".");if(previousCaller?.length>1){const previousCallerName=previousCaller[0],previousCallerMethod=previousCaller[1];previousSource=`${previousCallerName}::${previousCallerMethod}]`+"[";}return previousSource}writeLog(prefix,caller,message,...params){const source=this.getPreviousSource()+pc.white(`${this.ownerName}::${this.getCallerName(caller)}`);let messagePrefix="";if(this.messagePrefixes.length){messagePrefix=`[${this.messagePrefixes.join("][")}]`;}const timeDiff=(Date.now()-Logger.lastLogTime).toString().padStart(4,"0");this.outputEvent(prefix,timeDiff,source,messagePrefix,message,params);const output=`${prefix}[+${timeDiff}ms][${source}]${messagePrefix}: ${message}`;console.log(output,...params);Logger.lastLogTime=Date.now();}}
111
111
 
112
112
  var _package = {
113
113
  "name": "@zenflux/core",
114
- "version": "0.1.9",
114
+ "version": "0.1.11",
115
115
  "types": "dist/zenflux-core.d.ts",
116
116
  "type": "module",
117
117
  "files": [
@@ -157,7 +157,7 @@ var _package = {
157
157
  }
158
158
  };
159
159
  const name = "@zenflux/core";
160
- const version = "0.1.9";
160
+ const version = "0.1.11";
161
161
  const types = "dist/zenflux-core.d.ts";
162
162
  const type = "module";
163
163
  const files = ["dist","src","types"];
package/package.json CHANGED
@@ -1,11 +1,10 @@
1
1
  {
2
2
  "name": "@zenflux/core",
3
- "version": "0.1.11",
3
+ "version": "0.1.13",
4
4
  "types": "dist/zenflux-core.d.ts",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist",
8
- "src",
9
8
  "types"
10
9
  ],
11
10
  "scripts": {
@@ -33,7 +32,7 @@
33
32
  },
34
33
  "devDependencies": {
35
34
  "@jest/globals": "^29.7.0",
36
- "@zenflux/cli": "0.1.33"
35
+ "@zenflux/cli": "0.1.35"
37
36
  },
38
37
  "publishConfig": {
39
38
  "access": "public"
@@ -42,6 +41,6 @@
42
41
  "fastmcp": "^3.23.1",
43
42
  "zod": "^4.1.12",
44
43
  "picocolors": "^1.0.0",
45
- "@zenflux/utils": "0.1.15"
44
+ "@zenflux/utils": "0.1.17"
46
45
  }
47
46
  }
@@ -1,96 +0,0 @@
1
- /**
2
- * The `ControllerBase` class is an abstract base class responsible for managing commands and providing a structure
3
- * for controllers or command spaces.
4
- *
5
- * @author Leonid Vinikov <leonidvinikov@gmail.com>
6
- */
7
- import { ObjectBase } from "./object-base";
8
-
9
- import * as managers from "../managers/export";
10
-
11
- import type { CommandPublic } from "../command-bases/command-public";
12
- import type { CommandRestful } from "../command-bases/command-restful";
13
- import type { CommandInternal } from "../command-bases/command-internal";
14
-
15
- // noinspection TypeScriptAbstractClassConstructorCanBeMadeProtected
16
-
17
- export abstract class ControllerBase extends ObjectBase {
18
- private commands: { [ key: string ]: typeof CommandPublic };
19
- private restful: { [ key: string ]: typeof CommandRestful };
20
- private internal: { [ key: string ]: typeof CommandInternal };
21
-
22
- public static getName() {
23
- return "ZenFlux/Core/ControllerBase";
24
- }
25
-
26
- /**
27
- * Constructor for `ControllerBase` instances.
28
- * Initializes the base class and invokes the `initialize()` method.
29
- */
30
- public constructor() {
31
- super();
32
-
33
- // Initialize the controller
34
- this.initialize();
35
- }
36
-
37
- /**
38
- * Initializes the controller by calling the `register()` method and optionally the `setupHooks()` method.
39
- */
40
- protected initialize() {
41
- // Register commands and command types
42
- this.register();
43
-
44
- // Optionally, set up hooks if the `setupHooks()` method is defined in derived classes
45
- this.setupHooks && this.setupHooks();
46
- }
47
-
48
- /**
49
- * Registers commands and command types by calling manager functions.
50
- */
51
- protected register() {
52
- // Register public commands
53
- this.commands = managers.commands.register( this.getCommands(), this ) as {
54
- [ key: string ]: typeof CommandPublic
55
- };
56
-
57
- // Register RESTful commands
58
- this.restful = managers.restful.register( this.getRestful(), this ) as {
59
- [ key: string ]: typeof CommandRestful
60
- };
61
-
62
- // Register internal commands
63
- this.internal = managers.internal.register( this.getInternal(), this ) as {
64
- [ key: string ]: typeof CommandInternal
65
- };
66
- }
67
-
68
- /**
69
- * Retrieve the public commands associated with this controller.
70
- * Derived classes can override this method to specify their own commands.
71
- */
72
- protected getCommands(): { [ key: string ]: typeof CommandPublic } {
73
- return {};
74
- }
75
-
76
- /**
77
- * Retrieve the RESTful commands associated with this controller.
78
- * Derived classes can override this method to specify their own RESTful commands.
79
- */
80
- protected getRestful(): { [ key: string ]: typeof CommandRestful } {
81
- return {};
82
- }
83
-
84
- /**
85
- * Retrieve the internal commands associated with this controller.
86
- * Derived classes can override this method to specify their own internal commands.
87
- */
88
- protected getInternal(): { [ key: string ]: typeof CommandInternal } {
89
- return {};
90
- }
91
-
92
- /**
93
- * A hook method that can be optionally overridden in derived classes to set up hooks or event listeners.
94
- */
95
- protected setupHooks?() {}
96
- }
@@ -1,6 +0,0 @@
1
- /**
2
- * @author Leonid Vinikov <leonidvinikov@gmail.com>
3
- */
4
-
5
- export { ControllerBase } from "./controller-base";
6
- export { ObjectBase } from "./object-base";
@@ -1,32 +0,0 @@
1
- import { ObjectBase } from "@zenflux/core/src/bases/object-base";
2
-
3
- import { Logger } from "@zenflux/core/src/modules/logger";
4
-
5
- export abstract class InitializeBase extends ObjectBase {
6
- protected logger: Logger;
7
-
8
- protected constructor( shouldInitialize = true ) {
9
- super();
10
-
11
- this.logger = new Logger( this );
12
-
13
- if ( this.initialize && shouldInitialize ) {
14
- this.initialize();
15
- }
16
- }
17
-
18
- protected initialize?(): void;
19
-
20
- // TODO: Find better place for this
21
- protected debounce<T extends ( ...args: any[] ) => any>( func: T, delay: number ) {
22
- let timeoutId: ReturnType<typeof setTimeout>;
23
-
24
- return ( ...args: Parameters<T> ) => {
25
- clearTimeout( timeoutId );
26
-
27
- timeoutId = setTimeout( () => {
28
- func.apply( this, args );
29
- }, delay );
30
- };
31
- }
32
- }
@@ -1,55 +0,0 @@
1
- import { ForceMethodBase } from "../errors";
2
-
3
- export abstract class ObjectBase {
4
- private readonly id: string;
5
- private readonly name: string = "__UNDEFINED_NAME__";
6
-
7
- protected constructor() {
8
- this.name = this.getName();
9
-
10
- const timestamp = performance.now() * 1000000;
11
- const random1 = BigInt( Math.floor( Math.random() * 1000000 ) );
12
- const random2 = BigInt( Math.floor( Math.random() * 1000000 ) );
13
-
14
- this.id = `${ timestamp }${ random1 }${ random2 }`;
15
- }
16
-
17
- public static getName(): string {
18
- throw new ForceMethodBase( this.name, "getName" );
19
- }
20
-
21
- public static getSourcePath(): string {
22
- throw new ForceMethodBase( this.name, "getSourcePath" );
23
- }
24
-
25
- public getName(): string {
26
- return ( this.constructor as typeof ObjectBase ).getName();
27
- }
28
-
29
- public getUniqueId(): string {
30
- return this.id;
31
- }
32
-
33
- public getInitialName(): string {
34
- return this.name;
35
- }
36
-
37
- public getHierarchyNames(): string[] {
38
- const classNames = [];
39
- let obj = Object.getPrototypeOf( this );
40
- let className: string;
41
-
42
- while ( ( className = obj.getName() ) !== "Object" ) {
43
- classNames.push( className );
44
- obj = Object.getPrototypeOf( obj );
45
-
46
- if ( obj.constructor === ObjectBase ) {
47
- break;
48
- }
49
- }
50
-
51
- return classNames;
52
- }
53
- }
54
-
55
- export default ObjectBase;
@@ -1,152 +0,0 @@
1
- /**
2
- * The `Http` class provides a simple wrapper for the Fetch API.
3
- *
4
- * @author Leonid Vinikov <leonidvinikov@gmail.com>
5
- */
6
- import { E_HTTP_METHOD_TYPE } from "../interfaces";
7
-
8
- import { ObjectBase } from "../bases/object-base";
9
-
10
- import type {
11
- ILogger,
12
- TErrorHandlerCallbackType,
13
- TResponseFilterCallbackType,
14
- TResponseHandlerCallbackType
15
- } from "../interfaces";
16
-
17
- // noinspection ExceptionCaughtLocallyJS
18
-
19
- export class Http extends ObjectBase {
20
- private readonly logger: ILogger;
21
- private readonly apiBaseUrl: string;
22
- private readonly requestInit: RequestInit;
23
-
24
- private errorHandler?: TErrorHandlerCallbackType = undefined;
25
- private responseFilter?: TResponseFilterCallbackType = undefined;
26
- private responseHandler?: TResponseHandlerCallbackType = undefined;
27
-
28
- public static getName(): string {
29
- return "ZenFlux/Core/Clients/Http";
30
- }
31
-
32
- /**
33
- * Initializes the base class and sets up configuration parameters.
34
- */
35
- public constructor( apiBaseUrl = "http://localhost", requestInit: RequestInit = { "credentials": "include" } ) {
36
- super();
37
-
38
- this.logger = new zCore.classes.Logger( Http );
39
-
40
- this.logger.startsWith( this.constructor, { apiBaseUrl } );
41
-
42
- this.apiBaseUrl = apiBaseUrl + "/";
43
- this.requestInit = requestInit;
44
- }
45
-
46
- /**
47
- * Fetches data from the specified path using the given HTTP method and optional request body.
48
- */
49
- public async fetch( path: string, method: E_HTTP_METHOD_TYPE, body: any = {} ) {
50
- this.logger.startsWith( this.constructor, { path, method, body } );
51
-
52
- const params = Object.assign( {}, this.requestInit );
53
- const headers = {};
54
-
55
- if ( method === E_HTTP_METHOD_TYPE.GET ) {
56
- Object.assign( params, { headers } );
57
- } else {
58
- Object.assign( headers, { "Content-Type": "application/json" } );
59
- Object.assign( params, {
60
- method,
61
- headers: headers,
62
- body: JSON.stringify( body ),
63
- } );
64
- }
65
-
66
- const fetchPromise = globalThis.fetch( this.apiBaseUrl + path, params );
67
-
68
- let response = await fetchPromise;
69
-
70
- if ( ! response ) {
71
- return false;
72
- }
73
-
74
- let data = undefined;
75
-
76
- try {
77
- if ( ! response.ok ) {
78
- throw new Error( response.statusText );
79
- }
80
-
81
- let responseText = await response.text();
82
-
83
- responseText = this.applyResponseFilter( responseText );
84
-
85
- // TODO: Currently support JSON and plain text.
86
- if ( response.headers?.get( "Content-Type" )?.includes( "application/json" ) ) {
87
- data = JSON.parse( responseText );
88
- } else {
89
- data = responseText;
90
- }
91
-
92
- if ( this.applyResponseHandler( data ) ) {
93
- return false;
94
- }
95
- } catch ( e ) {
96
- if ( this.applyErrorHandler( e ) ) {
97
- return false;
98
- }
99
-
100
- await Promise.reject( e );
101
- }
102
-
103
- this.logger.drop( this.fetch, { path }, data );
104
-
105
- return data;
106
- }
107
-
108
- /**
109
- * Sets the error handler callback for handling errors during fetch requests.
110
- */
111
- public setErrorHandler( callback: TErrorHandlerCallbackType ) {
112
- if ( this.errorHandler ) {
113
- throw new Error( "Error handler already set." );
114
- }
115
-
116
- this.errorHandler = callback;
117
- }
118
-
119
- /**
120
- * Sets the response filter callback for filtering the response text.
121
- */
122
- public setResponseFilter( callback: TResponseFilterCallbackType ) {
123
- if ( this.responseFilter ) {
124
- throw new Error( "Response filter already set." );
125
- }
126
-
127
- this.responseFilter = callback;
128
- }
129
-
130
- /**
131
- * Sets the response handler callback for handling the response data.
132
- */
133
- public setResponseHandler( callback: TResponseHandlerCallbackType ) {
134
- if ( this.responseHandler ) {
135
- throw new Error( "Response handler already set." );
136
- }
137
-
138
- this.responseHandler = callback;
139
- }
140
-
141
- private applyErrorHandler( error: any ) {
142
- return !! this.errorHandler && this.errorHandler( error );
143
- }
144
-
145
- private applyResponseFilter( text: string ) {
146
- return ( this.responseFilter && this.responseFilter( text ) ) || text;
147
- }
148
-
149
- private applyResponseHandler( text: string ) {
150
- return !! this.responseHandler && this.responseHandler( text );
151
- }
152
- }
@@ -1,82 +0,0 @@
1
- /**
2
- * @author Leonid Vinikov <leonidvinikov@gmail.com>
3
- * @description Base for all commands, they are all will be managed by the `Commands` managers.
4
- *
5
- * TODO
6
- * - Add validateArgs method or find something better.
7
- */
8
- import { ObjectBase } from "../bases";
9
- import { ControllerAlreadySet, ForceMethodImplementation } from "../errors";
10
-
11
- import type { ControllerBase } from "../bases";
12
-
13
- import type { ICommandArgsInterface, ICommandOptionsInterface, ILogger } from "../interfaces";
14
-
15
- export abstract class CommandBase extends ObjectBase {
16
- private static controller: ControllerBase;
17
-
18
- protected args: ICommandArgsInterface = {};
19
- protected options: ICommandOptionsInterface = {};
20
-
21
- private readonly logger: ILogger;
22
-
23
- public static getName() {
24
- return "ZenFlux/Core/CommandBases/CommandBase";
25
- }
26
-
27
- public static setController( controller: ControllerBase ) {
28
- if ( this.controller ) {
29
- throw new ControllerAlreadySet( this.controller );
30
- }
31
-
32
- this.controller = controller;
33
- }
34
-
35
- public static getController() {
36
- return this.controller;
37
- }
38
-
39
- public constructor( args: ICommandArgsInterface = {}, options = {} ) {
40
- super();
41
-
42
- const type = ( this.constructor as typeof CommandBase );
43
-
44
- this.logger = new zCore.classes.Logger( type, {
45
- // Happens or occurs many times, often in a similar or identical manner.
46
- repeatedly: true,
47
- } );
48
-
49
- this.logger.startsWith( this.constructor, { args, options } );
50
-
51
- this.initialize( args, options );
52
- }
53
-
54
- protected initialize( args: ICommandArgsInterface, options: ICommandOptionsInterface ) {
55
- this.args = args;
56
- this.options = options;
57
- }
58
-
59
- /**
60
- * TODO: Maybe abstract, currently not sure about parameters initialization.
61
- */
62
- protected apply( args = this.args, options = this.options ): any {// eslint-disable-line @typescript-eslint/no-unused-vars
63
- throw new ForceMethodImplementation( this, "apply" );
64
- }
65
-
66
- protected onBeforeApply?():void;
67
- protected onAfterApply?():void;
68
-
69
- public async run() {
70
- return this.runInternal();
71
- }
72
-
73
- private async runInternal() {
74
- this.onBeforeApply && this.onBeforeApply();
75
-
76
- const result = await this.apply( this.args, this.options );
77
-
78
- this.onAfterApply && this.onAfterApply();
79
-
80
- return result;
81
- }
82
- }
@@ -1,11 +0,0 @@
1
- /**
2
- * @author Leonid Vinikov <leonidvinikov@gmail.com>
3
- * @description CommandInternal, is used when part of the logic needed to be in the command but not represent a user action.
4
- */
5
- import { CommandBase } from "./command-base";
6
-
7
- export class CommandInternal extends CommandBase {
8
- public static getName() {
9
- return "ZenFlux/Core/CommandBases/CommandInternal";
10
- }
11
- }
@@ -1,12 +0,0 @@
1
- /**
2
- * @author Leonid Vinikov <leonidvinikov@gmail.com>
3
- * @description CommandPublic represents a USER action, every class which inherit from this class will USER action.
4
- * */
5
- import { CommandBase } from "./command-base";
6
-
7
- export class CommandPublic extends CommandBase {
8
- public static getName() {
9
- return "ZenFlux/Core/CommandBases/CommandPublic";
10
- }
11
- }
12
-