node-universe
Version:
基于 Nodejs 环境的一款微服务框架,原理来自于宇宙中的恒星,行星,卫星等系统。
1 lines • 340 kB
JavaScript
import e from"path";import t from"fs";import s from"os";import r from"kleur";import i,{pick as n,random as o,flatten as a,defaultsDeep as l,isObject as c}from"lodash";import h from"eventemitter3";import d,{format as u}from"util";import p from"log4js";import v from"pino";import g from"http";import m from"zlib";import E from"node-fetch";import f from"dgram";import S from"v8";import{monitorEventLoopDelay as T}from"monitor-event-loop-delay";import{PerformanceObserver as _,performance as I}from"perf_hooks";import y from"recursive-watch";import{Etcd3 as N}from"etcd3";import R from"ioredis";import{Encoder as b}from"cbor-x";import A from"notepack.io";import{LRUCache as O}from"lru-cache";import P from"crypto";import C from"redlock";import{Transform as D,Writable as w}from"stream";import U from"nats";import L from"mqtt";import{Kafka as k}from"kafkajs";import M from"events";import $ from"ipaddr.js";import V from"net";import x from"fastest-validator";import{glob as H}from"glob";var G,q,j,B="close",F="half_open",Y="half_open_wait",K="open",z="failedProcessingPacket",Q="failedSendRequestPacket",W="failedSendEventPacket",Z="failedSendResponsePacket",J="failedNodesDiscovery",X="failedNodeDiscovery",ee="failedSendInfoPacket",te="failedSendPingPacket",se="failedSendHeartbeatPacket",re="failedServicesStop",ie="failedServiceLoad",ne="failedServiceRestart",oe="failedServiceDestruction",ae="clientError",le="failedSendPing",ce="publisherError",he="failedTopicCreation";class de extends Error{constructor(e=""){super(e),Object.defineProperty(this,"message",{configurable:!0,enumerable:!1,value:e,writable:!0}),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:this.constructor.name,writable:!0}),Object.prototype.hasOwnProperty.call(Error,"captureStackTrace")?Error.captureStackTrace(this,this.constructor):Object.defineProperty(this,"stack",{configurable:!0,enumerable:!1,value:new Error(e).stack,writable:!0})}}function ue(e,t,s=Promise){return t?s.allSettled(e):s.all(e)}function pe(e=1e3){let t=null,s=Date.now();return new Promise(((r,i)=>{t=setInterval((()=>{s+e<Date.now()&&(clearInterval(t),t=null,r(!0))}),10)}))}function ve(){const e=(new Date).getMilliseconds();return e<10?`00${e}`:e>=10&&e<100?`0${e}`:`${e}`}function ge(e){return t=e,function(...e){return new Promise(((s,r)=>{try{s(t.apply(this,e))}catch(e){r(e)}}))};var t}function me(e){if("function"!=typeof e)throw new TypeError("Expected a function");const t=["`",'"',"'"],s=e.toString().replace(/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/gm,"");let r="",i=0,n=0;for(;n<s.length&&")"!==s.charAt(n);n+=1){if(s.startsWith("=>",n)){r=s,n=s.length;break}if("="===s.charAt(n)){for(;n<s.length&&(","!==s.charAt(n)&&")"!==s.charAt(n)||0!==i);n+=1){let e=!1;for(const r of t)if(s.charAt(n)===r){for(n+=1;n<s.length&&s.charAt(n)!==r;)n+=1;e=!0;break}if(!e)switch(s.charAt(n)){case"(":case"[":case"{":i+=1;break;case")":case"]":case"}":i-=1}}if(","===s.charAt(n)&&(r+=","),")"===s.charAt(n)){r+=")";break}}else r+=s.charAt(n)}n<s.length&&")"===s.charAt(n)&&(r+=")");const o=/^(?:async)?([^=()]+)=|\(([^)]+)\)/.exec(r);return o?(o[1]||o[2]).split(",").map((e=>e.trim())).filter(Boolean):[]}function Ee(e){return e.length>0&&-1!==["ctx","context"].indexOf(e[0].toLowerCase())}function fe(e){Object.keys(require.cache).forEach((t=>{t===e&&delete require.cache[t]}))}class Se{static hasComplexStructure(e){if(!Je(e))return!1;for(const t in e){const s=e[t];if(Je(s)||Array.isArray(s))return!0}return!1}static smartClone(e){return Je(e)?this.hasComplexStructure(e)?i.cloneDeep(e):{...e}:e}static structuredClone(e,t=!0){if(!Je(e))return e;const s={};for(const r in e){const n=e[r];t&&et(n)?s[r]=n:Je(n)||Array.isArray(n)?s[r]=i.cloneDeep(n):s[r]=n}return s}}!function(e){e.BAD_GETWAY="BAD_GETWAY",e.SERVICE_NOT_FOUND="SERVICE_NOT_FOUND",e.SERVICE_NOT_AVAILABLE="SERVICE_NOT_AVAILABLE",e.REQUEST_TIMEOUT="REQUEST_TIMEOUT",e.REQUEST_SKIPPED="REQUEST_SKIPPED",e.REQUEST_REJECTED="REQUEST_REJECTED",e.QUEUE_FULL="QUEUE_FULL",e.VALIDATION_ERROR="VALIDATION_ERROR",e.MAX_CALL_LEVEL="MAX_CALL_LEVEL",e.SERVICE_SCHEMA_ERROR="SERVICE_SCHEMA_ERROR",e.STAR_OPTIONS_ERROR="STAR_OPTIONS_ERROR",e.GRACEFUL_STOP_TIMEOUT="GRACEFUL_STOP_TIMEOUT",e.PROTOCOL_VERSION_MISMATCH="PROTOCOL_VERSION_MISMATCH",e.INVALID_PACKET_DATA="INVALID_PACKET_DATA",e.MISSING_PAYLOAD="MISSING_PAYLOAD",e.INVALID_ENDPOINT="INVALID_ENDPOINT",e.INVALID_PARAMETERS="INVALID_PARAMETERS",e.METRICS_DISABLED="METRICS_DISABLED",e.NOT_FOUND_EVENT="NOT_FOUND_EVENT",e.WAITFOR_SERVICES="WAITFOR_SERVICES"}(G||(G={})),function(e){e.UniverseError="UniverseError",e.UniverseRetryableError="UniverseRetryableError",e.StarDisconnectedError="StarDisconnectedError",e.StarServerError="StarServerError",e.StarClientError="StarClientError",e.ServiceNotFoundError="ServiceNotFoundError",e.ServiceNotAvailableError="ServiceNotAvailableError",e.RequestTimeoutError="RequestTimeoutError",e.RequestSkippedError="RequestSkippedError",e.RequestRejectedError="RequestRejectedError",e.QueueIsFullError="QueueIsFullError",e.ValidationError="ValidationError",e.MaxCallLevelError="MaxCallLevelError",e.ServiceSchemaError="ServiceSchemaError",e.StarOptionsError="StarOptionsError",e.GracefulStopTimeoutError="GracefulStopTimeoutError",e.ProtocolVersionMismatchError="ProtocolVersionMismatchError",e.InvalidPacketDataError="InvalidPacketDataError"}(q||(q={})),function(e){e[e.RESPONSE_ERROR=400]="RESPONSE_ERROR",e[e.SERVICE_NOT_FOUND=404]="SERVICE_NOT_FOUND",e[e.VALIDATION_ERROR=422]="VALIDATION_ERROR",e[e.QUEUE_FULL=429]="QUEUE_FULL",e[e.SERVICE_ERROR=500]="SERVICE_ERROR",e[e.BAD_GETWAY=502]="BAD_GETWAY",e[e.REQUEST_REJECTED=503]="REQUEST_REJECTED",e[e.REQUEST_TIMEOUT=504]="REQUEST_TIMEOUT",e[e.REQUEST_SKIPPED=514]="REQUEST_SKIPPED"}(j||(j={}));class Te extends de{constructor(e,t,s,r){super(e),this.code=t||j.BAD_GETWAY,this.type=s||G.BAD_GETWAY,this.data=r,this.retryable=!1}}class _e extends Te{constructor(e,t,s,r){super(e,t,s,r),this.retryable=!0}}class Ie extends _e{constructor(){super("The star's transporter has disconnected. Please try again when a connection is reestablished.",502,G.BAD_GETWAY),this.stack=""}}class ye extends _e{}class Ne extends Te{constructor(e,t,s,r){super(e,t||j.RESPONSE_ERROR,s,r)}}class Re extends _e{constructor(e={}){let t="";(null==e?void 0:e.nodeID)&&(null==e?void 0:e.action)?t=`Service '${null==e?void 0:e.action}' is not found on '${null==e?void 0:e.nodeID}' node.`:(null==e?void 0:e.action)&&(t=`Service '${null==e?void 0:e.action}' is not found.`),(null==e?void 0:e.service)&&(null==e?void 0:e.version)?t=`Service '${null==e?void 0:e.version}.${null==e?void 0:e.service}' not found.`:(null==e?void 0:e.service)&&(t=`Service '${null==e?void 0:e.service}' not found.`),super(t,j.SERVICE_NOT_FOUND,G.SERVICE_NOT_FOUND,e)}}class be extends _e{constructor(e={}){let t="";t=(null==e?void 0:e.nodeID)?`Service '${null==e?void 0:e.action}' is not available on '${null==e?void 0:e.nodeID}' node.`:`Service '${null==e?void 0:e.action}' is not available.`,super(t,j.SERVICE_NOT_FOUND,G.SERVICE_NOT_AVAILABLE,e)}}class Ae extends _e{constructor(e={}){super(`Request is timed out when call '${null==e?void 0:e.action}' action on '${null==e?void 0:e.nodeID}' node.`,j.REQUEST_TIMEOUT,G.REQUEST_TIMEOUT,e)}}class Oe extends Te{constructor(e={}){super(`Calling '${e.action}' is skipped because timeout reached on '${e.nodeID}' node.`,j.REQUEST_SKIPPED,G.REQUEST_SKIPPED,e),this.retryable=!1}}class Pe extends _e{constructor(e={}){super(`Request is rejected when call '${null==e?void 0:e.action}' action on '${null==e?void 0:e.nodeID}' node.`,j.REQUEST_REJECTED,G.REQUEST_REJECTED,e)}}class Ce extends _e{constructor(e={}){super(`Queue is full. Request '${null==e?void 0:e.action}' action on '${null==e?void 0:e.nodeID}' node is rejected.`,j.QUEUE_FULL,G.QUEUE_FULL,e)}}class De extends Ne{constructor(e,t,s){super(e,j.VALIDATION_ERROR,t||G.VALIDATION_ERROR,s)}}class we extends Te{constructor(e){super(`Request level is reached the limit (${null==e?void 0:e.level}) on '${null==e?void 0:e.nodeID}' node.`,j.SERVICE_ERROR,G.MAX_CALL_LEVEL,e),this.retryable=!1}}class Ue extends Te{constructor(e,t){super(e,j.SERVICE_ERROR,G.SERVICE_SCHEMA_ERROR,t)}}class Le extends Te{constructor(e,t){super(e,j.SERVICE_ERROR,G.STAR_OPTIONS_ERROR,t)}}class ke extends Te{constructor(e){e&&(null==e?void 0:e.service)?super(`Unable to stop '${null==e?void 0:e.service.name}' service gracefully.`,j.SERVICE_ERROR,G.GRACEFUL_STOP_TIMEOUT,e&&(null==e?void 0:e.service)?{name:null==e?void 0:e.service.name,version:null==e?void 0:e.service.version}:void 0):super("Unable to stop ServiceBroker gracefully.",j.SERVICE_ERROR,G.GRACEFUL_STOP_TIMEOUT)}}class Me extends Te{constructor(e){super("Protocol version mismatch.",j.SERVICE_ERROR,G.PROTOCOL_VERSION_MISMATCH,e)}}class $e extends Te{constructor(e){super("Invalid packet data.",j.SERVICE_ERROR,G.INVALID_PACKET_DATA,e)}}function Ve(e){switch(e.name){case q.UniverseError:return new Te(e.message,e.code,e.type,e.data);case q.UniverseRetryableError:return new _e(e.message,e.code,e.type,e.data);case q.StarServerError:return new ye(e.message,e.code,e.type,e.data);case q.StarClientError:return new Ne(e.message,e.code,e.type,e.data);case q.ValidationError:return new De(e.message,e.type,e.data);case q.ServiceNotFoundError:case q.ServiceNotAvailableError:case q.RequestSkippedError:case q.RequestRejectedError:case q.RequestTimeoutError:return new Re(e.data);case q.MaxCallLevelError:return new we(e.data);case q.QueueIsFullError:return new Ce(e.data);case q.GracefulStopTimeoutError:return new ke(e.data);case q.ProtocolVersionMismatchError:return new Me(e.data);case q.InvalidPacketDataError:return new $e(e.data);case q.ServiceSchemaError:return new Ue(e.message,e.data);case q.StarOptionsError:return new Le(e.message,e.data);case q.StarDisconnectedError:return new Ie}}class xe{constructor(){this.star=null}init(e){this.star=e}restore(e,t){let s=this.restoreCustomError(e,t);return s||(s=Ve(e)),s||(s=this.createDefaultError(e)),this.restoreExternalFields(e,s,t),this.restoreStack(e,s),s}extracPlainError(e,t){var s;return{name:e.name,message:e.message,nodeID:e.nodeID||t.nodeID||(null===(s=this.star)||void 0===s?void 0:s.nodeID),code:e.code,type:e.type,retryable:e.retryable,stack:e.stack,data:e.data}}restoreCustomError(e,t){}createDefaultError(e){const t=new Te(e.message);return t.name=e.name,t.code=e.code,t.type=e.type,t.data=e.data,t}restoreExternalFields(e,t,s){t.retryable=e.retryable,t.nodeID=e.nodeID||s.sender}restoreStack(e,t){e.stack&&(t.stack=e.stack)}}function He(e){return e instanceof xe?e:new xe}class Ge{static createServiceSchemaError(e,t={},s){const r=this.buildEnhancedMessage(e,t),i=new Ue(r,t);return s&&s.error("Service Schema Error:",{message:r,context:t,stack:i.stack}),i}static createUniverseError(e,t,s,r={},i){const n=this.buildEnhancedMessage(e,r),o={...r,timestamp:r.timestamp||Date.now(),errorType:this.ERROR_CONTEXT_MAP.get(s)||s},a=new Te(n,t,s,o);return i&&i.error("Universe Error:",{message:n,code:t,type:s,context:o,stack:a.stack}),a}static buildEnhancedMessage(e,t){let s=e;return t.serviceName&&(s+=` [服务: ${t.serviceName}]`),t.actionName&&(s+=` [动作: ${t.actionName}]`),t.eventName&&(s+=` [事件: ${t.eventName}]`),t.nodeId&&(s+=` [节点: ${t.nodeId}]`),t.expectedType&&void 0!==t.actualValue&&(s+=` [期望类型: ${t.expectedType}, 实际值: ${JSON.stringify(t.actualValue)}]`),t.suggestions&&t.suggestions.length>0&&(s+=`\n建议解决方案:\n${t.suggestions.map(((e,t)=>` ${t+1}. ${e}`)).join("\n")}`),s}static async safeExecute(e,t){try{return await e()}catch(e){throw this.enhanceExistingError(e,t)}}static enhanceExistingError(e,t){if(e instanceof Te||e instanceof Ue)return e;const s=`${t.operation}失败: ${e.message}`;t.logger&&t.logger.error("Enhanced Error:",{operation:t.operation,originalError:e.message,serviceName:t.serviceName,stack:e.stack});const r=new Error(s);return r.stack=e.stack,r.cause=e,r}static validateRequired(e,t,s={}){if(null==e)throw this.createServiceSchemaError(`必需参数 '${t}' 不能为空`,{...s,schemaProperty:t,actualValue:e,suggestions:[`请确保传入有效的 ${t} 参数`,`检查调用方法时是否遗漏了 ${t} 参数`,s.expectedType?`参数类型应为: ${s.expectedType}`:""].filter(Boolean)})}static validateType(e,t,s,r={}){const i=typeof e;if(i!==t)throw this.createServiceSchemaError(`参数 '${s}' 类型错误`,{...r,schemaProperty:s,expectedType:t,actualValue:e,suggestions:[`将 ${s} 转换为 ${t} 类型`,`当前类型: ${i}, 期望类型: ${t}`,"检查参数传递是否正确"]})}}Ge.ERROR_CONTEXT_MAP=new Map([["SERVICE_SCHEMA_ERROR","服务模式配置错误"],["SERVICE_NOT_FOUND","服务未找到"],["ACTION_NOT_FOUND","动作未找到"],["EVENT_NOT_FOUND","事件未找到"],["VALIDATION_ERROR","参数验证失败"],["TIMEOUT_ERROR","操作超时"],["DEPENDENCY_ERROR","依赖服务错误"]]);class qe{static validateServiceSchema(e){return!(!e||"object"!=typeof e)&&(!(!e.name||"string"!=typeof e.name)&&((void 0===e.version||"string"==typeof e.version)&&((void 0===e.settings||"object"==typeof e.settings&&null!==e.settings)&&((void 0===e.metadata||"object"==typeof e.metadata&&null!==e.metadata)&&(!!(void 0===e.mixins||Array.isArray(e.mixins)||"object"==typeof e.mixins&&null!==e.mixins)&&!(void 0!==e.dependencies&&!Array.isArray(e.dependencies)))))))}static validateMethodDefinition(e){return!(!e||"object"!=typeof e)&&("function"==typeof e.handler&&(void 0===e.params||"object"==typeof e.params&&null!==e.params))}static validateActionDefinition(e){return!(!e||"object"!=typeof e)&&("function"==typeof e.handler&&!(void 0!==e.visibility&&!["public","protected","private"].includes(e.visibility)))}static validateEventDefinition(e){if(!e||"object"!=typeof e)return!1;const t=e.handler;return!("function"!=typeof t&&!Array.isArray(t))&&!(Array.isArray(t)&&!t.every((e=>"function"==typeof e)))}static validateServiceName(e){if("string"!=typeof e||0===e.length)return!1;return/^[a-zA-Z0-9._$-]+$/.test(e)}static validateVersion(e){if("string"!=typeof e)return!1;return/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$/.test(e)}static deepValidateObject(e,t){if(!e||"object"!=typeof e)return!1;for(const[s,r]of Object.entries(t))if(void 0!==e[s]){if(typeof e[s]!==r)return!1}return!0}}class je{static validateServiceName(e){const t={isValid:!0,errors:[],warnings:[]};if("string"!=typeof e)return t.isValid=!1,t.errors.push("服务名称必须是字符串类型"),t;0===e.length?(t.isValid=!1,t.errors.push("服务名称不能为空")):e.length>100&&(t.isValid=!1,t.errors.push("服务名称长度不能超过100个字符"));return/^[a-zA-Z0-9._$-]+$/.test(e)||(t.isValid=!1,t.errors.push("服务名称只能包含字母、数字、点号、下划线、美元符号和连字符")),/^[a-zA-Z]/.test(e)||t.warnings.push("建议服务名称以字母开头"),/[._-]{2,}/.test(e)&&t.warnings.push("避免使用连续的特殊字符"),t}static validateVersion(e){const t={isValid:!0,errors:[],warnings:[]};if(null==e)return t;if("string"!=typeof e&&"number"!=typeof e)return t.isValid=!1,t.errors.push("版本号必须是字符串或数字类型"),t;const s=String(e);return/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?(\+[a-zA-Z0-9.-]+)?$/.test(s)||t.warnings.push("建议使用语义版本格式 (如: 1.0.0)"),t}static validateDependencies(e){const t={isValid:!0,errors:[],warnings:[]};if(null==e)return t;if("string"==typeof e){const s=this.validateServiceName(e);s.isValid||(t.isValid=!1,t.errors.push(`依赖项名称无效: ${s.errors.join(", ")}`))}else Array.isArray(e)?(0===e.length&&t.warnings.push("依赖项数组为空,考虑移除该属性"),e.forEach(((e,s)=>{if("string"==typeof e){const r=this.validateServiceName(e);r.isValid||(t.isValid=!1,t.errors.push(`依赖项[${s}]名称无效: ${r.errors.join(", ")}`))}else if("object"==typeof e&&null!==e)if(e.name){const r=this.validateServiceName(e.name);r.isValid||(t.isValid=!1,t.errors.push(`依赖项[${s}]名称无效: ${r.errors.join(", ")}`))}else t.isValid=!1,t.errors.push(`依赖项[${s}]缺少name属性`);else t.isValid=!1,t.errors.push(`依赖项[${s}]必须是字符串或对象`)}))):(t.isValid=!1,t.errors.push("依赖项必须是字符串、数组或对象"));return t}static validateSettings(e){const t={isValid:!0,errors:[],warnings:[]};if(null==e)return t;if("object"!=typeof e||Array.isArray(e))return t.isValid=!1,t.errors.push("设置必须是对象类型"),t;return this.getObjectDepth(e)>5&&t.warnings.push("设置对象嵌套层级过深,建议不超过5层"),this.hasCircularReference(e)&&(t.isValid=!1,t.errors.push("设置对象包含循环引用")),t}static validateMetadata(e){const t={isValid:!0,errors:[],warnings:[]};if(null==e)return t;if("object"!=typeof e||Array.isArray(e))return t.isValid=!1,t.errors.push("元数据必须是对象类型"),t;return["description","author","tags","category"].some((t=>e[t]))||t.warnings.push("建议添加描述性元数据字段 (description, author, tags, category)"),t}static validateFunctionParams(e){const t={isValid:!0,errors:[],warnings:[]};if(null==e)return t;if("object"!=typeof e||Array.isArray(e))return t.isValid=!1,t.errors.push("函数参数定义必须是对象类型"),t;for(const[s,r]of Object.entries(e)){if("object"!=typeof r||null===r){t.warnings.push(`参数 ${s} 的定义建议使用对象格式`);continue}const e=r;e.type||t.warnings.push(`参数 ${s} 缺少类型定义`),void 0===e.required&&t.warnings.push(`参数 ${s} 建议明确指定是否必需`)}return t}static validateBatch(e){const t={isValid:!0,errors:[],warnings:[]};for(const s of e){const e=s();e.isValid||(t.isValid=!1),t.errors.push(...e.errors),t.warnings.push(...e.warnings)}return t}static getObjectDepth(e,t=0){if(t>10)return t;if("object"!=typeof e||null===e)return t;let s=t;for(const r of Object.values(e)){const e=this.getObjectDepth(r,t+1);s=Math.max(s,e)}return s}static hasCircularReference(e,t=new WeakSet){if("object"!=typeof e||null===e)return!1;if(t.has(e))return!0;t.add(e);for(const s of Object.values(e))if(this.hasCircularReference(s,t))return!0;return t.delete(e),!1}}class Be{static checkArrayBounds(e,t){return t>=0&&t<e.length}static checkStringLength(e,t=0,s=Number.MAX_SAFE_INTEGER){return e.length>=t&&e.length<=s}static checkNumberRange(e,t=Number.MIN_SAFE_INTEGER,s=Number.MAX_SAFE_INTEGER){return e>=t&&e<=s&&Number.isFinite(e)}static checkObjectSize(e,t=1e3){return Object.keys(e).length<=t}static checkObjectDepth(e,t=10){const s=(e,r=0)=>{if(r>t)return r;if("object"!=typeof e||null===e)return r;let i=r;for(const t in e)if(e.hasOwnProperty(t)){const n=s(e[t],r+1);i=Math.max(i,n)}return i};return s(e)<=t}static checkMethodCount(e,t=50){return e<=t}static checkActionCount(e,t=30){return e<=t}static checkEventCount(e,t=20){return e<=t}static estimateMemoryUsage(e){const t=new WeakSet;return function e(s){if(null==s)return 0;if("boolean"==typeof s)return 4;if("number"==typeof s)return 8;if("string"==typeof s)return 2*s.length;if("function"==typeof s)return 0;if("object"==typeof s){if(t.has(s))return 0;t.add(s);let r=0;if(Array.isArray(s)){r+=8*s.length;for(const t of s)r+=e(t)}else{const t=Object.keys(s);r+=16*t.length;for(const i of t)r+=2*i.length,r+=e(s[i])}return r}return 0}(e)}}class Fe{static checkCodeInjection(e){const t=[/eval\s*\(/gi,/Function\s*\(/gi,/setTimeout\s*\(/gi,/setInterval\s*\(/gi,/require\s*\(/gi,/import\s*\(/gi,/__proto__/i,/constructor/i,/prototype/i],s=[];for(const r of t)r.test(e)&&s.push(`检测到代码注入模式: ${r.source}`);return{isValid:0===s.length,errors:s,warnings:[]}}static checkXSS(e){const t=[/<script[^>]*>.*?<\/script>/gi,/<iframe[^>]*>.*?<\/iframe>/gi,/javascript:/gi,/on\w+\s*=/gi,/<object[^>]*>/i,/<embed[^>]*>/i],s=[];for(const r of t)r.test(e)&&s.push(`检测到潜在的XSS攻击模式: ${r.source}`);return{isValid:0===s.length,errors:s,warnings:[]}}static checkPathTraversal(e){const t=[/\.\.[\\\//]/g,/[\\\//]\.\.[\\\//]/g,/%2e%2e%2f/gi,/%2e%2e%5c/gi],s=[];for(const r of t)r.test(e)&&s.push(`检测到路径遍历攻击模式: ${r.source}`);return{isValid:0===s.length,errors:s,warnings:[]}}static checkSQLInjection(e){const t=[/('|(\-\-)|(;)|(\||\|)|(\*|\*))/i,/(union|select|insert|delete|update|drop|create|alter|exec|execute)/i],s=[];for(const r of t)r.test(e)&&s.push(`检测到潜在的SQL注入模式: ${r.source}`);return{isValid:0===s.length,errors:s,warnings:[]}}static checkMethodSecurity(e,t){const s=[],r=this.checkCodeInjection(e);if(r.isValid||s.push(...r.errors.map((e=>`方法名称: ${e}`))),t.description&&"string"==typeof t.description){const e=this.checkXSS(t.description);e.isValid||s.push(...e.errors.map((e=>`方法描述: ${e}`)))}if(t.params){const e=JSON.stringify(t.params),r=this.checkCodeInjection(e);r.isValid||s.push(...r.errors.map((e=>`参数定义: ${e}`)))}return{isValid:0===s.length,errors:s,warnings:[]}}static checkActionSecurity(e,t){const s=[],r=this.checkCodeInjection(e);if(r.isValid||s.push(...r.errors.map((e=>`动作名称: ${e}`))),t.description&&"string"==typeof t.description){const e=this.checkXSS(t.description);e.isValid||s.push(...e.errors.map((e=>`动作描述: ${e}`)))}return{isValid:0===s.length,errors:s,warnings:[]}}static checkEventSecurity(e,t){const s=[],r=this.checkCodeInjection(e);if(r.isValid||s.push(...r.errors.map((e=>`事件名称: ${e}`))),t.description&&"string"==typeof t.description){const e=this.checkXSS(t.description);e.isValid||s.push(...e.errors.map((e=>`事件描述: ${e}`)))}return{isValid:0===s.length,errors:s,warnings:[]}}}const Ye=new Map,Ke=[],ze=["h","m","s","ms","μs","ns"],Qe=[36e5,6e4,1e3,1,.001,1e-6],We=[];for(let e=0;e<256;e++)We[e]=(e<16?"0":"")+e.toString(16);class Ze extends de{}function Je(e){return null!==e&&"object"==typeof e&&!(e instanceof String)}function Xe(e){return null!==e&&("string"==typeof e||e instanceof String)}function et(e){return"function"==typeof e}function tt(e){return null!=e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}function st(e){if(null==e)return;let t=e.prototype;return t&&t.constructor&&t.constructor.name?t.constructor.name:e.constructor&&e.constructor.name?e.constructor.name:void 0}function rt(e,t){const s=st(t);let r=e;for(;r=Object.getPrototypeOf(r);){if(s==st(r))return!0}return!1}function it(s){s.split(e.sep).reduce(((s,r)=>{const i=e.join(s,r,e.sep);return t.existsSync(i)||t.mkdirSync(i),i}),"")}function nt(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return We[255&e]+We[e>>8&255]+We[e>>16&255]+We[e>>24&255]+"-"+We[255&t]+We[t>>8&255]+"-"+We[t>>16&15|64]+We[t>>24&255]+"-"+We[63&s|128]+We[s>>8&255]+"-"+We[s>>16&255]+We[s>>24&255]+We[255&r]+We[r>>8&255]+We[r>>16&255]+We[r>>24&255]}function ot(){var e;const t=[],r=[],i=s.networkInterfaces();for(let s in i)for(let n in i[s])if(null===(e=i[s])||void 0===e?void 0:e.length){const e=i[s][n];if("IPv4"===e.family){if(e.internal){r.push(e.address);break}t.push(e.address);break}}return t.length>0?t:r}function at(e,t){if(-1==t.indexOf("?")){const s=t.indexOf("*");if(-1==s)return t===e;const r=t.length;if(r>2&&t.endsWith("**")&&s>r-3)return t=t.substring(0,r-2),e.startsWith(t);if(r>1&&t.endsWith("*")&&s>r-2)return t=t.substring(0,r-1),!!e.startsWith(t)&&-1==e.indexOf(".",r);if(1==r&&0==s)return-1==e.indexOf(".");if(2==r&&0==s&&1==t.lastIndexOf("*"))return!0}const s=t;let r=Ye.get(s);return null==r&&(t.startsWith("$")&&(t="\\"+t),t="^"+(t=(t=(t=(t=t.replace(/\?/g,".")).replace(/\*\*/g,"§§§")).replace(/\*/g,"[^\\.]*")).replace(/§§§/g,".*"))+"$",r=new RegExp(t,""),Ye.set(s,r)),r.test(e)}function lt(e,t){1===arguments.length&&(t=e),-1===Ke.indexOf(e)&&(console.warn(r.yellow().bold(`DeprecationWarning: ${t}`)),Ke.push(e))}function ct(e){return Array.isArray(e)?e:[e]}function ht(e){return et(e)?{handler:e}:e}function dt(e,t){return JSON.parse(JSON.stringify(e,function(e={maxSafeObjectSize:1/0}){const t=new WeakSet;return function(s,r){if("object"==typeof r&&null!==r){const s=r.constructor&&r.constructor.name||typeof r;if(e.maxSafeObjectSize&&"length"in r&&r.length>e.maxSafeObjectSize)return`[${s} ${r.length}]`;if(e.maxSafeObjectSize&&"size"in r&&r.size>e.maxSafeObjectSize)return`[${s} ${r.size}]`;if(t.has(r))return;t.add(r)}return r}}(t)))}function ut(e){if(null==e)return"?";for(let t=0;t<Qe.length;t++){const s=e/Qe[t];if(s>=1)return""+Math.floor(s)+ze[t]}return"now"}function pt(e,t){return t&&Object.assign(e.meta,t),e.meta}class Context{constructor(e,t){this.id="",this.nodeID="",this.endpoint=null,this.action=null,this.service=null,this.event=null,this.starHrTime=null,this.star=e,this.star?(this.nodeID=this.star.nodeID||"",this.id=this.star.generateUid()):this.nodeID=null,t?this.setEndpoint(t):(this.endpoint=null,this.service=null,this.action=null,this.event=null),this.eventName=null,this.eventType=null,this.eventGroups=null,this.options={timeout:null,retries:null},this.parentID=null,this.caller=null,this.level=1,this.params=null,this.meta={},this.locals={},this.requestID=this.id,this.tracing=null,this.span=null,this._spanStack=[],this.needAck=null,this.ackID=null,this.cachedResult=!1}static create(e,t,s,r){var i,n,o,a,l;const c=new Context(e,t);if(null!=t&&c.setEndpoint(t),null!=s){let t=!!e&&e.options.contextParamsCloning;r&&null!=r.paramsCloning&&(t=r.paramsCloning),c.setParams(s,t)}return r&&(c.options=r),(null==r?void 0:r.requestID)?c.requestID=r.requestID:(null==r?void 0:r.parentCtx)&&r.parentCtx.requestID&&(c.requestID=r.parentCtx.requestID),(null==r?void 0:r.parentCtx)&&r.parentCtx.meta?c.meta=Object.assign({},r.parentCtx.meta||{},r.meta||{}):(null==r?void 0:r.meta)&&(c.meta=r.meta),(null==r?void 0:r.parentCtx)&&(c.tracing=r.parentCtx.tracing,c.level=r.parentCtx.level+1,(null===(i=r.parentCtx)||void 0===i?void 0:i.span)?c.parentID=null===(n=r.parentCtx.span)||void 0===n?void 0:n.id:c.parentID=r.parentCtx.id,r.parentCtx.service&&(c.caller=r.parentCtx.service.fullName)),(null==r?void 0:r.caller)&&(c.caller=r.caller),(null==r?void 0:r.parentSpan)&&(c.parentID=null===(o=r.parentSpan)||void 0===o?void 0:o.id,c.requestID=null===(a=r.parentSpan)||void 0===a?void 0:a.traceID,c.tracing=null===(l=r.parentSpan)||void 0===l?void 0:l.sampled),(null==r?void 0:r.needAck)&&(c.needAck=r.needAck),c}copy(e){const t=new Context(this.star);return t.nodeID=this.nodeID,t.setEndpoint(e||this.endpoint),t.options=this.options,t.parentID=this.parentID,t.caller=this.caller,t.level=this.level,t.params=this.params,t.meta=this.meta,t.locals=this.locals,t.requestID=this.requestID,t.tracing=this.tracing,t.span=this.span,t.needAck=this.needAck,t.ackID=this.ackID,t.eventName=this.eventName,t.eventType=this.eventType,t.eventGroups=this.eventGroups,t.cachedResult=this.cachedResult,t}setParams(e,t=!1){this.params=t&&e?Object.assign({},e):e}setEndpoint(e){this.endpoint=e,this.endpoint&&(this.nodeID=e.id,e.action?(this.action=e.action,this.action.service&&(this.service=this.action.service),this.event=null):e.event&&(this.event=e.event,this.event.service&&(this.service=this.event.service),this.action=null))}call(e,t,s){var r;const i=Object.assign({parentCtx:this},s);if(this.options.timeout&&this.options.timeout>0&&this.starHrTime){const t=process.hrtime(this.starHrTime),s=1e3*t[0]+t[1]/1e6,r=this.options.timeout-s;if(r<=0)return Promise.reject(new Oe({action:e,nodeID:this.star.nodeID||""}));(!i.timeout||r<i.timeout)&&(i.timeout=r)}if((null===(r=this.star.options)||void 0===r?void 0:r.maxCallLevel)&&this.star.options.maxCallLevel>0&&this.level>=this.star.options.maxCallLevel)return Promise.reject(new we({nodeID:this.star.nodeID||"",level:this.level}));let n=this.star.call(e,t,s);return n.then((e=>(n.ctx&&pt(this,n.ctx.meta),e))).catch((e=>(n.ctx&&pt(this,n.ctx.meta),Promise.reject(e))))}mcall(e,t={}){const s=Object.assign({parentCtx:this},t);if(this.options.timeout&&this.options.timeout>0&&this.starHrTime){const t=process.hrtime(this.starHrTime),r=1e3*t[0]+t[1]/1e6,i=this.options.timeout-r;if(i<=0){const t=(Array.isArray(e)?e:Object.values(e)).map((e=>e.action)).join(", ");return Promise.reject(new Oe({action:t,nodeID:this.star.nodeID||""}))}(!s.timeout||i<s.timeout)&&(s.timeout=i)}if(this.star.options.maxCallLevel&&this.star.options.maxCallLevel>0&&this.level>=this.star.options.maxCallLevel)return Promise.reject(new we({nodeID:this.star.nodeID||"",level:this.level}));let r=this.star.mcall(e,s);return r.then((e=>(Array.isArray(r.ctx)&&r.ctx.length&&r.ctx.forEach((e=>pt(this,e.meta))),e))).catch((e=>(Array.isArray(r.ctx)&&r.ctx.length&&r.ctx.forEach((e=>pt(this,e.meta))),Promise.reject(e))))}emit(e,t,s){return Array.isArray(s)||Xe(s)?s={groups:s}:null==s&&(s={}),s.groups&&!Array.isArray(s.groups)&&(s.groups=[s.groups]),s.parentCtx=this,this.star.emit(e,t,s)}broadcast(e,t,s){return Array.isArray(s)||Xe(s)?s={groups:s}:null==s&&(s={}),s.groups&&!Array.isArray(s.groups)&&(s.groups=[s.groups]),s.parentCtx=this,this.star.broadcast(e,t,s)}setContextEventData(e){e.eventName&&(this.eventName=e.eventName),e.eventType&&(this.eventType=e.eventType),e.eventGroups&&(this.eventGroups=e.eventGroups)}startSpan(e,t){var s;let r;return r=this.span?this.span.startSpan(e,Object.assign({ctx:this},t)):null===(s=this.star.tracer)||void 0===s?void 0:s.startSpan(e,Object.assign({ctx:this},t)),this._spanStack.push(r),this.span=r,r}finishSpan(e,t){var s,r;if(!e.isActive())return;e.finish(t);const i=this._spanStack.findIndex((t=>t==e));-1!==i?(this._spanStack.splice(i,1),this.span=this._spanStack[this._spanStack.length-1]):null===(r=null===(s=this.service)||void 0===s?void 0:s.logger)||void 0===r||r.warn("This span is not assigned to this context",e)}toJSON(){return i.pick(this,["id","nodeID","action.name","event.name","service.name","service.version","service.fullName","options","parentID","caller","level","params","meta","requestID","tracing","span","needAck","ackID","eventName","eventType","eventGroups","cachedResult"])}[d.inspect.custom](e,t){if(e<0)return null==t?void 0:t.stylize("[Context]","special");const s=d.inspect(this.toJSON(),t);return`${null==t?void 0:t.stylize("Context","special")}< ${s} >`}}var vt;!function(e){e.fatal="fatal",e.error="error",e.warn="warn",e.debug="debug",e.info="info",e.trace="trace"}(vt||(vt={}));const gt=[vt.fatal,vt.error,vt.warn,vt.debug,vt.info,vt.trace];class mt{constructor(e){this.options=i.defaultsDeep(e,{level:vt.info,createLogger:null})}init(e){this.loggerFactory=e,this.star=e.star}stop(){return Promise.resolve()}getLogLevel(e){const t=e?e.toUpperCase():"",s=this.options.level;if(Xe(s))return s;if(Je(s)){if(s[t])return s[t];const e=Object.keys(s).find((e=>function(e,t){if(-1==t.indexOf("?")){const s=t.indexOf("*");if(-1==s)return t===e;const r=t.length;if(r>2&&t.endsWith("**")&&s>r-3)return t=t.substring(0,r-2),e.startsWith(t);if(r>1&&t.endsWith("*")&&s>r-2)return t=t.substring(0,r-1),!!e.startsWith(t)&&-1==e.indexOf(".",r);if(1==r&&0==s)return-1==e.indexOf(".");if(2==r&&0==s&&1==t.lastIndexOf("*"))return!0}const s=t;let r=Ye.get(s);return null==r&&(t.startsWith("$")&&(t="\\"+t),t="^"+(t=(t=(t=(t=t.replace(/\?/g,".")).replace(/\*\*/g,"§§§")).replace(/\*/g,"[^\\.]*")).replace(/§§§/g,".*"))+"$",r=new RegExp(t,""),Ye.set(s,r)),r.test(e)}(t,e)&&"**"!==e));if(e)return s[e];if(s["**"])return s["**"]}return null}getLogHandler(e){return null}}class Et extends mt{constructor(e){super(e),this.options={},this.maxPrefixLength=0,this.levelColorStr={},this.options=i.defaultsDeep(this.options,e,{colors:!0,moduleColors:!1,formatter:"full",objectPrinter:null,autoPadding:!1}),this.maxPrefixLength=0}init(e){super.init(e),this.options.colors||(r.enabled=!1),this.objectPrinter=this.options.objectPrinter?this.options.objectPrinter:e=>d.inspect(e,{showHidden:!1,depth:2,colors:r.enabled,breakLength:Number.POSITIVE_INFINITY}),this.levelColorStr=gt.reduce(((e,t)=>(e[t]=function(e){switch(e){case vt.fatal:return r.red().inverse;case vt.error:return r.red;case vt.warn:return r.yellow;case vt.debug:return r.magenta;case vt.trace:return r.gray;case vt.info:default:return r.green}}(t)(i.padEnd(t.toUpperCase(),5)),e)),{}),this.options.colors&&!0===this.options.moduleColor&&(this.options.moduleColor=["yellow","bold.yellow","cyan","bold.cyan","green","bold.green","magenta","bold.magenta","blue","bold.blue"])}getNextColor(e){if(this.options.colors&&Array.isArray(this.options.moduleColor)){let t=0;for(let s=0;s<e.length;s++)t=(t<<5)-t+e.charCodeAt(s),t|=0;return this.options.moduleColor[Math.abs(t)%this.options.moduleColor.length]}return"grey"}padLeft(e){return this.options.autoPadding?" ".repeat(this.maxPrefixLength-e):""}render(e,t){return e.replace(/\{\s?(\w+)\s?\}/g,((e,s)=>t[s]||""))}getFormatter(e){const t=this.options.formatter,s=e&&e.mod?e.mod.toUpperCase():"",i=this.getNextColor(s).split(".").reduce(((e,t)=>e[t]||e()[t]),r)(s);e&&r.grey(e.nodeID+"/");const n=e=>e.map((e=>Je(e)||Array.isArray(e)?this.objectPrinter(e):e));if(et(t))return(s,r)=>t.call(this,s,r,e,{printArgs:n});if("json"===t)return r.enabled=!1,(t,s)=>[JSON.stringify({time:Date.now(),level:t,msg:n(s).join(" "),...e})];if("jsonext"===t)return(t,s)=>{const r={time:`${(new Date).toLocaleString("zh-CN",{hour12:!1})}:${ve()}`,level:t,message:"",...e};return s.length>0&&("object"==typeof s[0]?(Object.assign(r,s[0]),r.message=n(s.slice(1)).join(" ")):r.message=n(s).join(" ")),[JSON.stringify(r)]};if("simple"===t)return(e,t)=>[this.levelColorStr[e],"-",...n(t)];if("short"===t){const t=23+e.mod.length;return this.maxPrefixLength=Math.max(t,this.maxPrefixLength),(e,s)=>[r.grey(`[${(new Date).toDateString().substring(11)}]`),this.levelColorStr[e],i+this.padLeft(t)+r.grey(":"),...n(s)]}if("full"===t){const t=35+e.nodeID.length+e.mod.length;return this.maxPrefixLength=Math.max(t,this.maxPrefixLength),(e,s)=>[r.grey(`[${(new Date).toLocaleString("zh-CN",{hour12:!1})}:${ve()}]`),this.levelColorStr[e],i+this.padLeft(t)+r.grey(":"),...n(s)]}return(s,o)=>{const a=`${(new Date).toLocaleString("zh-CN",{hour12:!1})}:${ve()}`;return[this.render(t,{timestamp:r.grey(a),time:r.grey(a.substring(11)),level:this.levelColorStr[s],nodeID:r.grey(e.nodeID),mod:i,msg:n(o).join(" ")})]}}}const ft=d.promisify(t.appendFile);const St={BaseLogger:mt,Formatted:Et,Console:class extends Et{constructor(e){super(e),this.maxPrefixLength=0}init(e){super.init(e),this.options.colors||(r.enabled=!1)}getLogHandler(e){const t=e?this.getLogLevel(e.mod):null;if(!t)return null;const s=gt.indexOf(t),r=this.getFormatter(e);return(e,t)=>{if(gt.indexOf(e)>s)return;const i=r(e,t);switch(e){case vt.fatal:case vt.error:return console.error(...i);case vt.warn:return console.warn(...i);default:return console.log(...i)}}}},File:class extends Et{constructor(e){super(e),this.logFolder="",this.options=i.defaultsDeep(this.options,{folder:"./logs",filename:"universer-{date}.log",eol:s.EOL,interval:1e3}),this.options.colors=!1,this.queue=[],this.timer=null,this.currentFileName=null,this.fs=null}init(t){super.init(t),this.logFolder=e.resolve(this.render(this.options.folder,{nodeID:this.star.nodeID,namespace:this.star.namespace})),it(this.logFolder),this.options.interval&&(this.timer=setInterval((()=>this.flush()),this.options.interval),this.timer.unref())}stop(){return this.timer&&(clearInterval(this.timer),this.timer=null),this.flush()}getFileName(){const t=(new Date).toISOString().substring(0,10);return e.join(this.logFolder,this.render(this.options.filename,{date:t,nodeID:this.star.nodeID,namespace:this.star.namespace}))}async flush(){if(this.queue.length>0){const e=this.getFileName(),t=Array.from(this.queue);this.queue.length=0;const s=t.join(this.options.eol)+this.options.eol;return ft(e,s).catch((t=>{console.debug("Unable to write log file:",e,t)}))}return Promise.resolve()}getLogHandler(e){const t=e?this.getLogLevel(e.mod):null;if(!t)return null;const s=gt.indexOf(t),r=this.getFormatter(e);return(e,t)=>{if(gt.indexOf(e)>s)return;const i=r(e,t).join(" ").replace(/\u001b\[.*?m/g,"");return this.queue.push(i),this.options.interval?void 0:this.flush()}}},Log4js:class extends mt{constructor(e){super(e),this.log4js=null,this.options=i.defaultsDeep(this.options,{})}init(e){super.init(e);try{this.options.log4js&&(this.log4js=p.configure(this.options.log4js))}catch(e){this.star.fatal("The 'log4js' package is missing! Please install it with 'npm install log4js --save' command!",e,!0)}}stop(){return this.log4js?new Promise((e=>{var t;return null===(t=this.log4js)||void 0===t?void 0:t.shutdown(e)})):Promise.resolve()}getLogHandler(e){var t;let s,r=e?this.getLogLevel(e.mod):null;return r?(et(this.options.createLogger)?s=this.options.createLogger(r,e):this.log4js&&(s=null===(t=this.log4js)||void 0===t?void 0:t.getLogger(e.mod.toUpperCase()),s.level=r),(e,t)=>s[e]([...t])):null}},Pino:class extends mt{constructor(e){super(e),this.pino=null,this.options=i.defaultsDeep(this.options,{pino:{options:null,destination:null}})}init(e){super.init(e);try{this.pino=v(this.options.pino&&this.options.pino.options?this.options.pino.options:void 0,this.options.pino&&this.options.pino.destination?this.options.pino.destination:void 0)}catch(e){this.star.fatal("The 'pino' package is missing! Please install it with 'yarn add pino --save' command!",e,!0)}}getLogHandler(e){let t=e?this.getLogLevel(e.mod):null;if(!t)return null;const s=et(this.options.createLogger)?this.options.createLogger(t,e):this.pino.child(e,{level:t});return(e,t)=>s[e](...t)}},LEVELS:gt};function Tt(e){if(!e)return null;let t=Object.keys(St).find((t=>t.toLocaleLowerCase()==e.toLocaleLowerCase()));return t?St[t]:void 0}var _t={Loggers:St,resolve:function(e){if(Je(e)&&rt(e,mt))return e;if(Xe(e)){let t=Tt(e);if(t)return new t}else if(Je(e)){let t=Tt(e.type);if(t)return new t(e.options);throw new Le(`Invalid logger configuration. Type '${e.type}'`,{type:e.type})}throw new Le(`Invalid logger configuration: '${e}'`,{type:e})},register:function(e,t){St[e]=t}};const It=()=>{},yt=process.cwd();class Nt{constructor(e){this.appenders=[],this.star=e,this.appenders=[],this.cache=new Map}init(e){this.options=e;const t=this.star.options.logLevel||"info";!1===e||null==e?this.appenders=[]:!0===e||e===console?this.appenders=[_t.resolve({type:"Console",options:{level:t}})]:(Array.isArray(e)||(e=[e]),this.appenders=i.compact(e).map((e=>Xe(e)?_t.resolve({type:e,options:{level:t}}):tt(e)?_t.resolve(i.defaultsDeep({},e,{options:{level:t}})):_t.resolve(e)))),this.appenders.forEach((e=>e.init(this)))}stop(){return this.star.Promise.all(this.appenders.map((e=>e.stop())))}getCallerFromStack(){const e=Error.prepareStackTrace;Error.prepareStackTrace=(e,t)=>t;const t=(new Error).stack;if(Error.prepareStackTrace=e,t&&t.length>2){const e=t[2];return{filename:e.getFileName().substring(yt.length+1),lineNumber:e.getLineNumber(),columnNumber:e.getColumnNumber(),methodName:e.getMethodName(),functionName:e.getFunctionName()}}}getBindingsKey(e){return e?["nodeID","namespace","mod"].map((t=>e[t])).join("|"):""}getLogger(e){let t=this.cache.get(this.getBindingsKey(e));if(t)return t;t={};const s=this.star,r=this.appenders,n=i.compact(r.map((t=>t.getLogHandler(e)))),o=s.middlewares&&s.middlewares.registeredHooks.newLogEntry;return gt.forEach((r=>{if(0==n.length&&!o)return t[r]=It;t[r]=function(...t){var i;if(o&&s.middlewares&&(null===(i=s.middlewares)||void 0===i||i.callSyncHandlers("newLogEntry",[r,t,e],{})),0!=n.length)for(let e=0;e<n.length;e++)n[e](r,t)}})),t.appenders=r,this.cache.set(this.getBindingsKey(e),t),t}}var Rt={TYPE_COUNTER:"counter",TYPE_GAUGE:"gauge",TYPE_HISTOGRAM:"histogram",TYPE_INFO:"info",UNIVERSE_METRICS_COMMON_COLLECT_TOTAL:"universe.metrics.common.collect.total",UNIVERSE_METRICS_COMMON_COLLECT_TIME:"universe.metrics.common.collect.time",PROCESS_ARGUMENTS:"process.arguments",PROCESS_PID:"process.pid",PROCESS_PPID:"process.ppid",PROCESS_MEMORY_HEAP_SIZE_TOTAL:"process.memory.heap.size.total",PROCESS_MEMORY_HEAP_SIZE_USED:"process.memory.heap.size.used",PROCESS_MEMORY_RSS:"process.memory.rss",PROCESS_MEMORY_EXTERNAL:"process.memory.external",PROCESS_MEMORY_HEAP_SPACE_SIZE_TOTAL:"process.memory.heap.space.size.total",PROCESS_MEMORY_HEAP_SPACE_SIZE_USED:"process.memory.heap.space.size.used",PROCESS_MEMORY_HEAP_SPACE_SIZE_AVAILABLE:"process.memory.heap.space.size.available",PROCESS_MEMORY_HEAP_SPACE_SIZE_PHYSICAL:"process.memory.heap.space.size.physical",PROCESS_MEMORY_HEAP_STAT_HEAP_SIZE_TOTAL:"process.memory.heap.stat.heap.size.total",PROCESS_MEMORY_HEAP_STAT_EXECUTABLE_SIZE_TOTAL:"process.memory.heap.stat.executable.size.total",PROCESS_MEMORY_HEAP_STAT_PHYSICAL_SIZE_TOTAL:"process.memory.heap.stat.physical.size.total",PROCESS_MEMORY_HEAP_STAT_AVAILABLE_SIZE_TOTAL:"process.memory.heap.stat.available.size.total",PROCESS_MEMORY_HEAP_STAT_USED_HEAP_SIZE:"process.memory.heap.stat.used.heap.size",PROCESS_MEMORY_HEAP_STAT_HEAP_SIZE_LIMIT:"process.memory.heap.stat.heap.size.limit",PROCESS_MEMORY_HEAP_STAT_MALLOCATED_MEMORY:"process.memory.heap.stat.mallocated.memory",PROCESS_MEMORY_HEAP_STAT_PEAK_MALLOCATED_MEMORY:"process.memory.heap.stat.peak.mallocated.memory",PROCESS_MEMORY_HEAP_STAT_ZAP_GARBAGE:"process.memory.heap.stat.zap.garbage",PROCESS_UPTIME:"process.uptime",PROCESS_INTERNAL_ACTIVE_HANDLES:"process.internal.active.handles",PROCESS_INTERNAL_ACTIVE_REQUESTS:"process.internal.active.requests",PROCESS_VERSIONS_NODE:"process.versions.node",PROCESS_EVENTLOOP_LAG_MIN:"process.eventloop.lag.min",PROCESS_EVENTLOOP_LAG_AVG:"process.eventloop.lag.avg",PROCESS_EVENTLOOP_LAG_MAX:"process.eventloop.lag.max",PROCESS_EVENTLOOP_LAG_COUNT:"process.eventloop.lag.count",PROCESS_GC_TIME:"process.gc.time",PROCESS_GC_TOTAL_TIME:"process.gc.total.time",PROCESS_GC_EXECUTED_TOTAL:"process.gc.executed.total",OS_MEMORY_FREE:"os.memory.free",OS_MEMORY_USED:"os.memory.used",OS_MEMORY_TOTAL:"os.memory.total",OS_UPTIME:"os.uptime",OS_TYPE:"os.type",OS_RELEASE:"os.release",OS_HOSTNAME:"os.hostname",OS_ARCH:"os.arch",OS_PLATFORM:"os.platform",OS_USER_UID:"os.user.uid",OS_USER_GID:"os.user.gid",OS_USER_USERNAME:"os.user.username",OS_USER_HOMEDIR:"os.user.homedir",OS_DATETIME_UNIX:"os.datetime.unix",OS_DATETIME_ISO:"os.datetime.iso",OS_DATETIME_UTC:"os.datetime.utc",OS_DATETIME_TZ_OFFSET:"os.datetime.tz.offset",OS_NETWORK_ADDRESS:"os.network.address",OS_NETWORK_MAC:"os.network.mac",OS_CPU_LOAD_1:"os.cpu.load.1",OS_CPU_LOAD_5:"os.cpu.load.5",OS_CPU_LOAD_15:"os.cpu.load.15",OS_CPU_UTILIZATION:"os.cpu.utilization",OS_CPU_USER:"os.cpu.user",OS_CPU_SYSTEM:"os.cpu.system",OS_CPU_TOTAL:"os.cpu.total",OS_CPU_INFO_MODEL:"os.cpu.info.model",OS_CPU_INFO_SPEED:"os.cpu.info.speed",OS_CPU_INFO_TIMES_USER:"os.cpu.info.times.user",OS_CPU_INFO_TIMES_SYS:"os.cpu.info.times.sys",UNIVERSE_NODE_TYPE:"universe.node.type",UNIVERSE_NODE_VERSIONS_UNIVERSE:"universe.node.versions.universe",UNIVERSE_NODE_VERSIONS_LANG:"universe.node.versions.lang",UNIVERSE_NODE_VERSIONS_PROTOCOL:"universe.node.versions.protocol",UNIVERSE_STAR_NAMESPACE:"universe.star.namespace",UNIVERSE_STAR_STARTED:"universe.star.started",UNIVERSE_STAR_LOCAL_SERVICES_TOTAL:"universe.star.local.services.total",UNIVERSE_STAR_MIDDLEWARES_TOTAL:"universe.star.middlewares.total",UNIVERSE_REGISTRY_NODES_TOTAL:"universe.registry.nodes.total",UNIVERSE_REGISTRY_NODES_ONLINE_TOTAL:"universe.registry.nodes.online.total",UNIVERSE_REGISTRY_SERVICES_TOTAL:"universe.registry.services.total",UNIVERSE_REGISTRY_SERVICE_ENDPOINTS_TOTAL:"universe.registry.service.endpoints.total",UNIVERSE_REGISTRY_ACTIONS_TOTAL:"universe.registry.actions.total",UNIVERSE_REGISTRY_ACTION_ENDPOINTS_TOTAL:"universe.registry.action.endpoints.total",UNIVERSE_REGISTRY_EVENTS_TOTAL:"universe.registry.events.total",UNIVERSE_REGISTRY_EVENT_ENDPOINTS_TOTAL:"universe.registry.event.endpoints.total",UNIVERSE_REQUEST_TOTAL:"universe.request.total",UNIVERSE_REQUEST_ACTIVE:"universe.request.active",UNIVERSE_REQUEST_ERROR_TOTAL:"universe.request.error.total",UNIVERSE_REQUEST_TIME:"universe.request.time",UNIVERSE_REQUEST_LEVELS:"universe.request.levels",UNIVERSE_REQUEST_DIRECTCALL_TOTAL:"universe.request.directcall.total",UNIVERSE_REQUEST_MULTICALL_TOTAL:"universe.request.multicall.total",UNIVERSE_EVENT_EMIT_TOTAL:"universe.event.emit.total",UNIVERSE_EVENT_BROADCAST_TOTAL:"universe.event.broadcast.total",UNIVERSE_EVENT_BROADCASTLOCAL_TOTAL:"universe.event.broadcast_local.total",UNIVERSE_EVENT_RECEIVED_TOTAL:"universe.event.received.total",UNIVERSE_EVENT_RECEIVED_ACTIVE:"universe.event.received.active",UNIVERSE_EVENT_RECEIVED_ERROR_TOTAL:"universe.event.received.error.total",UNIVERSE_EVENT_RECEIVED_TIME:"universe.event.received.time",UNIVERSE_TRANSIT_PUBLISH_TOTAL:"universe.transit.publish.total",UNIVERSE_TRANSIT_RECEIVE_TOTAL:"universe.transit.receive.total",UNIVERSE_TRANSIT_REQUESTS_ACTIVE:"universe.transit.requests.active",UNIVERSE_TRANSIT_STREAMS_SEND_ACTIVE:"universe.transit.streams.send.active",UNIVERSE_TRANSIT_STREAMS_RECEIVE_ACTIVE:"universe.transit.streams.receive.active",UNIVERSE_TRANSIT_READY:"universe.transit.ready",UNIVERSE_TRANSIT_CONNECTED:"universe.transit.connected",UNIVERSE_TRANSIT_PONG_TIME:"universe.transit.pong.time",UNIVERSE_TRANSIT_PONG_SYSTIME_DIFF:"universe.transit.pong.systime_diff",UNIVERSE_TRANSIT_ORPHAN_RESPONSE_TOTAL:"universe.transit.orphan.response.total",UNIVERSE_TRANSPORTER_PACKETS_SENT_TOTAL:"universe.transporter.packets.sent.total",UNIVERSE_TRANSPORTER_PACKETS_SENT_BYTES:"universe.transporter.packets.sent.bytes",UNIVERSE_TRANSPORTER_PACKETS_RECEIVED_TOTAL:"universe.transporter.packets.received.total",UNIVERSE_TRANSPORTER_PACKETS_RECEIVED_BYTES:"universe.transporter.packets.received.bytes",UNIVERSE_CIRCUIT_STAR_OPENED_ACTIVE:"universe.circuit_star.opened.active",UNIVERSE_CIRCUIT_STAR_OPENED_TOTAL:"universe.circuit_star.opened.total",UNIVERSE_CIRCUIT_STAR_HALF_OPENED_ACTIVE:"universe.circuit_star.half_opened.active",UNIVERSE_REQUEST_FALLBACK_TOTAL:"universe.request.fallback.total",UNIVERSE_REQUEST_BULKHEAD_INFLIGHT:"universe.request.bulkhead.inflight",UNIVERSE_REQUEST_BULKHEAD_QUEUE_SIZE:"universe.request.bulkhead.queue.size",UNIVERSE_EVENT_BULKHEAD_INFLIGHT:"universe.event.bulkhead.inflight",UNIVERSE_EVENT_BULKHEAD_QUEUE_SIZE:"universe.event.bulkhead.queue.size",UNIVERSE_REQUEST_RETRY_ATTEMPTS_TOTAL:"universe.request.retry.attempts.total",UNIVERSE_REQUEST_TIMEOUT_TOTAL:"universe.request.timeout.total",UNIVERSE_CACHER_GET_TOTAL:"universe.cacher.get.total",UNIVERSE_CACHER_GET_TIME:"universe.cacher.get.time",UNIVERSE_CACHER_FOUND_TOTAL:"universe.cacher.found.total",UNIVERSE_CACHER_SET_TOTAL:"universe.cacher.set.total",UNIVERSE_CACHER_SET_TIME:"universe.cacher.set.time",UNIVERSE_CACHER_DEL_TOTAL:"universe.cacher.del.total",UNIVERSE_CACHER_DEL_TIME:"universe.cacher.del.time",UNIVERSE_CACHER_CLEAN_TOTAL:"universe.cacher.clean.total",UNIVERSE_CACHER_CLEAN_TIME:"universe.cacher.clean.time",UNIVERSE_CACHER_EXPIRED_TOTAL:"universe.cacher.expired.total",UNIVERSE_DISCOVERER_REDIS_COLLECT_TOTAL:"universe.discoverer.redis.collect.total",UNIVERSE_DISCOVERER_REDIS_COLLECT_TIME:"universe.discoverer.redis.collect.time",UNIVERSE_DISCOVERER_ETCD_COLLECT_TOTAL:"universe.discoverer.etcd.collect.total",UNIVERSE_DISCOVERER_ETCD_COLLECT_TIME:"universe.discoverer.etcd.collect.time",UNIT_BIT:"bit",UNIT_BYTE:"byte",UNIT_KILOBYTES:"kilobyte",UNIT_MEGABYTE:"megabyte",UNIT_GIGABYTE:"gigabyte",UNIT_TERRABYTE:"terrabyte",UNIT_PETABYTE:"petabyte",UNIT_EXOBYTE:"exabyte",UNIT_NANOSECONDS:"nanosecond",UNIT_MICROSECONDS:"microsecond",UNIT_MILLISECONDS:"millisecond",UNIT_SECONDS:"second",UNIT_MINUTE:"minute",UNIT_HOUR:"hour",UNIT_DAY:"day",UNIT_WEEK:"week",UNIT_MONTH:"month",UNIT_YEAR:"year",UNIT_HANDLE:"handle",UNIT_CPU:"cpu",UNIT_GHZ:"GHz",UNIT_REQUEST:"request",UNIT_CONNECTION:"connection",UNIT_PACKET:"packet",UNIT_MESSAGE:"message",UNIT_STREAM:"stream",UNIT_EVENT:"event"};class bt{constructor(e){this.registry=null,this.star=null,this.logger=null,this.options=i.defaultsDeep(e,{includes:null,excludes:null,metricNamePrefix:null,metricNameSuffix:null,metricNameFormatter:null,labelNameFormatter:null}),Xe(this.options.includes)&&(this.options.includes=[this.options.includes]),Xe(this.options.excludes)&&(this.options.excludes=[this.options.excludes])}init(e){this.registry=e,this.star=this.registry.star,this.logger=this.registry.logger}stop(){return Promise.resolve()}matchMetricName(e){return!(Array.isArray(this.options.includes)&&!this.options.includes.some((t=>at(e,t))))&&!(Array.isArray(this.options.excludes)&&!this.options.excludes.every((t=>!at(e,t))))}formatMetricName(e){return e=(this.options.metricNamePrefix?this.options.metricNamePrefix:"")+e+(this.options.metricNameSuffix?this.options.metricNameSuffix:""),this.options.metricNameFormatter?this.options.metricNameFormatter(e):e}formatLabelName(e){return this.options.labelNameFormatter?this.options.labelNameFormatter(e):e}metricChanged(e,t,s,r){}}const At="metric";const Ot={Base:bt,Console:class extends bt{constructor(e){super(e),this.timer=null,this.options=i.defaultsDeep(this.options,{interval:5,logger:null,colors:!0,onlyChanges:!0}),this.options.colors||(r.enabled=!1),this.lastChanges=new Set}init(e){super.init(e),this.options.interval>0&&(this.timer=setInterval((()=>this.print()),1e3*this.options.interval),this.timer=null)}labelToStr(e){const t=Object.keys(e);return 0===t.length?r.gray("{}"):r.gray("{")+t.map((t=>`${r.gray(this.formatLabelName(t))}: ${r.magenta(""+e[t])}`)).join(", ")+r.gray("}")}print(){var e;let t=null===(e=this.registry)||void 0===e?void 0:e.list({includes:this.options.includes,excludes:this.options.excludes});this.options.onlyChanges&&(t=null==t?void 0:t.filter((e=>this.lastChanges.has(e.name)))),0!==(null==t?void 0:t.length)&&(this.log(r.gray(`------------------- [ METRICS START (${null==t?void 0:t.length}) ] -------------------`)),null==t||t.forEach((e=>{var t;this.log(r.cyan().bold(this.formatMetricName(e.name))+" "+r.gray("("+e.type+")")),0===e.values.size?this.log(r.gray(" <no values>")):(e.unit&&r.gray((null===(t=this.registry)||void 0===t?void 0:t.pluralizeUnit(e.unit))||""),e.values.forEach((t=>{let s;switch(this.labelToStr(t.labels),e.type){case Rt.TYPE_COUNTER:case Rt.TYPE_GAUGE:case Rt.TYPE_INFO:s=""===t.value?r.grey("<empty string>"):r.green().bold(t.value),null!=t.rate&&(s=s+r.grey(" | Rate: ")+(null!=t.rate?r.green().bold(t.rate.toFixed(2)):"-"));break;case Rt.TYPE_HISTOGRAM:{const e=[];e.push(`Count: ${t.count}`),t.buckets&&Object.keys(t.buckets).forEach((s=>{e.push(`${s}: ${null!=t.buckets[s]?t.buckets[s]:"-"}`)})),t.quantiles&&(e.push(`Min: ${null!=t.min?t.min.toFixed(2):"-"}`),e.push(`Mean: ${null!=t.mean?t.mean.toFixed(2):"-"}`),e.push(`Var: ${null!=t.variance?t.variance.toFixed(2):"-"}`),e.push(`StdDev: ${null!=t.stdDev?t.stdDev.toFixed(2):"-"}`),e.push(`Max: ${null!=t.max?t.max.toFixed(2):"-"}`),Object.keys(t.quantiles).forEach((s=>{e.push(`${s}: ${null!=t.quantiles[s]?t.quantiles[s].toFixed(2):"-"}`)}))),null!=t.rate&&e.push(`Rate: ${null!=t.rate?t.rate.toFixed(2):"-"}`),s=r.green().bold(e.join(" | "));break}}}))),this.log("")})),this.log(r.gray(`-------------------- [ METRIC