node-universe
Version:
基于 Nodejs 环境的一款微服务框架,原理来自于宇宙中的恒星,行星,卫星等系统。
1 lines • 340 kB
JavaScript
"use strict";var e,t,s,r=require("path"),i=require("fs"),n=require("os"),o=require("kleur"),a=require("lodash"),l=require("eventemitter3"),c=require("util"),h=require("log4js"),d=require("pino"),u=require("http"),p=require("zlib"),v=require("node-fetch"),g=require("dgram"),m=require("v8"),E=require("monitor-event-loop-delay"),f=require("perf_hooks"),S=require("recursive-watch"),T=require("etcd3"),_=require("ioredis"),I=require("cbor-x"),y=require("notepack.io"),N=require("lru-cache"),R=require("crypto"),b=require("redlock"),A=require("stream"),O=require("nats"),P=require("mqtt"),C=require("kafkajs"),D=require("events"),w=require("ipaddr.js"),U=require("net"),L=require("fastest-validator"),k=require("glob"),M="close",$="half_open",V="half_open_wait",x="open",H="failedProcessingPacket",q="failedSendRequestPacket",G="failedSendEventPacket",j="failedSendResponsePacket",B="failedNodesDiscovery",F="failedNodeDiscovery",Y="failedSendInfoPacket",K="failedSendPingPacket",z="failedSendHeartbeatPacket",Q="failedServicesStop",W="failedServiceLoad",Z="failedServiceRestart",J="failedServiceDestruction",X="clientError",ee="failedSendPing",te="publisherError",se="failedTopicCreation";class re 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 ie(e,t,s=Promise){return t?s.allSettled(e):s.all(e)}function ne(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 oe(){const e=(new Date).getMilliseconds();return e<10?`00${e}`:e>=10&&e<100?`0${e}`:`${e}`}function ae(e){return t=e,function(...e){return new Promise(((s,r)=>{try{s(t.apply(this,e))}catch(e){r(e)}}))};var t}function le(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 ce(e){return e.length>0&&-1!==["ctx","context"].indexOf(e[0].toLowerCase())}function he(e){Object.keys(require.cache).forEach((t=>{t===e&&delete require.cache[t]}))}class de{static hasComplexStructure(e){if(!Be(e))return!1;for(const t in e){const s=e[t];if(Be(s)||Array.isArray(s))return!0}return!1}static smartClone(e){return Be(e)?this.hasComplexStructure(e)?a.cloneDeep(e):{...e}:e}static structuredClone(e,t=!0){if(!Be(e))return e;const s={};for(const r in e){const i=e[r];t&&Ye(i)?s[r]=i:Be(i)||Array.isArray(i)?s[r]=a.cloneDeep(i):s[r]=i}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"}(e||(e={})),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"}(t||(t={})),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"}(s||(s={}));class ue extends re{constructor(t,r,i,n){super(t),this.code=r||s.BAD_GETWAY,this.type=i||e.BAD_GETWAY,this.data=n,this.retryable=!1}}class pe extends ue{constructor(e,t,s,r){super(e,t,s,r),this.retryable=!0}}class ve extends pe{constructor(){super("The star's transporter has disconnected. Please try again when a connection is reestablished.",502,e.BAD_GETWAY),this.stack=""}}class ge extends pe{}class me extends ue{constructor(e,t,r,i){super(e,t||s.RESPONSE_ERROR,r,i)}}class Ee extends pe{constructor(t={}){let r="";(null==t?void 0:t.nodeID)&&(null==t?void 0:t.action)?r=`Service '${null==t?void 0:t.action}' is not found on '${null==t?void 0:t.nodeID}' node.`:(null==t?void 0:t.action)&&(r=`Service '${null==t?void 0:t.action}' is not found.`),(null==t?void 0:t.service)&&(null==t?void 0:t.version)?r=`Service '${null==t?void 0:t.version}.${null==t?void 0:t.service}' not found.`:(null==t?void 0:t.service)&&(r=`Service '${null==t?void 0:t.service}' not found.`),super(r,s.SERVICE_NOT_FOUND,e.SERVICE_NOT_FOUND,t)}}class fe extends pe{constructor(t={}){let r="";r=(null==t?void 0:t.nodeID)?`Service '${null==t?void 0:t.action}' is not available on '${null==t?void 0:t.nodeID}' node.`:`Service '${null==t?void 0:t.action}' is not available.`,super(r,s.SERVICE_NOT_FOUND,e.SERVICE_NOT_AVAILABLE,t)}}class Se extends pe{constructor(t={}){super(`Request is timed out when call '${null==t?void 0:t.action}' action on '${null==t?void 0:t.nodeID}' node.`,s.REQUEST_TIMEOUT,e.REQUEST_TIMEOUT,t)}}class Te extends ue{constructor(t={}){super(`Calling '${t.action}' is skipped because timeout reached on '${t.nodeID}' node.`,s.REQUEST_SKIPPED,e.REQUEST_SKIPPED,t),this.retryable=!1}}class _e extends pe{constructor(t={}){super(`Request is rejected when call '${null==t?void 0:t.action}' action on '${null==t?void 0:t.nodeID}' node.`,s.REQUEST_REJECTED,e.REQUEST_REJECTED,t)}}class Ie extends pe{constructor(t={}){super(`Queue is full. Request '${null==t?void 0:t.action}' action on '${null==t?void 0:t.nodeID}' node is rejected.`,s.QUEUE_FULL,e.QUEUE_FULL,t)}}class ye extends me{constructor(t,r,i){super(t,s.VALIDATION_ERROR,r||e.VALIDATION_ERROR,i)}}class Ne extends ue{constructor(t){super(`Request level is reached the limit (${null==t?void 0:t.level}) on '${null==t?void 0:t.nodeID}' node.`,s.SERVICE_ERROR,e.MAX_CALL_LEVEL,t),this.retryable=!1}}class Re extends ue{constructor(t,r){super(t,s.SERVICE_ERROR,e.SERVICE_SCHEMA_ERROR,r)}}class be extends ue{constructor(t,r){super(t,s.SERVICE_ERROR,e.STAR_OPTIONS_ERROR,r)}}class Ae extends ue{constructor(t){t&&(null==t?void 0:t.service)?super(`Unable to stop '${null==t?void 0:t.service.name}' service gracefully.`,s.SERVICE_ERROR,e.GRACEFUL_STOP_TIMEOUT,t&&(null==t?void 0:t.service)?{name:null==t?void 0:t.service.name,version:null==t?void 0:t.service.version}:void 0):super("Unable to stop ServiceBroker gracefully.",s.SERVICE_ERROR,e.GRACEFUL_STOP_TIMEOUT)}}class Oe extends ue{constructor(t){super("Protocol version mismatch.",s.SERVICE_ERROR,e.PROTOCOL_VERSION_MISMATCH,t)}}class Pe extends ue{constructor(t){super("Invalid packet data.",s.SERVICE_ERROR,e.INVALID_PACKET_DATA,t)}}function Ce(e){switch(e.name){case t.UniverseError:return new ue(e.message,e.code,e.type,e.data);case t.UniverseRetryableError:return new pe(e.message,e.code,e.type,e.data);case t.StarServerError:return new ge(e.message,e.code,e.type,e.data);case t.StarClientError:return new me(e.message,e.code,e.type,e.data);case t.ValidationError:return new ye(e.message,e.type,e.data);case t.ServiceNotFoundError:case t.ServiceNotAvailableError:case t.RequestSkippedError:case t.RequestRejectedError:case t.RequestTimeoutError:return new Ee(e.data);case t.MaxCallLevelError:return new Ne(e.data);case t.QueueIsFullError:return new Ie(e.data);case t.GracefulStopTimeoutError:return new Ae(e.data);case t.ProtocolVersionMismatchError:return new Oe(e.data);case t.InvalidPacketDataError:return new Pe(e.data);case t.ServiceSchemaError:return new Re(e.message,e.data);case t.StarOptionsError:return new be(e.message,e.data);case t.StarDisconnectedError:return new ve}}class De{constructor(){this.star=null}init(e){this.star=e}restore(e,t){let s=this.restoreCustomError(e,t);return s||(s=Ce(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 ue(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 we(e){return e instanceof De?e:new De}class Ue{static createServiceSchemaError(e,t={},s){const r=this.buildEnhancedMessage(e,t),i=new Re(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 ue(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 ue||e instanceof Re)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}`,"检查参数传递是否正确"]})}}Ue.ERROR_CONTEXT_MAP=new Map([["SERVICE_SCHEMA_ERROR","服务模式配置错误"],["SERVICE_NOT_FOUND","服务未找到"],["ACTION_NOT_FOUND","动作未找到"],["EVENT_NOT_FOUND","事件未找到"],["VALIDATION_ERROR","参数验证失败"],["TIMEOUT_ERROR","操作超时"],["DEPENDENCY_ERROR","依赖服务错误"]]);class Le{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 ke{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 Me{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 $e{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 Ve=new Map,xe=[],He=["h","m","s","ms","μs","ns"],qe=[36e5,6e4,1e3,1,.001,1e-6],Ge=[];for(let e=0;e<256;e++)Ge[e]=(e<16?"0":"")+e.toString(16);class je extends re{}function Be(e){return null!==e&&"object"==typeof e&&!(e instanceof String)}function Fe(e){return null!==e&&("string"==typeof e||e instanceof String)}function Ye(e){return"function"==typeof e}function Ke(e){return null!=e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}function ze(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 Qe(e,t){const s=ze(t);let r=e;for(;r=Object.getPrototypeOf(r);){if(s==ze(r))return!0}return!1}function We(e){e.split(r.sep).reduce(((e,t)=>{const s=r.join(e,t,r.sep);return i.existsSync(s)||i.mkdirSync(s),s}),"")}function Ze(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return Ge[255&e]+Ge[e>>8&255]+Ge[e>>16&255]+Ge[e>>24&255]+"-"+Ge[255&t]+Ge[t>>8&255]+"-"+Ge[t>>16&15|64]+Ge[t>>24&255]+"-"+Ge[63&s|128]+Ge[s>>8&255]+"-"+Ge[s>>16&255]+Ge[s>>24&255]+Ge[255&r]+Ge[r>>8&255]+Ge[r>>16&255]+Ge[r>>24&255]}function Je(){var e;const t=[],s=[],r=n.networkInterfaces();for(let i in r)for(let n in r[i])if(null===(e=r[i])||void 0===e?void 0:e.length){const e=r[i][n];if("IPv4"===e.family){if(e.internal){s.push(e.address);break}t.push(e.address);break}}return t.length>0?t:s}function Xe(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=Ve.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,""),Ve.set(s,r)),r.test(e)}function et(e,t){1===arguments.length&&(t=e),-1===xe.indexOf(e)&&(console.warn(o.yellow().bold(`DeprecationWarning: ${t}`)),xe.push(e))}function tt(e){return Array.isArray(e)?e:[e]}function st(e){return Ye(e)?{handler:e}:e}function rt(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 it(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)+He[t]}return"now"}function nt(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 Te({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 Ne({nodeID:this.star.nodeID||"",level:this.level}));let n=this.star.call(e,t,s);return n.then((e=>(n.ctx&&nt(this,n.ctx.meta),e))).catch((e=>(n.ctx&&nt(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 Te({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 Ne({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=>nt(this,e.meta))),e))).catch((e=>(Array.isArray(r.ctx)&&r.ctx.length&&r.ctx.forEach((e=>nt(this,e.meta))),Promise.reject(e))))}emit(e,t,s){return Array.isArray(s)||Fe(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)||Fe(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 a.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"])}[c.inspect.custom](e,t){if(e<0)return null==t?void 0:t.stylize("[Context]","special");const s=c.inspect(this.toJSON(),t);return`${null==t?void 0:t.stylize("Context","special")}< ${s} >`}}var ot;!function(e){e.fatal="fatal",e.error="error",e.warn="warn",e.debug="debug",e.info="info",e.trace="trace"}(ot||(ot={}));const at=[ot.fatal,ot.error,ot.warn,ot.debug,ot.info,ot.trace];class lt{constructor(e){this.options=a.defaultsDeep(e,{level:ot.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(Fe(s))return s;if(Be(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=Ve.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,""),Ve.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 ct extends lt{constructor(e){super(e),this.options={},this.maxPrefixLength=0,this.levelColorStr={},this.options=a.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||(o.enabled=!1),this.objectPrinter=this.options.objectPrinter?this.options.objectPrinter:e=>c.inspect(e,{showHidden:!1,depth:2,colors:o.enabled,breakLength:Number.POSITIVE_INFINITY}),this.levelColorStr=at.reduce(((e,t)=>(e[t]=function(e){switch(e){case ot.fatal:return o.red().inverse;case ot.error:return o.red;case ot.warn:return o.yellow;case ot.debug:return o.magenta;case ot.trace:return o.gray;case ot.info:default:return o.green}}(t)(a.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():"",r=this.getNextColor(s).split(".").reduce(((e,t)=>e[t]||e()[t]),o)(s);e&&o.grey(e.nodeID+"/");const i=e=>e.map((e=>Be(e)||Array.isArray(e)?this.objectPrinter(e):e));if(Ye(t))return(s,r)=>t.call(this,s,r,e,{printArgs:i});if("json"===t)return o.enabled=!1,(t,s)=>[JSON.stringify({time:Date.now(),level:t,msg:i(s).join(" "),...e})];if("jsonext"===t)return(t,s)=>{const r={time:`${(new Date).toLocaleString("zh-CN",{hour12:!1})}:${oe()}`,level:t,message:"",...e};return s.length>0&&("object"==typeof s[0]?(Object.assign(r,s[0]),r.message=i(s.slice(1)).join(" ")):r.message=i(s).join(" ")),[JSON.stringify(r)]};if("simple"===t)return(e,t)=>[this.levelColorStr[e],"-",...i(t)];if("short"===t){const t=23+e.mod.length;return this.maxPrefixLength=Math.max(t,this.maxPrefixLength),(e,s)=>[o.grey(`[${(new Date).toDateString().substring(11)}]`),this.levelColorStr[e],r+this.padLeft(t)+o.grey(":"),...i(s)]}if("full"===t){const t=35+e.nodeID.length+e.mod.length;return this.maxPrefixLength=Math.max(t,this.maxPrefixLength),(e,s)=>[o.grey(`[${(new Date).toLocaleString("zh-CN",{hour12:!1})}:${oe()}]`),this.levelColorStr[e],r+this.padLeft(t)+o.grey(":"),...i(s)]}return(s,n)=>{const a=`${(new Date).toLocaleString("zh-CN",{hour12:!1})}:${oe()}`;return[this.render(t,{timestamp:o.grey(a),time:o.grey(a.substring(11)),level:this.levelColorStr[s],nodeID:o.grey(e.nodeID),mod:r,msg:i(n).join(" ")})]}}}const ht=c.promisify(i.appendFile);const dt={BaseLogger:lt,Formatted:ct,Console:class extends ct{constructor(e){super(e),this.maxPrefixLength=0}init(e){super.init(e),this.options.colors||(o.enabled=!1)}getLogHandler(e){const t=e?this.getLogLevel(e.mod):null;if(!t)return null;const s=at.indexOf(t),r=this.getFormatter(e);return(e,t)=>{if(at.indexOf(e)>s)return;const i=r(e,t);switch(e){case ot.fatal:case ot.error:return console.error(...i);case ot.warn:return console.warn(...i);default:return console.log(...i)}}}},File:class extends ct{constructor(e){super(e),this.logFolder="",this.options=a.defaultsDeep(this.options,{folder:"./logs",filename:"universer-{date}.log",eol:n.EOL,interval:1e3}),this.options.colors=!1,this.queue=[],this.timer=null,this.currentFileName=null,this.fs=null}init(e){super.init(e),this.logFolder=r.resolve(this.render(this.options.folder,{nodeID:this.star.nodeID,namespace:this.star.namespace})),We(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 e=(new Date).toISOString().substring(0,10);return r.join(this.logFolder,this.render(this.options.filename,{date:e,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 ht(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=at.indexOf(t),r=this.getFormatter(e);return(e,t)=>{if(at.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 lt{constructor(e){super(e),this.log4js=null,this.options=a.defaultsDeep(this.options,{})}init(e){super.init(e);try{this.options.log4js&&(this.log4js=h.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?(Ye(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 lt{constructor(e){super(e),this.pino=null,this.options=a.defaultsDeep(this.options,{pino:{options:null,destination:null}})}init(e){super.init(e);try{this.pino=d(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=Ye(this.options.createLogger)?this.options.createLogger(t,e):this.pino.child(e,{level:t});return(e,t)=>s[e](...t)}},LEVELS:at};function ut(e){if(!e)return null;let t=Object.keys(dt).find((t=>t.toLocaleLowerCase()==e.toLocaleLowerCase()));return t?dt[t]:void 0}var pt={Loggers:dt,resolve:function(e){if(Be(e)&&Qe(e,lt))return e;if(Fe(e)){let t=ut(e);if(t)return new t}else if(Be(e)){let t=ut(e.type);if(t)return new t(e.options);throw new be(`Invalid logger configuration. Type '${e.type}'`,{type:e.type})}throw new be(`Invalid logger configuration: '${e}'`,{type:e})},register:function(e,t){dt[e]=t}};const vt=()=>{},gt=process.cwd();class mt{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=[pt.resolve({type:"Console",options:{level:t}})]:(Array.isArray(e)||(e=[e]),this.appenders=a.compact(e).map((e=>Fe(e)?pt.resolve({type:e,options:{level:t}}):Ke(e)?pt.resolve(a.defaultsDeep({},e,{options:{level:t}})):pt.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(gt.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,i=a.compact(r.map((t=>t.getLogHandler(e)))),n=s.middlewares&&s.middlewares.registeredHooks.newLogEntry;return at.forEach((r=>{if(0==i.length&&!n)return t[r]=vt;t[r]=function(...t){var o;if(n&&s.middlewares&&(null===(o=s.middlewares)||void 0===o||o.callSyncHandlers("newLogEntry",[r,t,e],{})),0!=i.length)for(let e=0;e<i.length;e++)i[e](r,t)}})),t.appenders=r,this.cache.set(this.getBindingsKey(e),t),t}}var Et={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 ft{constructor(e){this.registry=null,this.star=null,this.logger=null,this.options=a.defaultsDeep(e,{includes:null,excludes:null,metricNamePrefix:null,metricNameSuffix:null,metricNameFormatter:null,labelNameFormatter:null}),Fe(this.options.includes)&&(this.options.includes=[this.options.includes]),Fe(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=>Xe(e,t))))&&!(Array.isArray(this.options.excludes)&&!this.options.excludes.every((t=>!Xe(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 St="metric";const Tt={Base:ft,Console:class extends ft{constructor(e){super(e),this.timer=null,this.options=a.defaultsDeep(this.options,{interval:5,logger:null,colors:!0,onlyChanges:!0}),this.options.colors||(o.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?o.gray("{}"):o.gray("{")+t.map((t=>`${o.gray(this.formatLabelName(t))}: ${o.magenta(""+e[t])}`)).join(", ")+o.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(o.gray(`------------------- [ METRICS START (${null==t?void 0:t.length}) ] -------------------`)),null==t||t.forEach((e=>{var t;this.log(o.cyan().bold(this.formatMetricName(e.name))+" "+o.gray("("+e.type+")")),0===e.values.size?this.log(o.gray(" <no values>")):(e.unit&&o.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 Et.TYPE_COUNTER:case Et.TYPE_GAUGE:case Et.TYPE_INFO:s=""===t.value?o.grey("<empty string>"):o.green().bold(t.value),null!=t.rate&&(s=s+o.grey(" | Rate: ")+(null!=t.rate?o.green().bold(t.rate.toFixed(2)):"-"));break;case Et.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=o.green().bold(e.join(" | "));break}}}))),this.log("")})),this.log(o.gray(`-------------------- [ METRICS END (${null==t?void 0:t.length}) ] --------------------`)),this.lastChanges.clear())}log(...e){var t;return Ye(this.options.logger)?this.options.logger(...e):null===(t=this.logger)||void 0===t?void 0:t.info(...e)}metricChanged(e,t,s,r){this.matchMetricName(e.name)&&this.lastChange