@zenflux/core 0.1.29 → 0.1.31
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.
- package/dist/.tsconfig.probe.tsbuildinfo +1 -0
- package/dist/src/modules/logger/implementation.d.ts +2 -1
- package/dist/zenflux-core.cjs +38 -38
- package/dist/zenflux-core.mjs +38 -38
- package/package.json +2 -2
- package/src/bases/cache-base.ts +64 -0
- package/src/bases/controller-base.ts +96 -0
- package/src/bases/index.ts +9 -0
- package/src/bases/initialize-base.ts +32 -0
- package/src/bases/object-base.ts +55 -0
- package/src/bases/singleton-base.ts +18 -0
- package/src/clients/http.ts +152 -0
- package/src/command-bases/command-base.ts +80 -0
- package/src/command-bases/command-internal.ts +11 -0
- package/src/command-bases/command-public.ts +12 -0
- package/src/command-bases/command-restful.ts +55 -0
- package/src/command-bases/index.ts +8 -0
- package/src/errors/command-already-registered.ts +13 -0
- package/src/errors/command-not-found.ts +12 -0
- package/src/errors/controller-already-registered.ts +13 -0
- package/src/errors/controller-already-set.ts +13 -0
- package/src/errors/error-with-metadata.ts +29 -0
- package/src/errors/force-method-implementation.ts +15 -0
- package/src/errors/index-public.ts +1 -0
- package/src/errors/index.ts +10 -0
- package/src/exports-index.ts +15 -0
- package/src/exports.ts +55 -0
- package/src/index.ts +18 -0
- package/src/interfaces/commands.ts +17 -0
- package/src/interfaces/config.ts +23 -0
- package/src/interfaces/index.ts +8 -0
- package/src/interfaces/logger.ts +19 -0
- package/src/interfaces/restful.ts +23 -0
- package/src/managers/commands.ts +269 -0
- package/src/managers/controllers.ts +40 -0
- package/src/managers/export.ts +30 -0
- package/src/managers/index.ts +8 -0
- package/src/managers/internal.ts +11 -0
- package/src/managers/restful.ts +117 -0
- package/src/modules/debugger.ts +86 -0
- package/src/modules/event-bus/event-bus.ts +238 -0
- package/src/modules/export.ts +6 -0
- package/src/modules/logger/config.ts +66 -0
- package/src/modules/logger/create-logger.ts +38 -0
- package/src/modules/logger/implementation.ts +371 -0
- package/src/modules/logger/index.ts +3 -0
- package/src/modules/logger/logger-browser-infra.ts +364 -0
- package/src/modules/logger/types/picocolors.d.ts +15 -0
- package/src/modules/logger/utils/index.ts +3 -0
- package/src/modules/logger/utils/object.ts +19 -0
- package/src/modules/logger/utils/rgb.ts +34 -0
- package/src/modules/mcp-server/mcp-server.ts +139 -0
- package/src/modules/mcp-server/mcp-service.ts +80 -0
- package/src/modules/service/service-base.ts +55 -0
- package/src/modules/service/service-locator.ts +205 -0
- package/src/modules/service/service-with-dependencies-base.ts +51 -0
package/dist/zenflux-core.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Bundled with love using the help of @zenflux/cli toolkit v0.1.43
|
|
3
|
-
* Bundle name: @zenflux/core fileName: 'zenflux-core', built at
|
|
3
|
+
* Bundle name: @zenflux/core fileName: 'zenflux-core', built at Sat Sep 12 2026 13:50:48 GMT+0300 (Israel Daylight Time)
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
'use strict';
|
|
@@ -40,11 +40,41 @@ class ControllerAlreadySet extends Error{constructor(controller){super(`Controll
|
|
|
40
40
|
|
|
41
41
|
class ForceMethodBase extends Error{constructor(className,methodName){super(`ForceMethod implementation: at '${className}' method: '${methodName}'`);}}class ForceMethodImplementation extends Error{constructor(context,methodName){super(`ForceMethod implementation: at '${"string"===typeof context?context:context.getName()}' method: '${methodName}'`);}}
|
|
42
42
|
|
|
43
|
-
class ErrorWithMetadata extends Error{metadata;constructor(message,metadata=null){super(message);this.metadata=metadata;const metaView=null!==metadata?formatMetadata(metadata):null;this.message=null!==metaView?`${message} - Metadata: ${metaView}`:message;Object.setPrototypeOf(this,new.target.prototype);}}function formatMetadata(metadata){try{if(metadata===null||metadata===undefined){return String(metadata)}if(typeof metadata==="object"){return JSON.stringify(metadata)}return String(metadata)}catch
|
|
43
|
+
class ErrorWithMetadata extends Error{metadata;constructor(message,metadata=null){super(message);this.metadata=metadata;const metaView=null!==metadata?formatMetadata(metadata):null;this.message=null!==metaView?`${message} - Metadata: ${metaView}`:message;Object.setPrototypeOf(this,new.target.prototype);}}function formatMetadata(metadata){try{if(metadata===null||metadata===undefined){return String(metadata)}if(typeof metadata==="object"){return JSON.stringify(metadata)}return String(metadata)}catch{return "[unserializable metadata]"}}
|
|
44
44
|
|
|
45
45
|
class ObjectBase{id;name="__UNDEFINED_NAME__";constructor(){this.name=this.getName();const timestamp=performance.now()*1e6;const random1=BigInt(Math.floor(Math.random()*1e6));const random2=BigInt(Math.floor(Math.random()*1e6));this.id=`${timestamp}${random1}${random2}`;}static getName(){throw new ForceMethodBase(this.name,"getName")}static getSourcePath(){throw new ForceMethodBase(this.name,"getSourcePath")}getName(){return this.constructor.getName()}getUniqueId(){return this.id}getInitialName(){return this.name}getHierarchyNames(){const classNames=[];let obj=Object.getPrototypeOf(this);let className;while((className=obj.getName())!=="Object"){classNames.push(className);obj=Object.getPrototypeOf(obj);if(obj.constructor===ObjectBase){break}}return classNames}}
|
|
46
46
|
|
|
47
|
-
|
|
47
|
+
var commonjsGlobal=typeof globalThis!=="undefined"?globalThis:typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x["default"]:x}function getDefaultExportFromNamespaceIfPresent(n){return n&&Object.prototype.hasOwnProperty.call(n,"default")?n["default"]:n}function getDefaultExportFromNamespaceIfNotNamed(n){return n&&Object.prototype.hasOwnProperty.call(n,"default")&&Object.keys(n).length===1?n["default"]:n}function getAugmentedNamespace(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var f=n.default;if(typeof f=="function"){var a=function a(){var isInstance=false;try{isInstance=this instanceof a;}catch(e){}if(isInstance){return Reflect.construct(f,arguments,this.constructor)}return f.apply(this,arguments)};a.prototype=f.prototype;}else a={};Object.defineProperty(a,"__esModule",{value:true});Object.keys(n).forEach(function(k){var d=Object.getOwnPropertyDescriptor(n,k);Object.defineProperty(a,k,d.get?d:{enumerable:true,get:function(){return n[k]}});});return a}
|
|
48
|
+
|
|
49
|
+
var picocolors$1={exports:{}};
|
|
50
|
+
|
|
51
|
+
var picocolors=picocolors$1.exports;var hasRequiredPicocolors;function requirePicocolors(){if(hasRequiredPicocolors)return picocolors$1.exports;hasRequiredPicocolors=1;let p=process||{},argv=p.argv||[],env=p.env||{};let isColorSupported=!(!!env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p.platform==="win32"||(p.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI);let formatter=(open,close,replace=open)=>input=>{let string=""+input,index=string.indexOf(close,open.length);return ~index?open+replaceClose(string,close,replace,index)+close:open+string+close};let replaceClose=(string,close,replace,index)=>{let result="",cursor=0;do{result+=string.substring(cursor,index)+replace;cursor=index+close.length;index=string.indexOf(close,cursor);}while(~index)return result+string.substring(cursor)};let createColors=(enabled=isColorSupported)=>{let f=enabled?formatter:()=>String;return {isColorSupported:enabled,reset:f("\x1b[0m","\x1b[0m"),bold:f("\x1b[1m","\x1b[22m","\x1b[22m\x1b[1m"),dim:f("\x1b[2m","\x1b[22m","\x1b[22m\x1b[2m"),italic:f("\x1b[3m","\x1b[23m"),underline:f("\x1b[4m","\x1b[24m"),inverse:f("\x1b[7m","\x1b[27m"),hidden:f("\x1b[8m","\x1b[28m"),strikethrough:f("\x1b[9m","\x1b[29m"),black:f("\x1b[30m","\x1b[39m"),red:f("\x1b[31m","\x1b[39m"),green:f("\x1b[32m","\x1b[39m"),yellow:f("\x1b[33m","\x1b[39m"),blue:f("\x1b[34m","\x1b[39m"),magenta:f("\x1b[35m","\x1b[39m"),cyan:f("\x1b[36m","\x1b[39m"),white:f("\x1b[37m","\x1b[39m"),gray:f("\x1b[90m","\x1b[39m"),bgBlack:f("\x1b[40m","\x1b[49m"),bgRed:f("\x1b[41m","\x1b[49m"),bgGreen:f("\x1b[42m","\x1b[49m"),bgYellow:f("\x1b[43m","\x1b[49m"),bgBlue:f("\x1b[44m","\x1b[49m"),bgMagenta:f("\x1b[45m","\x1b[49m"),bgCyan:f("\x1b[46m","\x1b[49m"),bgWhite:f("\x1b[47m","\x1b[49m"),blackBright:f("\x1b[90m","\x1b[39m"),redBright:f("\x1b[91m","\x1b[39m"),greenBright:f("\x1b[92m","\x1b[39m"),yellowBright:f("\x1b[93m","\x1b[39m"),blueBright:f("\x1b[94m","\x1b[39m"),magentaBright:f("\x1b[95m","\x1b[39m"),cyanBright:f("\x1b[96m","\x1b[39m"),whiteBright:f("\x1b[97m","\x1b[39m"),bgBlackBright:f("\x1b[100m","\x1b[49m"),bgRedBright:f("\x1b[101m","\x1b[49m"),bgGreenBright:f("\x1b[102m","\x1b[49m"),bgYellowBright:f("\x1b[103m","\x1b[49m"),bgBlueBright:f("\x1b[104m","\x1b[49m"),bgMagentaBright:f("\x1b[105m","\x1b[49m"),bgCyanBright:f("\x1b[106m","\x1b[49m"),bgWhiteBright:f("\x1b[107m","\x1b[49m")}};picocolors$1.exports=createColors();picocolors$1.exports.createColors=createColors;return picocolors$1.exports}
|
|
52
|
+
|
|
53
|
+
var picocolorsExports=requirePicocolors();var pc = getDefaultExportFromCjs(picocolorsExports);
|
|
54
|
+
|
|
55
|
+
const DEFAULT_LOG_LEVEL="5";function getEnvVar(key){if(typeof process!=="undefined"&&process?.env){return process.env[key]??process.env[`VITE_${key}`]}if(typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('zenflux-core.cjs', document.baseURI).href)) })!=="undefined"&&undefined){const env=undefined;return env[key]??env[`VITE_${key}`]}return undefined}function getLoggerDefaultLevel(){return DEFAULT_LOG_LEVEL}function getLoggerLogLevel(){const raw=getEnvVar("LOGGER_LOG_LEVEL");return parseInt(raw??DEFAULT_LOG_LEVEL,10)}function getLoggerTimeFormat(){return (getEnvVar("LOGGER_TIME_FORMAT")||"").trim()}function getLoggerLogLevelString(){switch(getLoggerLogLevel()){case 0:return "NONE";case 1:return "ERROR";case 2:return "WARN";case 3:return "ADMIN";case 4:return "INFO";case 5:return "LOG";case 6:return "DEBUG";default:return "UNKNOWN"}}function isLoggerDebugEnabled(){return getLoggerLogLevel()>=6}function isLoggerDisabled(){return getEnvVar("LOGGER_DISABLED")==="true"}function isLoggerPreviousSourceDisabled(){return getEnvVar("LOGGER_LOG_PREVIOUS_CALLER_SOURCE_DISABLED")==="true"}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Reduce circular references.
|
|
59
|
+
*
|
|
60
|
+
* @copyright https://stackoverflow.com/a/53731154
|
|
61
|
+
*/const reduceCircularReferences=()=>{const seen=new WeakSet;return (key,value)=>{if(typeof value==="object"&&value!==null){if(seen.has(value)){return}seen.add(value);}return value}};
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Function hexColorDelta() : Return color difference in ratio decimal point.
|
|
65
|
+
*
|
|
66
|
+
* @copyright http://jsfiddle.net/96sME/
|
|
67
|
+
*/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};
|
|
68
|
+
|
|
69
|
+
const MAX_MAPPING_RECURSIVE_DEPTH=4,UNKNOWN_CALLER_NAME="anonymous function";Error.stackTraceLimit=50;class LoggerBrowserInfra extends ObjectBase{static mappers=[];static mapperDepth=0;static colorsOwners={};static colorsUsed=[];static outputSubscribers=new Set;defaultStyle;owner;args;color;outputHandler=console.log;pendingOutputMetadata;static getName(){return "ZenFlux/Logging/Modules/LoggerBrowserInfra"}static reset(){LoggerBrowserInfra.mappers=[];LoggerBrowserInfra.mapperDepth=0;LoggerBrowserInfra.colorsUsed=[];LoggerBrowserInfra.colorsOwners={};LoggerBrowserInfra.outputSubscribers.clear();}static attachOutputSubscriber(subscriber){LoggerBrowserInfra.outputSubscribers.add(subscriber);return ()=>{LoggerBrowserInfra.outputSubscribers.delete(subscriber);}}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.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);if(LoggerBrowserInfra.outputSubscribers.size===0){return}const event={logger:this,namespace:this.getOwnerName(),args,metadata:this.pendingOutputMetadata};LoggerBrowserInfra.outputSubscribers.forEach(subscriber=>{try{subscriber(event);}catch(error){console.error("[ZenFlux][Logger] output subscriber failed",error);}});}setOutputHandler(outputHandler){this.outputHandler=outputHandler;}runWithOutputMetadata(metadata,callback){const previous=this.pendingOutputMetadata;this.pendingOutputMetadata=metadata;try{return callback()}finally{this.pendingOutputMetadata=previous;}}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 color="#";for(let i=0;i<6;i++){color+=hex[Math.floor(Math.random()*16)];}return color}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}}
|
|
70
|
+
|
|
71
|
+
let SimpleEventEmitter=class SimpleEventEmitter{listeners=new Map;on(event,callback){if(!this.listeners.has(event)){this.listeners.set(event,new Set);}this.listeners.get(event).add(callback);}off(event,callback){this.listeners.get(event)?.delete(callback);}emit(event,...args){const callbacks=this.listeners.get(event);if(!callbacks||callbacks.size===0){return false}callbacks.forEach(cb=>cb(...args));return true}removeAllListeners(event){this.listeners.delete(event);}eventNames(){return Array.from(this.listeners.keys())}};class EventBus extends ObjectBase{static instance=null;objects=new Map;eventEmitter=new SimpleEventEmitter;lastEmittedEvents=new Map;static getName(){return "ZenFlux/Core/Modules/EventBus"}static getInstance(){if(!EventBus.instance){EventBus.instance=new EventBus;}return EventBus.instance}static get $(){return EventBus.getInstance()}getObjectNames(){return Array.from(this.objects.keys())}getEventNames(){this.eventEmitter.eventNames();}getEventName(objectName,methodName){return `${objectName}::${methodName}`}on(objectName,methodName,callback){if(!this.objects.has(objectName)){throw new Error(`Object ${objectName} is not registered`)}this.eventEmitter.on(this.getEventName(objectName,methodName),callback);}onCalledBeforeDoInvoke(objectName,methodName,callback){this.on(objectName,methodName,callback);if(this.objects.has(objectName)){const objectEntry=this.objects.get(objectName);if(objectEntry){const method=objectEntry.methods.find(method=>method.name===methodName);if(method&&this.lastEmittedEvents.has(this.getEventName(objectName,methodName))){callback(...this.lastEmittedEvents.get(this.getEventName(objectName,methodName)));}}}}off(objectName,methodName,callback){this.eventEmitter.off(this.getEventName(objectName,methodName),callback);}register(object,methods){if(this.objects.has(object.getName())){throw new Error(`Error in: '${this.getName()}', object: '${object.getName()}' is already registered`)}this.objects.set(object.getName(),{object,methods});this.hook(object,methods);}registerMultiInstances(object,methods){const objectName=object.getName();if(this.objects.has(objectName)){const existingEntry=this.objects.get(objectName);if(Array.isArray(existingEntry.object)){existingEntry.object.push(object);}else {existingEntry.object=[existingEntry.object,object];}}else {this.objects.set(objectName,{object,methods});}this.hook(object,methods);}unregister(objectName){const entry=this.objects.get(objectName);if(!entry){return false}if(Array.isArray(entry.object)){entry.object.forEach(obj=>{this.unhookObject(obj,entry.methods);});}else {this.unhookObject(entry.object,entry.methods);}this.objects.delete(objectName);}unhookObject(object,methods){methods.forEach(method=>{this.ensureFunction(object,method);this.eventEmitter.removeAllListeners(this.getEventName(object.getName(),method.name));object[method.name]=method;});}unhook(entry){if(Array.isArray(entry.object)){entry.object.forEach(obj=>{this.unhookObject(obj,entry.methods);});}else {this.unhookObject(entry.object,entry.methods);}}emit(object,method,...args){const eventName=this.getEventName(object.getName(),method.name);this.lastEmittedEvents.set(eventName,args);return this.eventEmitter.emit(eventName,...args)}hook(object,methods){methods.forEach(method=>{this.ensureFunction(object,method);const originalMethod=method;const eventBusHook=async(...args)=>{const result=await originalMethod.apply(object,args);this.emit(object,method,...args);return result};object[method.name]=new Proxy(eventBusHook,{get(target,prop){if(prop==="name"){return method.name}return target[prop]}});});}ensureFunction(object,method){if("function"!==typeof method){throw new Error(`Method ${method} is not a function on ${object.getName()}`)}}}
|
|
72
|
+
|
|
73
|
+
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 LEVEL_LABELS={log:"LOG",info:"INFO",debug:"DEBUG",warn:"WARN",error:"ERROR",admin:"ADMIN"};const registeredNames={};class Logger extends LoggerBrowserInfra{static lastLogTime=Date.now();static timestampFormat=getLoggerTimeFormat();ownerName;messagePrefixes=[];config={};static setTimestampFormat(format){Logger.timestampFormat=(format||"").trim();}static getTimestampFormat(){return Logger.timestampFormat}static getName(){return "ZenFlux/Core/Modules/Logger"}static getLogLevelString(){return getLoggerLogLevelString()}static getLogLevel(){return getLoggerLogLevel()}static attachOutputListener(listener){return LoggerBrowserInfra.attachOutputSubscriber(listener)}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("log",DEFAULT_LOG_PREFIX,caller,message,...params);}info(caller,message,...params){this.writeLog("info",DEFAULT_INFO_PREFIX,caller,message,...params);}debug(caller,message,...params){this.writeLog("debug",DEFAULT_DEBUG_PREFIX,caller,message,...params);}warn(caller,message,...params){this.writeLog("warn",DEFAULT_WARN_PREFIX,caller,message,...params);}error(caller,message,...params){this.writeLog("error",DEFAULT_ERROR_PREFIX,caller,message,...params);}admin(caller,message,...params){this.writeLog("admin",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(level,prefix,caller,message,...params){const callerName=this.getCallerName(caller);const source=this.getPreviousSource()+pc.white(`${this.ownerName}::${callerName}`);let messagePrefix="";if(this.messagePrefixes.length){messagePrefix=`[${this.messagePrefixes.join("][")}]`;}const timestampValue=Date.now();const timeDiff=(timestampValue-Logger.lastLogTime).toString().padStart(4,"0");const timeFormat=Logger.getTimestampFormat();const timestamp=timeFormat?this.formatTime(new Date(timestampValue),timeFormat):"";this.outputEvent(prefix,timeDiff,source,messagePrefix,message,params);const timestampPart=timestamp?`${timestamp} `:"";const output=`${timestampPart}${prefix}[+${timeDiff}ms][${source}]${messagePrefix}: ${message}`;const formatted=this.createBrowserFormat(level,callerName,messagePrefix,message);const metadata={id:`${timestampValue}-${Math.random().toString(16).slice(2)}`,level,namespace:this.ownerName,callerName,message,messagePrefix,payload:params.length===0?undefined:params.length===1?params[0]:params,timestamp:timestampValue,formatted};this.runWithOutputMetadata(metadata,()=>{this.output(output,...params);});Logger.lastLogTime=timestampValue;}createBrowserFormat(level,callerName,messagePrefix,message){const prefixLabel=LEVEL_LABELS[level]||level.toUpperCase();const prefixPart=messagePrefix?`${messagePrefix} `:"";return {format:`%c(${prefixLabel})-> %c%c${this.ownerName}%c::%c${callerName}%c() ${prefixPart}${message}%c`,styles:[...this.defaultStyle]}}formatTime(date,format){const pad=(num,size=2)=>num.toString().padStart(size,"0");const tokens={"YYYY":date.getFullYear().toString(),"Y":date.getFullYear().toString(),"M":pad(date.getMonth()+1),"D":pad(date.getDate()),"HH":pad(date.getHours()),"hh":pad(date.getHours()),"mm":pad(date.getMinutes()),"ss":pad(date.getSeconds()),"SSS":pad(date.getMilliseconds(),3),"S":pad(date.getMilliseconds(),3)};return format.replace(/YYYY|HH|hh|mm|ss|SSS|Y|M|D|S|h|m|s/g,token=>tokens[token]??token)}}
|
|
74
|
+
|
|
75
|
+
class ZenFluxLogger extends Logger{}const loggerCache=new Map;const resolveOwnerName=owner=>{if(typeof owner==="string"){return owner}if(owner&&typeof owner.getName==="function"){return owner.getName()}return "UnknownOwner"};const createLogger=(owner,options)=>{const ownerName=resolveOwnerName(owner);const cached=loggerCache.get(ownerName);if(cached){return cached}const logger=new ZenFluxLogger(owner,options);loggerCache.set(ownerName,logger);return logger};
|
|
76
|
+
|
|
77
|
+
class Commands extends ObjectBase{static trace=[];current={};currentArgs={};trace=[];commands={};onBeforeHooks={};onBeforeUIHooks={};onAfterHooks={};onAfterOnceHooks={};onAfterUIHooks={};onAfterAffectHooks={};logger;static getName(){return "ZenFlux/Core/Managers/Commands"}static async runCallbacks(callbacks,args={},options={}){const callbacksLength=callbacks?.length||0;for(let i=0;i<callbacksLength;++i){const callback=options.pop===true?callbacks.pop():callbacks[i];if(!callback){throw new Error("Callback is not defined.")}await callback(args,options);}}static hookCommand(stack,hookCommand,context){if(!stack[hookCommand]){stack[hookCommand]=[];}stack[hookCommand].push(context);}constructor(){super();const type=this.constructor;this.logger=createLogger(type);this.logger.startsEmpty(this.constructor);}async run(command,args={},options={}){if(typeof command==="string"){command=this.getCommandInstance(command,args,options);}this.attachCurrent(command,args);const result=await this.runInstance(command,args,options);this.detachCurrent(command);return result}register(commands,controller){const result={};Object.values(commands).forEach(command=>{const commandName=command.getName();if(this.commands[commandName]){throw new CommandAlreadyRegistered(command)}command.setController(controller);this.commands[commandName]=command;result[commandName]=command;});return result}getAll(){return this.commands}getByName(name){return this.commands[name]}getLogger(){return this.logger}getCommandInstance(name,args={},options={}){const CommandClass=this.commands[name];if(!CommandClass){throw new CommandNotFound(name)}return new CommandClass(args,options)}onBefore(hookCommand,callback){Commands.hookCommand(this.onBeforeHooks,hookCommand,callback);}onBeforeUI(hookCommand,callback){Commands.hookCommand(this.onBeforeUIHooks,hookCommand,callback);}onAfter(hookCommand,callback){Commands.hookCommand(this.onAfterHooks,hookCommand,callback);}onAfterUI(command,callback){Commands.hookCommand(this.onAfterUIHooks,command,callback);}onAfterOnce(command,callback){Commands.hookCommand(this.onAfterOnceHooks,command,callback);}onAfterAffect(hookCommand,affectCommand){Commands.hookCommand(this.onAfterAffectHooks,hookCommand,affectCommand);}onBeforeRun(command,args={},options={}){if(this.onBeforeHooks[command.getName()]){const callbacks=this.onBeforeHooks[command.getName()];callbacks.forEach(callback=>callback(args,options));}if(this.onBeforeUIHooks[command.getName()]){const callbacks=this.onBeforeUIHooks[command.getName()];callbacks.forEach(callback=>callback(args,options));}}async runInstance(command,args={},options={}){let result=null;this.logger.startsWith(this.runInstance,{command:command.getName(),options,args});this.onBeforeRun(command,args,options);result=await command.run();await this.onAfterRun(command,args,options,result);return result}async onAfterRun(command,args,options,result){options=Object.assign({},options);if(this.onAfterAffectHooks[command.getName()]){this.onAfterAffectHooks[command.getName()].forEach(command=>{args.result=result;result=this.run(command.toString(),args,options);});result=await result;}if(this.onAfterHooks){args.result=result;await Commands.runCallbacks(Object.assign([],this.onAfterHooks[command.getName()]),args,options);}if(this.onAfterOnceHooks){await Commands.runCallbacks(this.onAfterOnceHooks[command.getName()],args,{...options,pop:true});}if(this.onAfterUIHooks){Commands.runCallbacks(Object.assign([],this.onAfterUIHooks[command.getName()]),args,options);}return result}attachCurrent(command,args={}){this.current[command.getName()]=command;this.currentArgs[command.getName()]=args;this.trace.push(command.getName());Commands.trace.push(command.getName());}detachCurrent(command){delete this.current[command.getName()];delete this.currentArgs[command.getName()];Commands.trace.pop();this.trace.pop();}}
|
|
48
78
|
|
|
49
79
|
class Controllers extends ObjectBase{controllers={};constructor(){super();}static getName(){return "ZenFlux/Core/Managers/Controllers"}get(name){return this.controllers[name]}getAll(){return this.controllers}register(controller){if(this.controllers[controller.getName()]){throw new ControllerAlreadyRegistered(controller)}this.controllers[controller.getName()]=controller;return controller}}
|
|
50
80
|
|
|
@@ -77,36 +107,6 @@ get restful () { return restful; }
|
|
|
77
107
|
|
|
78
108
|
class ControllerBase extends ObjectBase{commands;restful;internal;static getName(){return "ZenFlux/Core/ControllerBase"}constructor(){super();this.initialize();}initialize(){this.register();this.setupHooks&&this.setupHooks();}register(){this.commands=commands.register(this.getCommands(),this);this.restful=restful.register(this.getRestful(),this);this.internal=internal.register(this.getInternal(),this);}getCommands(){return {}}getRestful(){return {}}getInternal(){return {}}setupHooks(){}}
|
|
79
109
|
|
|
80
|
-
const DEFAULT_LOG_LEVEL="5";function getEnvVar(key){if(typeof process!=="undefined"&&process?.env){return process.env[key]??process.env[`VITE_${key}`]}if(typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('zenflux-core.cjs', document.baseURI).href)) })!=="undefined"&&undefined){const env=undefined;return env[key]??env[`VITE_${key}`]}return undefined}function getLoggerDefaultLevel(){return DEFAULT_LOG_LEVEL}function getLoggerLogLevel(){const raw=getEnvVar("LOGGER_LOG_LEVEL");return parseInt(raw??DEFAULT_LOG_LEVEL,10)}function getLoggerTimeFormat(){return (getEnvVar("LOGGER_TIME_FORMAT")||"").trim()}function getLoggerLogLevelString(){switch(getLoggerLogLevel()){case 0:return "NONE";case 1:return "ERROR";case 2:return "WARN";case 3:return "ADMIN";case 4:return "INFO";case 5:return "LOG";case 6:return "DEBUG";default:return "UNKNOWN"}}function isLoggerDebugEnabled(){return getLoggerLogLevel()>=6}function isLoggerDisabled(){return getEnvVar("LOGGER_DISABLED")==="true"}function isLoggerPreviousSourceDisabled(){return getEnvVar("LOGGER_LOG_PREVIOUS_CALLER_SOURCE_DISABLED")==="true"}
|
|
81
|
-
|
|
82
|
-
var commonjsGlobal=typeof globalThis!=="undefined"?globalThis:typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x["default"]:x}function getDefaultExportFromNamespaceIfPresent(n){return n&&Object.prototype.hasOwnProperty.call(n,"default")?n["default"]:n}function getDefaultExportFromNamespaceIfNotNamed(n){return n&&Object.prototype.hasOwnProperty.call(n,"default")&&Object.keys(n).length===1?n["default"]:n}function getAugmentedNamespace(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var f=n.default;if(typeof f=="function"){var a=function a(){var isInstance=false;try{isInstance=this instanceof a;}catch{}if(isInstance){return Reflect.construct(f,arguments,this.constructor)}return f.apply(this,arguments)};a.prototype=f.prototype;}else a={};Object.defineProperty(a,"__esModule",{value:true});Object.keys(n).forEach(function(k){var d=Object.getOwnPropertyDescriptor(n,k);Object.defineProperty(a,k,d.get?d:{enumerable:true,get:function(){return n[k]}});});return a}
|
|
83
|
-
|
|
84
|
-
var picocolors$1={exports:{}};
|
|
85
|
-
|
|
86
|
-
var picocolors=picocolors$1.exports;var hasRequiredPicocolors;function requirePicocolors(){if(hasRequiredPicocolors)return picocolors$1.exports;hasRequiredPicocolors=1;let p=process||{},argv=p.argv||[],env=p.env||{};let isColorSupported=!(!!env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p.platform==="win32"||(p.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI);let formatter=(open,close,replace=open)=>input=>{let string=""+input,index=string.indexOf(close,open.length);return ~index?open+replaceClose(string,close,replace,index)+close:open+string+close};let replaceClose=(string,close,replace,index)=>{let result="",cursor=0;do{result+=string.substring(cursor,index)+replace;cursor=index+close.length;index=string.indexOf(close,cursor);}while(~index)return result+string.substring(cursor)};let createColors=(enabled=isColorSupported)=>{let f=enabled?formatter:()=>String;return {isColorSupported:enabled,reset:f("\x1b[0m","\x1b[0m"),bold:f("\x1b[1m","\x1b[22m","\x1b[22m\x1b[1m"),dim:f("\x1b[2m","\x1b[22m","\x1b[22m\x1b[2m"),italic:f("\x1b[3m","\x1b[23m"),underline:f("\x1b[4m","\x1b[24m"),inverse:f("\x1b[7m","\x1b[27m"),hidden:f("\x1b[8m","\x1b[28m"),strikethrough:f("\x1b[9m","\x1b[29m"),black:f("\x1b[30m","\x1b[39m"),red:f("\x1b[31m","\x1b[39m"),green:f("\x1b[32m","\x1b[39m"),yellow:f("\x1b[33m","\x1b[39m"),blue:f("\x1b[34m","\x1b[39m"),magenta:f("\x1b[35m","\x1b[39m"),cyan:f("\x1b[36m","\x1b[39m"),white:f("\x1b[37m","\x1b[39m"),gray:f("\x1b[90m","\x1b[39m"),bgBlack:f("\x1b[40m","\x1b[49m"),bgRed:f("\x1b[41m","\x1b[49m"),bgGreen:f("\x1b[42m","\x1b[49m"),bgYellow:f("\x1b[43m","\x1b[49m"),bgBlue:f("\x1b[44m","\x1b[49m"),bgMagenta:f("\x1b[45m","\x1b[49m"),bgCyan:f("\x1b[46m","\x1b[49m"),bgWhite:f("\x1b[47m","\x1b[49m"),blackBright:f("\x1b[90m","\x1b[39m"),redBright:f("\x1b[91m","\x1b[39m"),greenBright:f("\x1b[92m","\x1b[39m"),yellowBright:f("\x1b[93m","\x1b[39m"),blueBright:f("\x1b[94m","\x1b[39m"),magentaBright:f("\x1b[95m","\x1b[39m"),cyanBright:f("\x1b[96m","\x1b[39m"),whiteBright:f("\x1b[97m","\x1b[39m"),bgBlackBright:f("\x1b[100m","\x1b[49m"),bgRedBright:f("\x1b[101m","\x1b[49m"),bgGreenBright:f("\x1b[102m","\x1b[49m"),bgYellowBright:f("\x1b[103m","\x1b[49m"),bgBlueBright:f("\x1b[104m","\x1b[49m"),bgMagentaBright:f("\x1b[105m","\x1b[49m"),bgCyanBright:f("\x1b[106m","\x1b[49m"),bgWhiteBright:f("\x1b[107m","\x1b[49m")}};picocolors$1.exports=createColors();picocolors$1.exports.createColors=createColors;return picocolors$1.exports}
|
|
87
|
-
|
|
88
|
-
var picocolorsExports=requirePicocolors();var pc = getDefaultExportFromCjs(picocolorsExports);
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Reduce circular references.
|
|
92
|
-
*
|
|
93
|
-
* @copyright https://stackoverflow.com/a/53731154
|
|
94
|
-
*/const reduceCircularReferences=()=>{const seen=new WeakSet;return (key,value)=>{if(typeof value==="object"&&value!==null){if(seen.has(value)){return}seen.add(value);}return value}};
|
|
95
|
-
|
|
96
|
-
/**
|
|
97
|
-
* Function hexColorDelta() : Return color difference in ratio decimal point.
|
|
98
|
-
*
|
|
99
|
-
* @copyright http://jsfiddle.net/96sME/
|
|
100
|
-
*/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};
|
|
101
|
-
|
|
102
|
-
const MAX_MAPPING_RECURSIVE_DEPTH=4,UNKNOWN_CALLER_NAME="anonymous function";Error.stackTraceLimit=50;class LoggerBrowserInfra extends ObjectBase{static mappers=[];static mapperDepth=0;static colorsOwners={};static colorsUsed=[];static outputSubscribers=new Set;defaultStyle;owner;args;color;outputHandler=console.log;pendingOutputMetadata;static getName(){return "ZenFlux/Logging/Modules/LoggerBrowserInfra"}static reset(){LoggerBrowserInfra.mappers=[];LoggerBrowserInfra.mapperDepth=0;LoggerBrowserInfra.colorsUsed=[];LoggerBrowserInfra.colorsOwners={};LoggerBrowserInfra.outputSubscribers.clear();}static attachOutputSubscriber(subscriber){LoggerBrowserInfra.outputSubscribers.add(subscriber);return ()=>{LoggerBrowserInfra.outputSubscribers.delete(subscriber);}}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.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);if(LoggerBrowserInfra.outputSubscribers.size===0){return}const event={logger:this,namespace:this.getOwnerName(),args,metadata:this.pendingOutputMetadata};LoggerBrowserInfra.outputSubscribers.forEach(subscriber=>{try{subscriber(event);}catch(error){console.error("[ZenFlux][Logger] output subscriber failed",error);}});}setOutputHandler(outputHandler){this.outputHandler=outputHandler;}runWithOutputMetadata(metadata,callback){const previous=this.pendingOutputMetadata;this.pendingOutputMetadata=metadata;try{return callback()}finally{this.pendingOutputMetadata=previous;}}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 color="#";for(let i=0;i<6;i++){color+=hex[Math.floor(Math.random()*16)];}return color}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}}
|
|
103
|
-
|
|
104
|
-
let SimpleEventEmitter=class SimpleEventEmitter{listeners=new Map;on(event,callback){if(!this.listeners.has(event)){this.listeners.set(event,new Set);}this.listeners.get(event).add(callback);}off(event,callback){this.listeners.get(event)?.delete(callback);}emit(event,...args){const callbacks=this.listeners.get(event);if(!callbacks||callbacks.size===0){return false}callbacks.forEach(cb=>cb(...args));return true}removeAllListeners(event){this.listeners.delete(event);}eventNames(){return Array.from(this.listeners.keys())}};class EventBus extends ObjectBase{static instance=null;objects=new Map;eventEmitter=new SimpleEventEmitter;lastEmittedEvents=new Map;static getName(){return "ZenFlux/Core/Modules/EventBus"}static getInstance(){if(!EventBus.instance){EventBus.instance=new EventBus;}return EventBus.instance}static get $(){return EventBus.getInstance()}getObjectNames(){return Array.from(this.objects.keys())}getEventNames(){this.eventEmitter.eventNames();}getEventName(objectName,methodName){return `${objectName}::${methodName}`}on(objectName,methodName,callback){if(!this.objects.has(objectName)){throw new Error(`Object ${objectName} is not registered`)}this.eventEmitter.on(this.getEventName(objectName,methodName),callback);}onCalledBeforeDoInvoke(objectName,methodName,callback){this.on(objectName,methodName,callback);if(this.objects.has(objectName)){const objectEntry=this.objects.get(objectName);if(objectEntry){const method=objectEntry.methods.find(method=>method.name===methodName);if(method&&this.lastEmittedEvents.has(this.getEventName(objectName,methodName))){callback(...this.lastEmittedEvents.get(this.getEventName(objectName,methodName)));}}}}off(objectName,methodName,callback){this.eventEmitter.off(this.getEventName(objectName,methodName),callback);}register(object,methods){if(this.objects.has(object.getName())){throw new Error(`Error in: '${this.getName()}', object: '${object.getName()}' is already registered`)}this.objects.set(object.getName(),{object,methods});this.hook(object,methods);}registerMultiInstances(object,methods){const objectName=object.getName();if(this.objects.has(objectName)){const existingEntry=this.objects.get(objectName);if(Array.isArray(existingEntry.object)){existingEntry.object.push(object);}else {existingEntry.object=[existingEntry.object,object];}}else {this.objects.set(objectName,{object,methods});}this.hook(object,methods);}unregister(objectName){const entry=this.objects.get(objectName);if(!entry){return false}if(Array.isArray(entry.object)){entry.object.forEach(obj=>{this.unhookObject(obj,entry.methods);});}else {this.unhookObject(entry.object,entry.methods);}this.objects.delete(objectName);}unhookObject(object,methods){methods.forEach(method=>{this.ensureFunction(object,method);this.eventEmitter.removeAllListeners(this.getEventName(object.getName(),method.name));object[method.name]=method;});}unhook(entry){if(Array.isArray(entry.object)){entry.object.forEach(obj=>{this.unhookObject(obj,entry.methods);});}else {this.unhookObject(entry.object,entry.methods);}}emit(object,method,...args){const eventName=this.getEventName(object.getName(),method.name);this.lastEmittedEvents.set(eventName,args);return this.eventEmitter.emit(eventName,...args)}hook(object,methods){methods.forEach(method=>{this.ensureFunction(object,method);const originalMethod=method;const eventBusHook=async(...args)=>{const result=await originalMethod.apply(object,args);this.emit(object,method,...args);return result};object[method.name]=new Proxy(eventBusHook,{get(target,prop){if(prop==="name"){return method.name}return target[prop]}});});}ensureFunction(object,method){if("function"!==typeof method){throw new Error(`Method ${method} is not a function on ${object.getName()}`)}}}
|
|
105
|
-
|
|
106
|
-
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 LEVEL_LABELS={log:"LOG",info:"INFO",debug:"DEBUG",warn:"WARN",error:"ERROR",admin:"ADMIN"};const registeredNames={};class Logger extends LoggerBrowserInfra{static lastLogTime=Date.now();static timestampFormat=getLoggerTimeFormat();ownerName;messagePrefixes=[];config={};static setTimestampFormat(format){Logger.timestampFormat=(format||"").trim();}static getTimestampFormat(){return Logger.timestampFormat}static getName(){return "ZenFlux/Core/Modules/Logger"}static getLogLevelString(){return getLoggerLogLevelString()}static getLogLevel(){return getLoggerLogLevel()}static attachOutputListener(listener){return LoggerBrowserInfra.attachOutputSubscriber(listener)}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("log",DEFAULT_LOG_PREFIX,caller,message,...params);}info(caller,message,...params){this.writeLog("info",DEFAULT_INFO_PREFIX,caller,message,...params);}debug(caller,message,...params){this.writeLog("debug",DEFAULT_DEBUG_PREFIX,caller,message,...params);}warn(caller,message,...params){this.writeLog("warn",DEFAULT_WARN_PREFIX,caller,message,...params);}error(caller,message,...params){this.writeLog("error",DEFAULT_ERROR_PREFIX,caller,message,...params);}admin(caller,message,...params){this.writeLog("admin",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(level,prefix,caller,message,...params){const callerName=this.getCallerName(caller);const source=this.getPreviousSource()+pc.white(`${this.ownerName}::${callerName}`);let messagePrefix="";if(this.messagePrefixes.length){messagePrefix=`[${this.messagePrefixes.join("][")}]`;}const timestampValue=Date.now();const timeDiff=(timestampValue-Logger.lastLogTime).toString().padStart(4,"0");const timeFormat=Logger.getTimestampFormat();const timestamp=timeFormat?this.formatTime(new Date(timestampValue),timeFormat):"";this.outputEvent(prefix,timeDiff,source,messagePrefix,message,params);const timestampPart=timestamp?`${timestamp} `:"";const output=`${timestampPart}${prefix}[+${timeDiff}ms][${source}]${messagePrefix}: ${message}`;const formatted=this.createBrowserFormat(level,callerName,messagePrefix,message);const metadata={id:`${timestampValue}-${Math.random().toString(16).slice(2)}`,level,namespace:this.ownerName,callerName,message,messagePrefix,payload:params.length===0?undefined:params.length===1?params[0]:params,timestamp:timestampValue,formatted};this.runWithOutputMetadata(metadata,()=>{this.output(output,...params);});Logger.lastLogTime=timestampValue;}createBrowserFormat(level,callerName,messagePrefix,message){const prefixLabel=LEVEL_LABELS[level]||level.toUpperCase();const prefixPart=messagePrefix?`${messagePrefix} `:"";return {format:`%c(${prefixLabel})-> %c%c${this.ownerName}%c::%c${callerName}%c() ${prefixPart}${message}%c`,styles:[...this.defaultStyle]}}formatTime(date,format){const pad=(num,size=2)=>num.toString().padStart(size,"0");const tokens={"YYYY":date.getFullYear().toString(),"Y":date.getFullYear().toString(),"M":pad(date.getMonth()+1),"D":pad(date.getDate()),"HH":pad(date.getHours()),"hh":pad(date.getHours()),"mm":pad(date.getMinutes()),"ss":pad(date.getSeconds()),"SSS":pad(date.getMilliseconds(),3),"S":pad(date.getMilliseconds(),3)};return format.replace(/YYYY|HH|hh|mm|ss|SSS|Y|M|D|S|h|m|s/g,token=>tokens[token]??token)}}
|
|
107
|
-
|
|
108
|
-
class ZenFluxLogger extends Logger{}const loggerCache=new Map;const resolveOwnerName=owner=>{if(typeof owner==="string"){return owner}if(owner&&typeof owner.getName==="function"){return owner.getName()}return "UnknownOwner"};const createLogger=(owner,options)=>{const ownerName=resolveOwnerName(owner);const cached=loggerCache.get(ownerName);if(cached){return cached}const logger=new ZenFluxLogger(owner,options);loggerCache.set(ownerName,logger);return logger};
|
|
109
|
-
|
|
110
110
|
class InitializeBase extends ObjectBase{logger;constructor(shouldInitialize=true){super();this.logger=new Logger(this);if(this.initialize&&shouldInitialize){this.initialize();}}debounce(func,delay){let timeoutId;return (...args)=>{clearTimeout(timeoutId);timeoutId=setTimeout(()=>{func.apply(this,args);},delay);}}}
|
|
111
111
|
|
|
112
112
|
class SingletonBase extends InitializeBase{static instances=new Map;constructor(){super();}static getInstance(){if(!SingletonBase.instances.has(this)){SingletonBase.instances.set(this,new this);}return SingletonBase.instances.get(this)}}
|
|
@@ -126,7 +126,7 @@ ObjectBase: ObjectBase,
|
|
|
126
126
|
SingletonBase: SingletonBase
|
|
127
127
|
});
|
|
128
128
|
|
|
129
|
-
class CommandBase extends ObjectBase{static controller;args={};options={};logger;static getName(){return "ZenFlux/Core/CommandBases/CommandBase"}static setController(controller){if(this.controller){throw new ControllerAlreadySet(this.controller)}this.controller=controller;}static getController(){return this.controller}constructor(args={},options={}){super();const type=this.constructor;this.logger=
|
|
129
|
+
class CommandBase extends ObjectBase{static controller;args={};options={};logger;static getName(){return "ZenFlux/Core/CommandBases/CommandBase"}static setController(controller){if(this.controller){throw new ControllerAlreadySet(this.controller)}this.controller=controller;}static getController(){return this.controller}constructor(args={},options={}){super();const type=this.constructor;this.logger=createLogger(type);this.logger.startsWith(this.constructor,{args,options});this.initialize(args,options);}initialize(args,options){this.args=args;this.options=options;}apply(args=this.args,options=this.options){throw new ForceMethodImplementation(this,"apply")}async run(){return this.runInternal()}async runInternal(){this.onBeforeApply&&this.onBeforeApply();const result=await this.apply(this.args,this.options);this.onAfterApply&&this.onAfterApply();return result}}
|
|
130
130
|
|
|
131
131
|
class CommandPublic extends CommandBase{static getName(){return "ZenFlux/Core/CommandBases/CommandPublic"}}
|
|
132
132
|
|
|
@@ -166,12 +166,12 @@ createLogger: createLogger
|
|
|
166
166
|
|
|
167
167
|
var _package = {
|
|
168
168
|
"name": "@zenflux/core",
|
|
169
|
-
"version": "0.1.
|
|
169
|
+
"version": "0.1.30",
|
|
170
170
|
"types": "dist/zenflux-core.d.ts",
|
|
171
171
|
"type": "module",
|
|
172
172
|
"files": [
|
|
173
173
|
"dist",
|
|
174
|
-
"
|
|
174
|
+
"src"
|
|
175
175
|
],
|
|
176
176
|
"scripts": {
|
|
177
177
|
"@z-core--test": "jest",
|
|
@@ -214,10 +214,10 @@ var _package = {
|
|
|
214
214
|
}
|
|
215
215
|
};
|
|
216
216
|
const name = "@zenflux/core";
|
|
217
|
-
const version = "0.1.
|
|
217
|
+
const version = "0.1.30";
|
|
218
218
|
const types = "dist/zenflux-core.d.ts";
|
|
219
219
|
const type = "module";
|
|
220
|
-
const files = ["dist","
|
|
220
|
+
const files = ["dist","src"];
|
|
221
221
|
const scripts = {"@z-core--test":"jest","@z-core--build":"@z-cli @build","@z-core--dev":"@z-cli @watch --dev"};
|
|
222
222
|
const exports$1 = {".":{"import":"./dist/zenflux-core.mjs","default":"./dist/zenflux-core.cjs","require":"./dist/zenflux-core.mjs.js","types":"./dist/zenflux-core.d.ts"},"./dist/src/*":"./src/*","./src/*.ts":"./src/*.ts","./src/*":"./src/*.ts","./src/bases":"./src/bases/index.ts","./src/bases/*":"./src/bases/*.ts","./src/clients":"./src/clients/index.ts","./src/command-bases":"./src/command-bases/index.ts","./src/errors":"./src/errors/index.ts","./src/interfaces":"./src/interfaces/index.ts","./src/managers":"./src/managers/index.ts","./src/modules/logger":"./src/modules/logger/index.ts","./src/modules/*":"./src/modules/*.ts","./package.json":"./package.json"};
|
|
223
223
|
const devDependencies = {"@jest/globals":"^29.7.0","@zenflux/cli":"workspace:*"};
|
package/dist/zenflux-core.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Bundled with love using the help of @zenflux/cli toolkit v0.1.43
|
|
3
|
-
* Bundle name: @zenflux/core fileName: 'zenflux-core', built at
|
|
3
|
+
* Bundle name: @zenflux/core fileName: 'zenflux-core', built at Sat Sep 12 2026 13:50:48 GMT+0300 (Israel Daylight Time)
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
import * as util from 'util';
|
|
@@ -16,11 +16,41 @@ class ControllerAlreadySet extends Error{constructor(controller){super(`Controll
|
|
|
16
16
|
|
|
17
17
|
class ForceMethodBase extends Error{constructor(className,methodName){super(`ForceMethod implementation: at '${className}' method: '${methodName}'`);}}class ForceMethodImplementation extends Error{constructor(context,methodName){super(`ForceMethod implementation: at '${"string"===typeof context?context:context.getName()}' method: '${methodName}'`);}}
|
|
18
18
|
|
|
19
|
-
class ErrorWithMetadata extends Error{metadata;constructor(message,metadata=null){super(message);this.metadata=metadata;const metaView=null!==metadata?formatMetadata(metadata):null;this.message=null!==metaView?`${message} - Metadata: ${metaView}`:message;Object.setPrototypeOf(this,new.target.prototype);}}function formatMetadata(metadata){try{if(metadata===null||metadata===undefined){return String(metadata)}if(typeof metadata==="object"){return JSON.stringify(metadata)}return String(metadata)}catch
|
|
19
|
+
class ErrorWithMetadata extends Error{metadata;constructor(message,metadata=null){super(message);this.metadata=metadata;const metaView=null!==metadata?formatMetadata(metadata):null;this.message=null!==metaView?`${message} - Metadata: ${metaView}`:message;Object.setPrototypeOf(this,new.target.prototype);}}function formatMetadata(metadata){try{if(metadata===null||metadata===undefined){return String(metadata)}if(typeof metadata==="object"){return JSON.stringify(metadata)}return String(metadata)}catch{return "[unserializable metadata]"}}
|
|
20
20
|
|
|
21
21
|
class ObjectBase{id;name="__UNDEFINED_NAME__";constructor(){this.name=this.getName();const timestamp=performance.now()*1e6;const random1=BigInt(Math.floor(Math.random()*1e6));const random2=BigInt(Math.floor(Math.random()*1e6));this.id=`${timestamp}${random1}${random2}`;}static getName(){throw new ForceMethodBase(this.name,"getName")}static getSourcePath(){throw new ForceMethodBase(this.name,"getSourcePath")}getName(){return this.constructor.getName()}getUniqueId(){return this.id}getInitialName(){return this.name}getHierarchyNames(){const classNames=[];let obj=Object.getPrototypeOf(this);let className;while((className=obj.getName())!=="Object"){classNames.push(className);obj=Object.getPrototypeOf(obj);if(obj.constructor===ObjectBase){break}}return classNames}}
|
|
22
22
|
|
|
23
|
-
|
|
23
|
+
var commonjsGlobal=typeof globalThis!=="undefined"?globalThis:typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x["default"]:x}function getDefaultExportFromNamespaceIfPresent(n){return n&&Object.prototype.hasOwnProperty.call(n,"default")?n["default"]:n}function getDefaultExportFromNamespaceIfNotNamed(n){return n&&Object.prototype.hasOwnProperty.call(n,"default")&&Object.keys(n).length===1?n["default"]:n}function getAugmentedNamespace(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var f=n.default;if(typeof f=="function"){var a=function a(){var isInstance=false;try{isInstance=this instanceof a;}catch(e){}if(isInstance){return Reflect.construct(f,arguments,this.constructor)}return f.apply(this,arguments)};a.prototype=f.prototype;}else a={};Object.defineProperty(a,"__esModule",{value:true});Object.keys(n).forEach(function(k){var d=Object.getOwnPropertyDescriptor(n,k);Object.defineProperty(a,k,d.get?d:{enumerable:true,get:function(){return n[k]}});});return a}
|
|
24
|
+
|
|
25
|
+
var picocolors$1={exports:{}};
|
|
26
|
+
|
|
27
|
+
var picocolors=picocolors$1.exports;var hasRequiredPicocolors;function requirePicocolors(){if(hasRequiredPicocolors)return picocolors$1.exports;hasRequiredPicocolors=1;let p=process||{},argv=p.argv||[],env=p.env||{};let isColorSupported=!(!!env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p.platform==="win32"||(p.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI);let formatter=(open,close,replace=open)=>input=>{let string=""+input,index=string.indexOf(close,open.length);return ~index?open+replaceClose(string,close,replace,index)+close:open+string+close};let replaceClose=(string,close,replace,index)=>{let result="",cursor=0;do{result+=string.substring(cursor,index)+replace;cursor=index+close.length;index=string.indexOf(close,cursor);}while(~index)return result+string.substring(cursor)};let createColors=(enabled=isColorSupported)=>{let f=enabled?formatter:()=>String;return {isColorSupported:enabled,reset:f("\x1b[0m","\x1b[0m"),bold:f("\x1b[1m","\x1b[22m","\x1b[22m\x1b[1m"),dim:f("\x1b[2m","\x1b[22m","\x1b[22m\x1b[2m"),italic:f("\x1b[3m","\x1b[23m"),underline:f("\x1b[4m","\x1b[24m"),inverse:f("\x1b[7m","\x1b[27m"),hidden:f("\x1b[8m","\x1b[28m"),strikethrough:f("\x1b[9m","\x1b[29m"),black:f("\x1b[30m","\x1b[39m"),red:f("\x1b[31m","\x1b[39m"),green:f("\x1b[32m","\x1b[39m"),yellow:f("\x1b[33m","\x1b[39m"),blue:f("\x1b[34m","\x1b[39m"),magenta:f("\x1b[35m","\x1b[39m"),cyan:f("\x1b[36m","\x1b[39m"),white:f("\x1b[37m","\x1b[39m"),gray:f("\x1b[90m","\x1b[39m"),bgBlack:f("\x1b[40m","\x1b[49m"),bgRed:f("\x1b[41m","\x1b[49m"),bgGreen:f("\x1b[42m","\x1b[49m"),bgYellow:f("\x1b[43m","\x1b[49m"),bgBlue:f("\x1b[44m","\x1b[49m"),bgMagenta:f("\x1b[45m","\x1b[49m"),bgCyan:f("\x1b[46m","\x1b[49m"),bgWhite:f("\x1b[47m","\x1b[49m"),blackBright:f("\x1b[90m","\x1b[39m"),redBright:f("\x1b[91m","\x1b[39m"),greenBright:f("\x1b[92m","\x1b[39m"),yellowBright:f("\x1b[93m","\x1b[39m"),blueBright:f("\x1b[94m","\x1b[39m"),magentaBright:f("\x1b[95m","\x1b[39m"),cyanBright:f("\x1b[96m","\x1b[39m"),whiteBright:f("\x1b[97m","\x1b[39m"),bgBlackBright:f("\x1b[100m","\x1b[49m"),bgRedBright:f("\x1b[101m","\x1b[49m"),bgGreenBright:f("\x1b[102m","\x1b[49m"),bgYellowBright:f("\x1b[103m","\x1b[49m"),bgBlueBright:f("\x1b[104m","\x1b[49m"),bgMagentaBright:f("\x1b[105m","\x1b[49m"),bgCyanBright:f("\x1b[106m","\x1b[49m"),bgWhiteBright:f("\x1b[107m","\x1b[49m")}};picocolors$1.exports=createColors();picocolors$1.exports.createColors=createColors;return picocolors$1.exports}
|
|
28
|
+
|
|
29
|
+
var picocolorsExports=requirePicocolors();var pc = getDefaultExportFromCjs(picocolorsExports);
|
|
30
|
+
|
|
31
|
+
const DEFAULT_LOG_LEVEL="5";function getEnvVar(key){if(typeof process!=="undefined"&&process?.env){return process.env[key]??process.env[`VITE_${key}`]}if(typeof import.meta!=="undefined"&&import.meta.env){const env=import.meta.env;return env[key]??env[`VITE_${key}`]}return undefined}function getLoggerDefaultLevel(){return DEFAULT_LOG_LEVEL}function getLoggerLogLevel(){const raw=getEnvVar("LOGGER_LOG_LEVEL");return parseInt(raw??DEFAULT_LOG_LEVEL,10)}function getLoggerTimeFormat(){return (getEnvVar("LOGGER_TIME_FORMAT")||"").trim()}function getLoggerLogLevelString(){switch(getLoggerLogLevel()){case 0:return "NONE";case 1:return "ERROR";case 2:return "WARN";case 3:return "ADMIN";case 4:return "INFO";case 5:return "LOG";case 6:return "DEBUG";default:return "UNKNOWN"}}function isLoggerDebugEnabled(){return getLoggerLogLevel()>=6}function isLoggerDisabled(){return getEnvVar("LOGGER_DISABLED")==="true"}function isLoggerPreviousSourceDisabled(){return getEnvVar("LOGGER_LOG_PREVIOUS_CALLER_SOURCE_DISABLED")==="true"}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Reduce circular references.
|
|
35
|
+
*
|
|
36
|
+
* @copyright https://stackoverflow.com/a/53731154
|
|
37
|
+
*/const reduceCircularReferences=()=>{const seen=new WeakSet;return (key,value)=>{if(typeof value==="object"&&value!==null){if(seen.has(value)){return}seen.add(value);}return value}};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Function hexColorDelta() : Return color difference in ratio decimal point.
|
|
41
|
+
*
|
|
42
|
+
* @copyright http://jsfiddle.net/96sME/
|
|
43
|
+
*/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};
|
|
44
|
+
|
|
45
|
+
const MAX_MAPPING_RECURSIVE_DEPTH=4,UNKNOWN_CALLER_NAME="anonymous function";Error.stackTraceLimit=50;class LoggerBrowserInfra extends ObjectBase{static mappers=[];static mapperDepth=0;static colorsOwners={};static colorsUsed=[];static outputSubscribers=new Set;defaultStyle;owner;args;color;outputHandler=console.log;pendingOutputMetadata;static getName(){return "ZenFlux/Logging/Modules/LoggerBrowserInfra"}static reset(){LoggerBrowserInfra.mappers=[];LoggerBrowserInfra.mapperDepth=0;LoggerBrowserInfra.colorsUsed=[];LoggerBrowserInfra.colorsOwners={};LoggerBrowserInfra.outputSubscribers.clear();}static attachOutputSubscriber(subscriber){LoggerBrowserInfra.outputSubscribers.add(subscriber);return ()=>{LoggerBrowserInfra.outputSubscribers.delete(subscriber);}}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.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);if(LoggerBrowserInfra.outputSubscribers.size===0){return}const event={logger:this,namespace:this.getOwnerName(),args,metadata:this.pendingOutputMetadata};LoggerBrowserInfra.outputSubscribers.forEach(subscriber=>{try{subscriber(event);}catch(error){console.error("[ZenFlux][Logger] output subscriber failed",error);}});}setOutputHandler(outputHandler){this.outputHandler=outputHandler;}runWithOutputMetadata(metadata,callback){const previous=this.pendingOutputMetadata;this.pendingOutputMetadata=metadata;try{return callback()}finally{this.pendingOutputMetadata=previous;}}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 color="#";for(let i=0;i<6;i++){color+=hex[Math.floor(Math.random()*16)];}return color}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}}
|
|
46
|
+
|
|
47
|
+
let SimpleEventEmitter=class SimpleEventEmitter{listeners=new Map;on(event,callback){if(!this.listeners.has(event)){this.listeners.set(event,new Set);}this.listeners.get(event).add(callback);}off(event,callback){this.listeners.get(event)?.delete(callback);}emit(event,...args){const callbacks=this.listeners.get(event);if(!callbacks||callbacks.size===0){return false}callbacks.forEach(cb=>cb(...args));return true}removeAllListeners(event){this.listeners.delete(event);}eventNames(){return Array.from(this.listeners.keys())}};class EventBus extends ObjectBase{static instance=null;objects=new Map;eventEmitter=new SimpleEventEmitter;lastEmittedEvents=new Map;static getName(){return "ZenFlux/Core/Modules/EventBus"}static getInstance(){if(!EventBus.instance){EventBus.instance=new EventBus;}return EventBus.instance}static get $(){return EventBus.getInstance()}getObjectNames(){return Array.from(this.objects.keys())}getEventNames(){this.eventEmitter.eventNames();}getEventName(objectName,methodName){return `${objectName}::${methodName}`}on(objectName,methodName,callback){if(!this.objects.has(objectName)){throw new Error(`Object ${objectName} is not registered`)}this.eventEmitter.on(this.getEventName(objectName,methodName),callback);}onCalledBeforeDoInvoke(objectName,methodName,callback){this.on(objectName,methodName,callback);if(this.objects.has(objectName)){const objectEntry=this.objects.get(objectName);if(objectEntry){const method=objectEntry.methods.find(method=>method.name===methodName);if(method&&this.lastEmittedEvents.has(this.getEventName(objectName,methodName))){callback(...this.lastEmittedEvents.get(this.getEventName(objectName,methodName)));}}}}off(objectName,methodName,callback){this.eventEmitter.off(this.getEventName(objectName,methodName),callback);}register(object,methods){if(this.objects.has(object.getName())){throw new Error(`Error in: '${this.getName()}', object: '${object.getName()}' is already registered`)}this.objects.set(object.getName(),{object,methods});this.hook(object,methods);}registerMultiInstances(object,methods){const objectName=object.getName();if(this.objects.has(objectName)){const existingEntry=this.objects.get(objectName);if(Array.isArray(existingEntry.object)){existingEntry.object.push(object);}else {existingEntry.object=[existingEntry.object,object];}}else {this.objects.set(objectName,{object,methods});}this.hook(object,methods);}unregister(objectName){const entry=this.objects.get(objectName);if(!entry){return false}if(Array.isArray(entry.object)){entry.object.forEach(obj=>{this.unhookObject(obj,entry.methods);});}else {this.unhookObject(entry.object,entry.methods);}this.objects.delete(objectName);}unhookObject(object,methods){methods.forEach(method=>{this.ensureFunction(object,method);this.eventEmitter.removeAllListeners(this.getEventName(object.getName(),method.name));object[method.name]=method;});}unhook(entry){if(Array.isArray(entry.object)){entry.object.forEach(obj=>{this.unhookObject(obj,entry.methods);});}else {this.unhookObject(entry.object,entry.methods);}}emit(object,method,...args){const eventName=this.getEventName(object.getName(),method.name);this.lastEmittedEvents.set(eventName,args);return this.eventEmitter.emit(eventName,...args)}hook(object,methods){methods.forEach(method=>{this.ensureFunction(object,method);const originalMethod=method;const eventBusHook=async(...args)=>{const result=await originalMethod.apply(object,args);this.emit(object,method,...args);return result};object[method.name]=new Proxy(eventBusHook,{get(target,prop){if(prop==="name"){return method.name}return target[prop]}});});}ensureFunction(object,method){if("function"!==typeof method){throw new Error(`Method ${method} is not a function on ${object.getName()}`)}}}
|
|
48
|
+
|
|
49
|
+
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 LEVEL_LABELS={log:"LOG",info:"INFO",debug:"DEBUG",warn:"WARN",error:"ERROR",admin:"ADMIN"};const registeredNames={};class Logger extends LoggerBrowserInfra{static lastLogTime=Date.now();static timestampFormat=getLoggerTimeFormat();ownerName;messagePrefixes=[];config={};static setTimestampFormat(format){Logger.timestampFormat=(format||"").trim();}static getTimestampFormat(){return Logger.timestampFormat}static getName(){return "ZenFlux/Core/Modules/Logger"}static getLogLevelString(){return getLoggerLogLevelString()}static getLogLevel(){return getLoggerLogLevel()}static attachOutputListener(listener){return LoggerBrowserInfra.attachOutputSubscriber(listener)}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("log",DEFAULT_LOG_PREFIX,caller,message,...params);}info(caller,message,...params){this.writeLog("info",DEFAULT_INFO_PREFIX,caller,message,...params);}debug(caller,message,...params){this.writeLog("debug",DEFAULT_DEBUG_PREFIX,caller,message,...params);}warn(caller,message,...params){this.writeLog("warn",DEFAULT_WARN_PREFIX,caller,message,...params);}error(caller,message,...params){this.writeLog("error",DEFAULT_ERROR_PREFIX,caller,message,...params);}admin(caller,message,...params){this.writeLog("admin",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(level,prefix,caller,message,...params){const callerName=this.getCallerName(caller);const source=this.getPreviousSource()+pc.white(`${this.ownerName}::${callerName}`);let messagePrefix="";if(this.messagePrefixes.length){messagePrefix=`[${this.messagePrefixes.join("][")}]`;}const timestampValue=Date.now();const timeDiff=(timestampValue-Logger.lastLogTime).toString().padStart(4,"0");const timeFormat=Logger.getTimestampFormat();const timestamp=timeFormat?this.formatTime(new Date(timestampValue),timeFormat):"";this.outputEvent(prefix,timeDiff,source,messagePrefix,message,params);const timestampPart=timestamp?`${timestamp} `:"";const output=`${timestampPart}${prefix}[+${timeDiff}ms][${source}]${messagePrefix}: ${message}`;const formatted=this.createBrowserFormat(level,callerName,messagePrefix,message);const metadata={id:`${timestampValue}-${Math.random().toString(16).slice(2)}`,level,namespace:this.ownerName,callerName,message,messagePrefix,payload:params.length===0?undefined:params.length===1?params[0]:params,timestamp:timestampValue,formatted};this.runWithOutputMetadata(metadata,()=>{this.output(output,...params);});Logger.lastLogTime=timestampValue;}createBrowserFormat(level,callerName,messagePrefix,message){const prefixLabel=LEVEL_LABELS[level]||level.toUpperCase();const prefixPart=messagePrefix?`${messagePrefix} `:"";return {format:`%c(${prefixLabel})-> %c%c${this.ownerName}%c::%c${callerName}%c() ${prefixPart}${message}%c`,styles:[...this.defaultStyle]}}formatTime(date,format){const pad=(num,size=2)=>num.toString().padStart(size,"0");const tokens={"YYYY":date.getFullYear().toString(),"Y":date.getFullYear().toString(),"M":pad(date.getMonth()+1),"D":pad(date.getDate()),"HH":pad(date.getHours()),"hh":pad(date.getHours()),"mm":pad(date.getMinutes()),"ss":pad(date.getSeconds()),"SSS":pad(date.getMilliseconds(),3),"S":pad(date.getMilliseconds(),3)};return format.replace(/YYYY|HH|hh|mm|ss|SSS|Y|M|D|S|h|m|s/g,token=>tokens[token]??token)}}
|
|
50
|
+
|
|
51
|
+
class ZenFluxLogger extends Logger{}const loggerCache=new Map;const resolveOwnerName=owner=>{if(typeof owner==="string"){return owner}if(owner&&typeof owner.getName==="function"){return owner.getName()}return "UnknownOwner"};const createLogger=(owner,options)=>{const ownerName=resolveOwnerName(owner);const cached=loggerCache.get(ownerName);if(cached){return cached}const logger=new ZenFluxLogger(owner,options);loggerCache.set(ownerName,logger);return logger};
|
|
52
|
+
|
|
53
|
+
class Commands extends ObjectBase{static trace=[];current={};currentArgs={};trace=[];commands={};onBeforeHooks={};onBeforeUIHooks={};onAfterHooks={};onAfterOnceHooks={};onAfterUIHooks={};onAfterAffectHooks={};logger;static getName(){return "ZenFlux/Core/Managers/Commands"}static async runCallbacks(callbacks,args={},options={}){const callbacksLength=callbacks?.length||0;for(let i=0;i<callbacksLength;++i){const callback=options.pop===true?callbacks.pop():callbacks[i];if(!callback){throw new Error("Callback is not defined.")}await callback(args,options);}}static hookCommand(stack,hookCommand,context){if(!stack[hookCommand]){stack[hookCommand]=[];}stack[hookCommand].push(context);}constructor(){super();const type=this.constructor;this.logger=createLogger(type);this.logger.startsEmpty(this.constructor);}async run(command,args={},options={}){if(typeof command==="string"){command=this.getCommandInstance(command,args,options);}this.attachCurrent(command,args);const result=await this.runInstance(command,args,options);this.detachCurrent(command);return result}register(commands,controller){const result={};Object.values(commands).forEach(command=>{const commandName=command.getName();if(this.commands[commandName]){throw new CommandAlreadyRegistered(command)}command.setController(controller);this.commands[commandName]=command;result[commandName]=command;});return result}getAll(){return this.commands}getByName(name){return this.commands[name]}getLogger(){return this.logger}getCommandInstance(name,args={},options={}){const CommandClass=this.commands[name];if(!CommandClass){throw new CommandNotFound(name)}return new CommandClass(args,options)}onBefore(hookCommand,callback){Commands.hookCommand(this.onBeforeHooks,hookCommand,callback);}onBeforeUI(hookCommand,callback){Commands.hookCommand(this.onBeforeUIHooks,hookCommand,callback);}onAfter(hookCommand,callback){Commands.hookCommand(this.onAfterHooks,hookCommand,callback);}onAfterUI(command,callback){Commands.hookCommand(this.onAfterUIHooks,command,callback);}onAfterOnce(command,callback){Commands.hookCommand(this.onAfterOnceHooks,command,callback);}onAfterAffect(hookCommand,affectCommand){Commands.hookCommand(this.onAfterAffectHooks,hookCommand,affectCommand);}onBeforeRun(command,args={},options={}){if(this.onBeforeHooks[command.getName()]){const callbacks=this.onBeforeHooks[command.getName()];callbacks.forEach(callback=>callback(args,options));}if(this.onBeforeUIHooks[command.getName()]){const callbacks=this.onBeforeUIHooks[command.getName()];callbacks.forEach(callback=>callback(args,options));}}async runInstance(command,args={},options={}){let result=null;this.logger.startsWith(this.runInstance,{command:command.getName(),options,args});this.onBeforeRun(command,args,options);result=await command.run();await this.onAfterRun(command,args,options,result);return result}async onAfterRun(command,args,options,result){options=Object.assign({},options);if(this.onAfterAffectHooks[command.getName()]){this.onAfterAffectHooks[command.getName()].forEach(command=>{args.result=result;result=this.run(command.toString(),args,options);});result=await result;}if(this.onAfterHooks){args.result=result;await Commands.runCallbacks(Object.assign([],this.onAfterHooks[command.getName()]),args,options);}if(this.onAfterOnceHooks){await Commands.runCallbacks(this.onAfterOnceHooks[command.getName()],args,{...options,pop:true});}if(this.onAfterUIHooks){Commands.runCallbacks(Object.assign([],this.onAfterUIHooks[command.getName()]),args,options);}return result}attachCurrent(command,args={}){this.current[command.getName()]=command;this.currentArgs[command.getName()]=args;this.trace.push(command.getName());Commands.trace.push(command.getName());}detachCurrent(command){delete this.current[command.getName()];delete this.currentArgs[command.getName()];Commands.trace.pop();this.trace.pop();}}
|
|
24
54
|
|
|
25
55
|
class Controllers extends ObjectBase{controllers={};constructor(){super();}static getName(){return "ZenFlux/Core/Managers/Controllers"}get(name){return this.controllers[name]}getAll(){return this.controllers}register(controller){if(this.controllers[controller.getName()]){throw new ControllerAlreadyRegistered(controller)}this.controllers[controller.getName()]=controller;return controller}}
|
|
26
56
|
|
|
@@ -53,36 +83,6 @@ get restful () { return restful; }
|
|
|
53
83
|
|
|
54
84
|
class ControllerBase extends ObjectBase{commands;restful;internal;static getName(){return "ZenFlux/Core/ControllerBase"}constructor(){super();this.initialize();}initialize(){this.register();this.setupHooks&&this.setupHooks();}register(){this.commands=commands.register(this.getCommands(),this);this.restful=restful.register(this.getRestful(),this);this.internal=internal.register(this.getInternal(),this);}getCommands(){return {}}getRestful(){return {}}getInternal(){return {}}setupHooks(){}}
|
|
55
85
|
|
|
56
|
-
const DEFAULT_LOG_LEVEL="5";function getEnvVar(key){if(typeof process!=="undefined"&&process?.env){return process.env[key]??process.env[`VITE_${key}`]}if(typeof import.meta!=="undefined"&&import.meta.env){const env=import.meta.env;return env[key]??env[`VITE_${key}`]}return undefined}function getLoggerDefaultLevel(){return DEFAULT_LOG_LEVEL}function getLoggerLogLevel(){const raw=getEnvVar("LOGGER_LOG_LEVEL");return parseInt(raw??DEFAULT_LOG_LEVEL,10)}function getLoggerTimeFormat(){return (getEnvVar("LOGGER_TIME_FORMAT")||"").trim()}function getLoggerLogLevelString(){switch(getLoggerLogLevel()){case 0:return "NONE";case 1:return "ERROR";case 2:return "WARN";case 3:return "ADMIN";case 4:return "INFO";case 5:return "LOG";case 6:return "DEBUG";default:return "UNKNOWN"}}function isLoggerDebugEnabled(){return getLoggerLogLevel()>=6}function isLoggerDisabled(){return getEnvVar("LOGGER_DISABLED")==="true"}function isLoggerPreviousSourceDisabled(){return getEnvVar("LOGGER_LOG_PREVIOUS_CALLER_SOURCE_DISABLED")==="true"}
|
|
57
|
-
|
|
58
|
-
var commonjsGlobal=typeof globalThis!=="undefined"?globalThis:typeof window!=="undefined"?window:typeof global!=="undefined"?global:typeof self!=="undefined"?self:{};function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x["default"]:x}function getDefaultExportFromNamespaceIfPresent(n){return n&&Object.prototype.hasOwnProperty.call(n,"default")?n["default"]:n}function getDefaultExportFromNamespaceIfNotNamed(n){return n&&Object.prototype.hasOwnProperty.call(n,"default")&&Object.keys(n).length===1?n["default"]:n}function getAugmentedNamespace(n){if(Object.prototype.hasOwnProperty.call(n,"__esModule"))return n;var f=n.default;if(typeof f=="function"){var a=function a(){var isInstance=false;try{isInstance=this instanceof a;}catch{}if(isInstance){return Reflect.construct(f,arguments,this.constructor)}return f.apply(this,arguments)};a.prototype=f.prototype;}else a={};Object.defineProperty(a,"__esModule",{value:true});Object.keys(n).forEach(function(k){var d=Object.getOwnPropertyDescriptor(n,k);Object.defineProperty(a,k,d.get?d:{enumerable:true,get:function(){return n[k]}});});return a}
|
|
59
|
-
|
|
60
|
-
var picocolors$1={exports:{}};
|
|
61
|
-
|
|
62
|
-
var picocolors=picocolors$1.exports;var hasRequiredPicocolors;function requirePicocolors(){if(hasRequiredPicocolors)return picocolors$1.exports;hasRequiredPicocolors=1;let p=process||{},argv=p.argv||[],env=p.env||{};let isColorSupported=!(!!env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p.platform==="win32"||(p.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI);let formatter=(open,close,replace=open)=>input=>{let string=""+input,index=string.indexOf(close,open.length);return ~index?open+replaceClose(string,close,replace,index)+close:open+string+close};let replaceClose=(string,close,replace,index)=>{let result="",cursor=0;do{result+=string.substring(cursor,index)+replace;cursor=index+close.length;index=string.indexOf(close,cursor);}while(~index)return result+string.substring(cursor)};let createColors=(enabled=isColorSupported)=>{let f=enabled?formatter:()=>String;return {isColorSupported:enabled,reset:f("\x1b[0m","\x1b[0m"),bold:f("\x1b[1m","\x1b[22m","\x1b[22m\x1b[1m"),dim:f("\x1b[2m","\x1b[22m","\x1b[22m\x1b[2m"),italic:f("\x1b[3m","\x1b[23m"),underline:f("\x1b[4m","\x1b[24m"),inverse:f("\x1b[7m","\x1b[27m"),hidden:f("\x1b[8m","\x1b[28m"),strikethrough:f("\x1b[9m","\x1b[29m"),black:f("\x1b[30m","\x1b[39m"),red:f("\x1b[31m","\x1b[39m"),green:f("\x1b[32m","\x1b[39m"),yellow:f("\x1b[33m","\x1b[39m"),blue:f("\x1b[34m","\x1b[39m"),magenta:f("\x1b[35m","\x1b[39m"),cyan:f("\x1b[36m","\x1b[39m"),white:f("\x1b[37m","\x1b[39m"),gray:f("\x1b[90m","\x1b[39m"),bgBlack:f("\x1b[40m","\x1b[49m"),bgRed:f("\x1b[41m","\x1b[49m"),bgGreen:f("\x1b[42m","\x1b[49m"),bgYellow:f("\x1b[43m","\x1b[49m"),bgBlue:f("\x1b[44m","\x1b[49m"),bgMagenta:f("\x1b[45m","\x1b[49m"),bgCyan:f("\x1b[46m","\x1b[49m"),bgWhite:f("\x1b[47m","\x1b[49m"),blackBright:f("\x1b[90m","\x1b[39m"),redBright:f("\x1b[91m","\x1b[39m"),greenBright:f("\x1b[92m","\x1b[39m"),yellowBright:f("\x1b[93m","\x1b[39m"),blueBright:f("\x1b[94m","\x1b[39m"),magentaBright:f("\x1b[95m","\x1b[39m"),cyanBright:f("\x1b[96m","\x1b[39m"),whiteBright:f("\x1b[97m","\x1b[39m"),bgBlackBright:f("\x1b[100m","\x1b[49m"),bgRedBright:f("\x1b[101m","\x1b[49m"),bgGreenBright:f("\x1b[102m","\x1b[49m"),bgYellowBright:f("\x1b[103m","\x1b[49m"),bgBlueBright:f("\x1b[104m","\x1b[49m"),bgMagentaBright:f("\x1b[105m","\x1b[49m"),bgCyanBright:f("\x1b[106m","\x1b[49m"),bgWhiteBright:f("\x1b[107m","\x1b[49m")}};picocolors$1.exports=createColors();picocolors$1.exports.createColors=createColors;return picocolors$1.exports}
|
|
63
|
-
|
|
64
|
-
var picocolorsExports=requirePicocolors();var pc = getDefaultExportFromCjs(picocolorsExports);
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* Reduce circular references.
|
|
68
|
-
*
|
|
69
|
-
* @copyright https://stackoverflow.com/a/53731154
|
|
70
|
-
*/const reduceCircularReferences=()=>{const seen=new WeakSet;return (key,value)=>{if(typeof value==="object"&&value!==null){if(seen.has(value)){return}seen.add(value);}return value}};
|
|
71
|
-
|
|
72
|
-
/**
|
|
73
|
-
* Function hexColorDelta() : Return color difference in ratio decimal point.
|
|
74
|
-
*
|
|
75
|
-
* @copyright http://jsfiddle.net/96sME/
|
|
76
|
-
*/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};
|
|
77
|
-
|
|
78
|
-
const MAX_MAPPING_RECURSIVE_DEPTH=4,UNKNOWN_CALLER_NAME="anonymous function";Error.stackTraceLimit=50;class LoggerBrowserInfra extends ObjectBase{static mappers=[];static mapperDepth=0;static colorsOwners={};static colorsUsed=[];static outputSubscribers=new Set;defaultStyle;owner;args;color;outputHandler=console.log;pendingOutputMetadata;static getName(){return "ZenFlux/Logging/Modules/LoggerBrowserInfra"}static reset(){LoggerBrowserInfra.mappers=[];LoggerBrowserInfra.mapperDepth=0;LoggerBrowserInfra.colorsUsed=[];LoggerBrowserInfra.colorsOwners={};LoggerBrowserInfra.outputSubscribers.clear();}static attachOutputSubscriber(subscriber){LoggerBrowserInfra.outputSubscribers.add(subscriber);return ()=>{LoggerBrowserInfra.outputSubscribers.delete(subscriber);}}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.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);if(LoggerBrowserInfra.outputSubscribers.size===0){return}const event={logger:this,namespace:this.getOwnerName(),args,metadata:this.pendingOutputMetadata};LoggerBrowserInfra.outputSubscribers.forEach(subscriber=>{try{subscriber(event);}catch(error){console.error("[ZenFlux][Logger] output subscriber failed",error);}});}setOutputHandler(outputHandler){this.outputHandler=outputHandler;}runWithOutputMetadata(metadata,callback){const previous=this.pendingOutputMetadata;this.pendingOutputMetadata=metadata;try{return callback()}finally{this.pendingOutputMetadata=previous;}}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 color="#";for(let i=0;i<6;i++){color+=hex[Math.floor(Math.random()*16)];}return color}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}}
|
|
79
|
-
|
|
80
|
-
let SimpleEventEmitter=class SimpleEventEmitter{listeners=new Map;on(event,callback){if(!this.listeners.has(event)){this.listeners.set(event,new Set);}this.listeners.get(event).add(callback);}off(event,callback){this.listeners.get(event)?.delete(callback);}emit(event,...args){const callbacks=this.listeners.get(event);if(!callbacks||callbacks.size===0){return false}callbacks.forEach(cb=>cb(...args));return true}removeAllListeners(event){this.listeners.delete(event);}eventNames(){return Array.from(this.listeners.keys())}};class EventBus extends ObjectBase{static instance=null;objects=new Map;eventEmitter=new SimpleEventEmitter;lastEmittedEvents=new Map;static getName(){return "ZenFlux/Core/Modules/EventBus"}static getInstance(){if(!EventBus.instance){EventBus.instance=new EventBus;}return EventBus.instance}static get $(){return EventBus.getInstance()}getObjectNames(){return Array.from(this.objects.keys())}getEventNames(){this.eventEmitter.eventNames();}getEventName(objectName,methodName){return `${objectName}::${methodName}`}on(objectName,methodName,callback){if(!this.objects.has(objectName)){throw new Error(`Object ${objectName} is not registered`)}this.eventEmitter.on(this.getEventName(objectName,methodName),callback);}onCalledBeforeDoInvoke(objectName,methodName,callback){this.on(objectName,methodName,callback);if(this.objects.has(objectName)){const objectEntry=this.objects.get(objectName);if(objectEntry){const method=objectEntry.methods.find(method=>method.name===methodName);if(method&&this.lastEmittedEvents.has(this.getEventName(objectName,methodName))){callback(...this.lastEmittedEvents.get(this.getEventName(objectName,methodName)));}}}}off(objectName,methodName,callback){this.eventEmitter.off(this.getEventName(objectName,methodName),callback);}register(object,methods){if(this.objects.has(object.getName())){throw new Error(`Error in: '${this.getName()}', object: '${object.getName()}' is already registered`)}this.objects.set(object.getName(),{object,methods});this.hook(object,methods);}registerMultiInstances(object,methods){const objectName=object.getName();if(this.objects.has(objectName)){const existingEntry=this.objects.get(objectName);if(Array.isArray(existingEntry.object)){existingEntry.object.push(object);}else {existingEntry.object=[existingEntry.object,object];}}else {this.objects.set(objectName,{object,methods});}this.hook(object,methods);}unregister(objectName){const entry=this.objects.get(objectName);if(!entry){return false}if(Array.isArray(entry.object)){entry.object.forEach(obj=>{this.unhookObject(obj,entry.methods);});}else {this.unhookObject(entry.object,entry.methods);}this.objects.delete(objectName);}unhookObject(object,methods){methods.forEach(method=>{this.ensureFunction(object,method);this.eventEmitter.removeAllListeners(this.getEventName(object.getName(),method.name));object[method.name]=method;});}unhook(entry){if(Array.isArray(entry.object)){entry.object.forEach(obj=>{this.unhookObject(obj,entry.methods);});}else {this.unhookObject(entry.object,entry.methods);}}emit(object,method,...args){const eventName=this.getEventName(object.getName(),method.name);this.lastEmittedEvents.set(eventName,args);return this.eventEmitter.emit(eventName,...args)}hook(object,methods){methods.forEach(method=>{this.ensureFunction(object,method);const originalMethod=method;const eventBusHook=async(...args)=>{const result=await originalMethod.apply(object,args);this.emit(object,method,...args);return result};object[method.name]=new Proxy(eventBusHook,{get(target,prop){if(prop==="name"){return method.name}return target[prop]}});});}ensureFunction(object,method){if("function"!==typeof method){throw new Error(`Method ${method} is not a function on ${object.getName()}`)}}}
|
|
81
|
-
|
|
82
|
-
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 LEVEL_LABELS={log:"LOG",info:"INFO",debug:"DEBUG",warn:"WARN",error:"ERROR",admin:"ADMIN"};const registeredNames={};class Logger extends LoggerBrowserInfra{static lastLogTime=Date.now();static timestampFormat=getLoggerTimeFormat();ownerName;messagePrefixes=[];config={};static setTimestampFormat(format){Logger.timestampFormat=(format||"").trim();}static getTimestampFormat(){return Logger.timestampFormat}static getName(){return "ZenFlux/Core/Modules/Logger"}static getLogLevelString(){return getLoggerLogLevelString()}static getLogLevel(){return getLoggerLogLevel()}static attachOutputListener(listener){return LoggerBrowserInfra.attachOutputSubscriber(listener)}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("log",DEFAULT_LOG_PREFIX,caller,message,...params);}info(caller,message,...params){this.writeLog("info",DEFAULT_INFO_PREFIX,caller,message,...params);}debug(caller,message,...params){this.writeLog("debug",DEFAULT_DEBUG_PREFIX,caller,message,...params);}warn(caller,message,...params){this.writeLog("warn",DEFAULT_WARN_PREFIX,caller,message,...params);}error(caller,message,...params){this.writeLog("error",DEFAULT_ERROR_PREFIX,caller,message,...params);}admin(caller,message,...params){this.writeLog("admin",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(level,prefix,caller,message,...params){const callerName=this.getCallerName(caller);const source=this.getPreviousSource()+pc.white(`${this.ownerName}::${callerName}`);let messagePrefix="";if(this.messagePrefixes.length){messagePrefix=`[${this.messagePrefixes.join("][")}]`;}const timestampValue=Date.now();const timeDiff=(timestampValue-Logger.lastLogTime).toString().padStart(4,"0");const timeFormat=Logger.getTimestampFormat();const timestamp=timeFormat?this.formatTime(new Date(timestampValue),timeFormat):"";this.outputEvent(prefix,timeDiff,source,messagePrefix,message,params);const timestampPart=timestamp?`${timestamp} `:"";const output=`${timestampPart}${prefix}[+${timeDiff}ms][${source}]${messagePrefix}: ${message}`;const formatted=this.createBrowserFormat(level,callerName,messagePrefix,message);const metadata={id:`${timestampValue}-${Math.random().toString(16).slice(2)}`,level,namespace:this.ownerName,callerName,message,messagePrefix,payload:params.length===0?undefined:params.length===1?params[0]:params,timestamp:timestampValue,formatted};this.runWithOutputMetadata(metadata,()=>{this.output(output,...params);});Logger.lastLogTime=timestampValue;}createBrowserFormat(level,callerName,messagePrefix,message){const prefixLabel=LEVEL_LABELS[level]||level.toUpperCase();const prefixPart=messagePrefix?`${messagePrefix} `:"";return {format:`%c(${prefixLabel})-> %c%c${this.ownerName}%c::%c${callerName}%c() ${prefixPart}${message}%c`,styles:[...this.defaultStyle]}}formatTime(date,format){const pad=(num,size=2)=>num.toString().padStart(size,"0");const tokens={"YYYY":date.getFullYear().toString(),"Y":date.getFullYear().toString(),"M":pad(date.getMonth()+1),"D":pad(date.getDate()),"HH":pad(date.getHours()),"hh":pad(date.getHours()),"mm":pad(date.getMinutes()),"ss":pad(date.getSeconds()),"SSS":pad(date.getMilliseconds(),3),"S":pad(date.getMilliseconds(),3)};return format.replace(/YYYY|HH|hh|mm|ss|SSS|Y|M|D|S|h|m|s/g,token=>tokens[token]??token)}}
|
|
83
|
-
|
|
84
|
-
class ZenFluxLogger extends Logger{}const loggerCache=new Map;const resolveOwnerName=owner=>{if(typeof owner==="string"){return owner}if(owner&&typeof owner.getName==="function"){return owner.getName()}return "UnknownOwner"};const createLogger=(owner,options)=>{const ownerName=resolveOwnerName(owner);const cached=loggerCache.get(ownerName);if(cached){return cached}const logger=new ZenFluxLogger(owner,options);loggerCache.set(ownerName,logger);return logger};
|
|
85
|
-
|
|
86
86
|
class InitializeBase extends ObjectBase{logger;constructor(shouldInitialize=true){super();this.logger=new Logger(this);if(this.initialize&&shouldInitialize){this.initialize();}}debounce(func,delay){let timeoutId;return (...args)=>{clearTimeout(timeoutId);timeoutId=setTimeout(()=>{func.apply(this,args);},delay);}}}
|
|
87
87
|
|
|
88
88
|
class SingletonBase extends InitializeBase{static instances=new Map;constructor(){super();}static getInstance(){if(!SingletonBase.instances.has(this)){SingletonBase.instances.set(this,new this);}return SingletonBase.instances.get(this)}}
|
|
@@ -102,7 +102,7 @@ ObjectBase: ObjectBase,
|
|
|
102
102
|
SingletonBase: SingletonBase
|
|
103
103
|
});
|
|
104
104
|
|
|
105
|
-
class CommandBase extends ObjectBase{static controller;args={};options={};logger;static getName(){return "ZenFlux/Core/CommandBases/CommandBase"}static setController(controller){if(this.controller){throw new ControllerAlreadySet(this.controller)}this.controller=controller;}static getController(){return this.controller}constructor(args={},options={}){super();const type=this.constructor;this.logger=
|
|
105
|
+
class CommandBase extends ObjectBase{static controller;args={};options={};logger;static getName(){return "ZenFlux/Core/CommandBases/CommandBase"}static setController(controller){if(this.controller){throw new ControllerAlreadySet(this.controller)}this.controller=controller;}static getController(){return this.controller}constructor(args={},options={}){super();const type=this.constructor;this.logger=createLogger(type);this.logger.startsWith(this.constructor,{args,options});this.initialize(args,options);}initialize(args,options){this.args=args;this.options=options;}apply(args=this.args,options=this.options){throw new ForceMethodImplementation(this,"apply")}async run(){return this.runInternal()}async runInternal(){this.onBeforeApply&&this.onBeforeApply();const result=await this.apply(this.args,this.options);this.onAfterApply&&this.onAfterApply();return result}}
|
|
106
106
|
|
|
107
107
|
class CommandPublic extends CommandBase{static getName(){return "ZenFlux/Core/CommandBases/CommandPublic"}}
|
|
108
108
|
|
|
@@ -142,12 +142,12 @@ createLogger: createLogger
|
|
|
142
142
|
|
|
143
143
|
var _package = {
|
|
144
144
|
"name": "@zenflux/core",
|
|
145
|
-
"version": "0.1.
|
|
145
|
+
"version": "0.1.30",
|
|
146
146
|
"types": "dist/zenflux-core.d.ts",
|
|
147
147
|
"type": "module",
|
|
148
148
|
"files": [
|
|
149
149
|
"dist",
|
|
150
|
-
"
|
|
150
|
+
"src"
|
|
151
151
|
],
|
|
152
152
|
"scripts": {
|
|
153
153
|
"@z-core--test": "jest",
|
|
@@ -190,10 +190,10 @@ var _package = {
|
|
|
190
190
|
}
|
|
191
191
|
};
|
|
192
192
|
const name = "@zenflux/core";
|
|
193
|
-
const version = "0.1.
|
|
193
|
+
const version = "0.1.30";
|
|
194
194
|
const types = "dist/zenflux-core.d.ts";
|
|
195
195
|
const type = "module";
|
|
196
|
-
const files = ["dist","
|
|
196
|
+
const files = ["dist","src"];
|
|
197
197
|
const scripts = {"@z-core--test":"jest","@z-core--build":"@z-cli @build","@z-core--dev":"@z-cli @watch --dev"};
|
|
198
198
|
const exports$1 = {".":{"import":"./dist/zenflux-core.mjs","default":"./dist/zenflux-core.cjs","require":"./dist/zenflux-core.mjs.js","types":"./dist/zenflux-core.d.ts"},"./dist/src/*":"./src/*","./src/*.ts":"./src/*.ts","./src/*":"./src/*.ts","./src/bases":"./src/bases/index.ts","./src/bases/*":"./src/bases/*.ts","./src/clients":"./src/clients/index.ts","./src/command-bases":"./src/command-bases/index.ts","./src/errors":"./src/errors/index.ts","./src/interfaces":"./src/interfaces/index.ts","./src/managers":"./src/managers/index.ts","./src/modules/logger":"./src/modules/logger/index.ts","./src/modules/*":"./src/modules/*.ts","./package.json":"./package.json"};
|
|
199
199
|
const devDependencies = {"@jest/globals":"^29.7.0","@zenflux/cli":"workspace:*"};
|
package/package.json
CHANGED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { InitializeBase } from "@zenflux/core/src/bases/initialize-base";
|
|
2
|
+
import { Debugger } from "@zenflux/core/src/modules/debugger";
|
|
3
|
+
|
|
4
|
+
export abstract class CacheBase<CacheResult> extends InitializeBase {
|
|
5
|
+
private readonly cache: Map<string, CacheResult>;
|
|
6
|
+
|
|
7
|
+
private cacheDebugger: Debugger;
|
|
8
|
+
|
|
9
|
+
protected constructor( shouldDebugCache = true ) {
|
|
10
|
+
super();
|
|
11
|
+
|
|
12
|
+
this.cacheDebugger = new Debugger( this, undefined, shouldDebugCache );
|
|
13
|
+
|
|
14
|
+
this.cache = new Map<string, CacheResult>();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
protected getCache( key: string ) {
|
|
18
|
+
this.cacheDebugger.log( this.getCache, `Getting cache for key: '${ key }'` );
|
|
19
|
+
|
|
20
|
+
const result = this.cache.get( key );
|
|
21
|
+
|
|
22
|
+
if ( result ) {
|
|
23
|
+
this.cacheDebugger.log( this.getCache, `Got cache for key: '${ key }'` );
|
|
24
|
+
this.cacheDebugger.dumpDown( this.setCache, result );
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
return result;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
protected getCacheMap() {
|
|
31
|
+
return this.cache;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
protected setCache( key: string, value: CacheResult ): void {
|
|
35
|
+
this.cacheDebugger.log( this.setCache, `Setting cache for key: '${ key }'` );
|
|
36
|
+
|
|
37
|
+
this.cacheDebugger.dumpDown( this.setCache, value );
|
|
38
|
+
|
|
39
|
+
this.cache.set( key, value );
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
protected deleteCache( key: string ): boolean {
|
|
43
|
+
this.cacheDebugger.log( this.deleteCache, `Deleting cache for key: '${ key }'` );
|
|
44
|
+
|
|
45
|
+
if ( !this.cache.has( key ) ) {
|
|
46
|
+
this.cacheDebugger.log( this.deleteCache, `Cache for key: '${ key }' does not exist` );
|
|
47
|
+
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return this.cache.delete( key );
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
protected deleteCacheWithPrefix( prefix: string ): void {
|
|
55
|
+
this.cacheDebugger.log( this.deleteCacheWithPrefix, `Deleting cache prefix: '${ prefix }'` );
|
|
56
|
+
|
|
57
|
+
for ( const key of this.cache.keys() ) {
|
|
58
|
+
if ( key.startsWith( prefix ) ) {
|
|
59
|
+
this.deleteCache( key );
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|