UNPKG

@e2/core

Version:

Enterprise Application Stack

16 lines (13 loc) 41.7 kB
/* Enterprise Web Application Stack */import{format,inspect}from'util';import{IsNullOrUndefined,decorateClassField,IsObject,IsString,IsFunction,AgentAttribute,decorateAgent}from'agentframework';import{sep,resolve,isAbsolute,join}from'path';import{existsSync,accessSync,readFileSync,writeFileSync,constants,writeSync,mkdirSync,statSync,createWriteStream,appendFileSync}from'fs';import{URL}from'url';export{URL}from'url';import{EventEmitter}from'events';import*as safeStringify from'json-stringify-safe';import{IncomingMessage,OutgoingMessage}from'http';import{hostname}from'os';import{operation}from'retry';import{createHash}from'crypto';class Exception extends Error{constructor(){const e=Exception.parseArguments(arguments);IsNullOrUndefined(e.msg)?super():super(e.msg),this.cause=e.err,this.code=e.code,this.context=e.obj;const t=this.constructor.prototype.constructor.name;this.name=IsNullOrUndefined(this.code)?this.constructor.prototype.constructor.name:'['+this.code+'] '+this.constructor.prototype.constructor.name;const n=this.message;IsNullOrUndefined(this.context)||(this.message+=' ('+inspect(this.context)+')'),Error.captureStackTrace(this,new.target),this.name=t,this.message=n,Exception.buildNestedErrorStackTrace(this,this.cause)}static parseArguments(e){let t,n,r,i,s,o=e.length-1;for(t=0;t<=o;t++)if(!n&&e[t]instanceof Error)n=e[t];else if(!r&&'number'==typeof e[t])r=e[t];else if(!i&&'object'==typeof e[t])i=e[t];else{s=e[t];break}if(o>t){let n=Array.prototype.slice.call(e,t+1);s=format(s,n)}return{err:n,code:r,obj:i,msg:s}}static buildNestedErrorStackTrace(e,t){let n=e.stack;t&&(n+='\r\nCaused By -> '+t.stack),e.stack=n}toJSON(){return{error:this.name,errcode:this.code,message:this.message,stack:this.stack}}}class MissingConfigurationValueException extends Exception{constructor(e){super('Missing required configuration setting: `'+e+'`')}}class ApplicationNotCreatedException extends Exception{constructor(e){if(e){let t;t='symbol'==typeof e?e.toString():e,super(`Application not created. Please call 'CreateApplication' first before access '${t}'`)}else super(`Application not created. Please call 'CreateApplication' first`)}}class NotSupportedException extends Exception{constructor(e){super(`${e} is not support`)}}class DeserializationException extends Exception{constructor(e,t){super(e,{data:t},`Unable to parse giving json string`)}}class FileStreamException extends Exception{}class FileWriteException extends Exception{}class TransporterException extends Exception{}class LoggerException extends Exception{}class File{constructor(e,t){this._file=e,this._permission=t}static resolve(e,t,n){t=resolve(e,t);let r;try{r=statSync(t)}catch(e){const n=new Error(`File '${t}' is not exist`);throw n.file=t,n.innerError=e,n}if(!r.isFile())throw new Error(`'${t}' is not a file`);try{accessSync(t,n)}catch(e){throw e.file=t,e}return new File(t,n)}toString(){return this._file}get path(){return this._file}get permission(){return this._permission}readAll(){return readFileSync(this._file,'utf8')}}File.Read=constants.R_OK,File.ReadWrite=constants.R_OK|constants.W_OK,File.Write=constants.W_OK;class Directory{constructor(e,t){this._directory=e,this._permission=t}static cwd(){return Directory.resolve(process.cwd(),'.',constants.R_OK)}static withReadPermission(e){return Directory.resolve(process.cwd(),e,constants.R_OK)}static withReadWritePermission(e){return Directory.resolve(process.cwd(),e,constants.R_OK|constants.W_OK)}static mkdir(e,t){const r=e.split(sep);let i=1,s=!1;for(;i++<r.length;){const e=r.slice(0,i).join(sep);try{mkdirSync(e,t),s=!0}catch(t){let n;try{n=statSync(e)}catch(e){throw t}if(!n.isDirectory())throw new Error(`'${e}' is not a directory`)}}return s}static resolve(e,t,n){t=resolve(e,t);let r;try{r=statSync(t)}catch(e){const n=new Error(`Directory '${t}' is not exist`);throw n.file=t,n.innerError=e,n}if(!r.isDirectory()){const e=new Error(`'${t}' is not a directory`);throw e.file=t,e}try{accessSync(t,n|constants.X_OK)}catch(e){throw e.file=t,e}return new Directory(t,n)}toString(){return this._directory}get path(){return this._directory}directory(e){if(isAbsolute(e))throw new Error(`'${e}' is not a relative path`);return Directory.resolve(this._directory,e,this._permission)}file(e){if(isAbsolute(e))throw new Error(`'${e}' is not a relative path`);return File.resolve(this.path,e,this._permission)}}/*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */function __decorate(e,t,n,s){var o,a=arguments.length,l=3>a?t:null===s?s=Object.getOwnPropertyDescriptor(t,n):s;if('object'==typeof Reflect&&'function'==typeof Reflect.decorate)l=Reflect.decorate(e,t,n,s);else for(var g=e.length-1;0<=g;g--)(o=e[g])&&(l=(3>a?o(l):3<a?o(t,n,l):o(t,n))||l);return 3<a&&l&&Object.defineProperty(t,n,l),l}function __metadata(e,t){if('object'==typeof Reflect&&'function'==typeof Reflect.metadata)return Reflect.metadata(e,t)}class ConfigurationAttribute{constructor(e){this.key=e}beforeDecorate(e,t,n){return!0}}function conf(e){return decorateClassField(new ConfigurationAttribute(e))}class ApplicationSettings{constructor(){this.NAME='app',this.VERSION='0.0.0',this.ENV='production',this.SECURE=!1,this.PRINT_SETTINGS=!0,this.AUTO_CREATE_DIRECTORY=!0,this.PACKAGE_FILE='package.json',this.EXIT_WAIT_TIMEOUT=1e4,this.HOME_DIR='',this.DATA_DIR='',this.CONF_DIR='',this.LOG_DIR='',this.LOG_LEVEL='info',this.LOG_CONSOLE=!0,this.LOG_CONSOLE_LEVEL='debug',this.LOG_CONSOLE_STYLE='default',this.LOG_WEBHOOK=!1,this.LOG_WEBHOOK_LEVEL='error',this.LOG_WEBHOOK_URL=''}}__decorate([conf(),__metadata('design:type',String)],ApplicationSettings.prototype,'NAME',void 0),__decorate([conf(),__metadata('design:type',String)],ApplicationSettings.prototype,'VERSION',void 0),__decorate([conf(),__metadata('design:type',String)],ApplicationSettings.prototype,'ENV',void 0),__decorate([conf(),__metadata('design:type',Boolean)],ApplicationSettings.prototype,'SECURE',void 0),__decorate([conf(),__metadata('design:type',Boolean)],ApplicationSettings.prototype,'PRINT_SETTINGS',void 0),__decorate([conf(),__metadata('design:type',Boolean)],ApplicationSettings.prototype,'AUTO_CREATE_DIRECTORY',void 0),__decorate([conf(),__metadata('design:type',String)],ApplicationSettings.prototype,'PACKAGE_FILE',void 0),__decorate([conf(),__metadata('design:type',Number)],ApplicationSettings.prototype,'EXIT_WAIT_TIMEOUT',void 0),__decorate([conf(),__metadata('design:type',String)],ApplicationSettings.prototype,'HOME_DIR',void 0),__decorate([conf(),__metadata('design:type',String)],ApplicationSettings.prototype,'DATA_DIR',void 0),__decorate([conf(),__metadata('design:type',String)],ApplicationSettings.prototype,'CONF_DIR',void 0),__decorate([conf(),__metadata('design:type',String)],ApplicationSettings.prototype,'LOG_DIR',void 0),__decorate([conf(),__metadata('design:type',String)],ApplicationSettings.prototype,'LOG_LEVEL',void 0),__decorate([conf(),__metadata('design:type',Boolean)],ApplicationSettings.prototype,'LOG_CONSOLE',void 0),__decorate([conf(),__metadata('design:type',String)],ApplicationSettings.prototype,'LOG_CONSOLE_LEVEL',void 0),__decorate([conf(),__metadata('design:type',String)],ApplicationSettings.prototype,'LOG_CONSOLE_STYLE',void 0),__decorate([conf(),__metadata('design:type',Boolean)],ApplicationSettings.prototype,'LOG_WEBHOOK',void 0),__decorate([conf(),__metadata('design:type',String)],ApplicationSettings.prototype,'LOG_WEBHOOK_LEVEL',void 0),__decorate([conf(),__metadata('design:type',String)],ApplicationSettings.prototype,'LOG_WEBHOOK_URL',void 0);class ApplicationOptions{static parse(e){const t=new ApplicationOptions;return t.root=e&&e.root||process.cwd(),t.confDir=e&&e.confDir||'conf',t.settings=e&&e.settings||ApplicationSettings,t}}function padStart(e,t,n=' '){let r=e+'';if(r.length>=t)return r;n=n+'',0===n.length&&(n=' ');let i=t-r.length,s=Math.ceil(i/n.length),o=n.repeat(s).slice(0,i);return o+r}function padEnd(e,t,n=' '){if(e.length<t){const r=t-e.length;return e+n.repeat(r)}return e}class Printer{static printSettings(e,t){e.PRINT_SETTINGS&&(t.info('Active configuration properties:'),Object.getOwnPropertyNames(e).map(t=>{let n=e[t];const r=t.toUpperCase();if(r.endsWith('_URL')&&n.length){const e=new URL(n);e.password&&e.password.length&&(e.password=this.mask(e.password),n=e.toString())}else this.sensitive(r)&&(n=this.mask(n));return IsObject(n)&&(n=inspect(n)),{key:t,value:n}}).forEach(e=>{t.info(`${e.key} = ${e.value}`)}))}static sensitive(e){return e.endsWith('_KEY')||e.endsWith('_PASSWORD')||e.endsWith('_SECRET')||e.endsWith('_TOKEN')}static mask(e){const t=e.length;let n='';for(let r=0;r<t;r++)n+=10<t&&(2>r||r>t-3)?e[r]:'*';return n}}const stopper=Symbol.for('stopPropagation');class StoppableEvent{stopPropagation(){this[stopper]=!0}isStopped(){return this[stopper]}}class StoppableEventEmitter extends EventEmitter{emitStoppableEvent(e,t){if(this.listenerCount(e)){const n=this.listeners(e);for(const e of n)if(e(t),t.isStopped())return!0}return!1}}var LogLevel;(function(e){e[e.trace=10]='trace',e[e.debug=20]='debug',e[e.info=30]='info',e[e.warn=40]='warn',e[e.error=50]='error',e[e.fatal=60]='fatal'})(LogLevel||(LogLevel={}));class ConsoleFormatter{constructor(e){this.levels={10:['TRACE','grey'],20:['DEBUG','cyan'],30:['INFO ','green'],40:['WARN ','yellow'],50:['ERROR','magenta'],60:['FATAL','red']},this.textColors='none'!==e}static stylize(e,t='white'){const n=ConsoleFormatter.colors[t];return`\x1B[${n[0]}m${e}\x1B[${n[1]}m`}format(e){const t=[],n=[];let r=this.extractTime(e),i=this.extractLevel(e);const s=this.isSingleLineMsg(e);let o=s?this.extractMsg(e):'';s||t.push(this.indent(this.extractMsg(e)));const a=this.extractError(e);a&&t.push(this.indent(a)),this.applyDetails(this.extractCustomDetails(e),t,n);let l,d=n.length?' ('+n.join(', ')+')':'',g=t.length?t.join('\r\n\t----\r\n')+'\r\n':'';return this.textColors?(l=ConsoleFormatter.stylize(i[0],i[1]),10>=e.level?(r=ConsoleFormatter.stylize(r,'grey'),o=o&&ConsoleFormatter.stylize(o,'grey'),d=d&&ConsoleFormatter.stylize(d,'grey'),g=g&&ConsoleFormatter.stylize(g,'grey')):(r=ConsoleFormatter.stylize(r),d=d&&ConsoleFormatter.stylize(d,'cyan'),g=g&&ConsoleFormatter.stylize(g,'grey'))):l=i[0],`[${r}] ${l}: ${o}${d}\r\n${g}`}indent(e){return'\t'+e.split(/\r?\n/).join('\r\n\t')}extractTime(e){const t=e.time;if(IsString(t)&&'T'===t[10]){const t=new Date(e.time);return t.toLocaleTimeString('zh-CN')+'.'+padStart(t.getMilliseconds(),3,'0')}else{const e=new Date;return e.toLocaleTimeString('zh-CN')+'.'+padStart(e.getMilliseconds(),3,'0')}}extractLevel(e){return this.levels[e.level]}isSingleLineMsg(e){return!IsString(e.msg)||-1===e.msg.indexOf('\n')}extractMsg(e){return e.msg||''}extractError(e){return e.stack?e.stack:void 0}extractCustomDetails(e){const t=['level','time','msg','name','pid','hostname','v','src','err','error','client_req','client_res','req','res','stack','req_id'],n=[],r={};return Object.keys(e).filter(e=>-1===t.indexOf(e)).forEach(function(t){let i=e[t]||'',s=!1;'string'!=typeof i&&(i=JSON.stringify(i,null,2),s=!0),-1!==i.indexOf('\n')||50<i.length?n.push(t+': '+i):s||-1===i.indexOf(' ')&&0!==i.length?r[t]=i:r[t]=JSON.stringify(i)}),{details:n,extras:r}}applyDetails(e,t,n){e.details.forEach(e=>{t.push(this.indent(e))}),Object.keys(e.extras).forEach(t=>{n.push(t+'='+e.extras[t])})}}ConsoleFormatter.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};const yaml=require('js-yaml'),stringify=safeStringify;function parseYAML(e){return yaml.load(e.readAll())}function dumpYAML(e,t){writeFileSync(t,yaml.dump(e))}function parseJSON(e){return JSON.parse(e.readAll())}function dumpJSON(e,t){writeFileSync(t,JSON.stringify(e))}function deserialize(t){try{return JSON.parse(t)}catch(n){throw new DeserializationException(n,t)}}function serialize(e){if(null==e)return'null';else{const t=typeof e;return'boolean'==t?e?'"true"':'"false"':'number'==t||'function'==t||'symbol'==t?'"'+e.toString()+'"':stringify(e)}}class Transporter extends EventEmitter{constructor(e){super(),this.level=e}log(e,t){e<this.level||(e===LogLevel.fatal?this.writeSync(t):this.write(t))}}class ConsoleLogTransporter extends Transporter{constructor(e,t){super(e),this.formatter=new ConsoleFormatter(t)}format(e){return this.formatter.format(deserialize(e))}write(e){process.stdout.write(this.format(e))}writeSync(e){writeSync(2,this.format(e))}}class FileLogTransporter extends Transporter{constructor(e,t){super(e),this.filename=t,this.errors=[],this.openWritableFileStream()}openWritableFileStream(){const e=this,t=this.stream=createWriteStream(this.filename,{flags:'a',encoding:'utf8'});t.on('open',function(t){e.fd=t}),t.on('error',function(t){const n=new FileStreamException(t);e.errors.push(n),e.emit('error',n)})}write(e){this.stream.write(e)}writeSync(e){try{this.fd?writeSync(this.fd,e):appendFileSync(this.filename,e)}catch(t){const n=new FileWriteException(t,{file:this.filename,fd:this.fd,transporter:this.constructor.name,data:e},'Unable to write log data');this.emit('error',n)}}}class Serializers{static req(e){return{method:e.method,url:e.url,headers:e.headers,remoteAddress:e.connection&&e.connection.remoteAddress,remotePort:e.connection&&e.connection.remotePort}}static res(e){return{statusCode:e.statusCode,header:e._header}}static error(e){return e.toJSON?e.toJSON():{error:e.name,stack:e.stack}}}class BaseLogger extends EventEmitter{context(){return this._context}trace(){this.compose(LogLevel.trace,arguments)}debug(){this.compose(LogLevel.debug,arguments)}log(){this.compose(LogLevel.info,arguments)}info(){this.compose(LogLevel.info,arguments)}warn(){this.compose(LogLevel.warn,arguments)}error(){this.compose(LogLevel.error,arguments)}fatal(){this.compose(LogLevel.fatal,arguments)}compose(e,t){let n,r,i,s,o=t.length-1;for(n=0;n<=o;n++)if(!r&&t[n]instanceof Error)r=t[n];else if(!i&&'object'==typeof t[n])i=t[n];else{s=t[n];break}if(o>n){let e=Array.prototype.slice.call(t,n+1);s=format(s,e)}return this.write({level:e,msg:s,err:r,obj:i,seal:this._seal})}}class Logger extends BaseLogger{constructor(e,t){super(),this.options=e,this.transporters=t;const n=this;for(const r of t)r.on('error',function(e){n.emit('error',new TransporterException(e))});this._context=Object.assign(Object.create(null),e.context),this.makeSeal(this._context),this.cache=[],this.options.serializers=e.serializers||{},this.options.serializers=Object.assign({error:Serializers.error,res:Serializers.res,req:Serializers.req},e.serializers)}child(e){return new ChildLogger(this,Object.assign(Object.create(this._context),e))}update(e){'object'==typeof e&&(Object.assign(this._context,e),this.makeSeal(this._context))}write(e){let t=this.serialize(e);for(const n of this.transporters)n.log(e.level,t)}makeSeal(e){this._seal=','+JSON.stringify(e).slice(1,-1)+'}\r\n'}makeCache(e,t){const n=new Date(t);return'{"level":'+e+',"time":"'+n.toISOString()+'","msg":'}getCache(e){const t=Date.now();return this.cache[0]!==t&&(this.cache=[t,[]]),this.cache[1][e]?this.cache[1][e]:this.cache[1][e]=this.makeCache(e,t)}serialize(e){const t=this.options.serializers;let n=this.getCache(e.level)+serialize(e.msg);if(null!=e.err){let r=t.error(e.err);for(const e of Object.keys(r))n+=',"'+e+'":'+serialize(r[e])}if(null!=e.obj){let r=e.obj;r.toJSON?r=r.toJSON():r instanceof Error?r=t.error(r):r instanceof IncomingMessage?r=t.req(r):r instanceof OutgoingMessage&&(r=t.res(r));for(const e of Object.keys(r)){const i=r[e];n+=null==i?',"'+e+'":null':i.toJSON&&'function'==typeof i.toJSON?',"'+e+'":'+serialize(i.toJSON()):'req'===e?',"'+e+'":'+serialize(t.req(i)):'res'===e?',"'+e+'":'+serialize(t.res(i)):',"'+e+'":'+serialize(r[e])}}return n+e.seal}}class ChildLogger extends BaseLogger{constructor(e,t){super(),this.parent=e,this._context=t,this.makeSeal(this._context)}child(e){return new ChildLogger(this,Object.assign(Object.create(this._context),e))}update(e){this._context=Object.assign(this._context,e),this.makeSeal(this._context)}write(e){this.parent.write(e)}makeSeal(e){this._seal='';let t=e;const n=[];for(;t!==Object.prototype&&null!==t;)n.push(t),t=Object.getPrototypeOf(t);for(const t of n.reverse())for(const e of Object.keys(t))this._seal+=',"'+e+'":'+serialize(t[e]);this._seal+='}\r\n'}}function fatal(e){const t=new Date,n=t.toLocaleTimeString()+'.'+padStart(t.getMilliseconds(),3,'0');writeSync(2,`[${n}] FATAL: ${e}\r\n`)}function CreateApplicationLogger(e){const t={context:{name:e.NAME,pid:process.pid,hostname:hostname(),v:0},serializers:{}},n=[];if(e.LOG_CONSOLE&&n.push(new ConsoleLogTransporter(LogLevel[e.LOG_CONSOLE_LEVEL],e.LOG_CONSOLE_STYLE)),e.LOG_DIR){const t=join(e.LOG_DIR,'agent.log');n.push(new FileLogTransporter(LogLevel[e.LOG_LEVEL],t))}const r=new Logger(t,n);return r.on('error',function(e){const t=new LoggerException(e);fatal(t.message+'\n'+t.stack)}),r}class ExitEvent extends StoppableEvent{}var ApplicationEvents;(function(e){e.signals='signals',e.uncaughtException='uncaughtException',e.unhandledRejection='unhandledRejection',e.exiting='exiting',e.exit='exit'})(ApplicationEvents||(ApplicationEvents={}));function info(e){if(null==e)writeSync(1,`\r\n`);else{const t=new Date,n=t.toLocaleTimeString()+'.'+padStart(t.getMilliseconds(),3,'0');writeSync(1,`[${n}] INFO : ${e}\r\n`)}}function warn(e){const t=new Date,n=t.toLocaleTimeString()+'.'+padStart(t.getMilliseconds(),3,'0');writeSync(1,`[${n}] WARN : ${e}\r\n`)}class Loader{constructor(e,t,n,r){this.root=t,this.conf=n,this._settings=r,this._settings.ENV=e.toLowerCase(),this._settings.SECURE='production'===this._settings.ENV,this._settings.HOME_DIR=t.path,this._settings.CONF_DIR=n.path}static loadSettings(e,t,n){info();const r=this.checkEnvironment(),i=e.directory(t),s=new Loader(r,e,i,n);return s.applyFileSettings('settings.yaml'),'production'!==r&&s.applyFileSettings('production.yaml'),s.applyFileSettings(r+'.yaml'),s.applyFileSettings(r+'.local.yaml'),s.applyPackageInfo(),s.applyEnvironmentSettings(),s.resolveAbsolutePath(),s.resolveAbsoluteFile(),s.applyCustomSettingFile(),info(),s._settings}static checkEnvironment(){let e=process.env.NODE_ENV;return e?info('\x1B[7mApplication loaded using the "'+process.env.NODE_ENV+'" configuration\x1B[0m'):(process.env.NODE_ENV=e='production',info('\x1B[33mNODE_ENV is not defined! Using default "'+process.env.NODE_ENV+'" configuration\x1B[0m')),e}applyFileSettings(e){let t,n;try{t=this.conf.file(e)}catch(e){return warn(`Application settings file '${e.file}' is not found, ignoring...`),!1}try{n=parseYAML(t)}catch(e){throw fatal(`Error parsing '${t.path}', reason: '${e.message}', exiting...`),e}if('object'!=typeof n){const e=new Error(`'${t.path}' is not validate settings file`);throw fatal(e.message),e}const r=[];for(const t of Object.keys(n))this._settings[t]=n[t],r.push(t);return info(`Applied ${r.length} key(s) from '${t.path}'`),!0}applyPackageInfo(){let e;try{e=this.root.file(this._settings.PACKAGE_FILE);try{const t=parseJSON(e);this._settings.VERSION=t.version||this._settings.VERSION,this._settings.NAME=t.name||this._settings.NAME}catch(e){warn(`Package file '${this._settings.PACKAGE_FILE}' parsing error, ignoring...`)}}catch(e){warn(`Package file '${e.file}' is not found, ignoring...`)}}applyEnvironmentSettings(){let e=!0;const t=[];for(const n of Object.keys(this._settings)){const r=this._settings[n];if(null!=process.env[n]){info('Applying '+n+' from environment');const e=process.env[n];try{this._settings[n]='string'==typeof e?JSON.parse(e):e}catch(t){this._settings[n]=e}}else null==r&&(e=!1,t.push(n),warn('Missing environment variable: '+n))}if(!e){const e=new Error(`Missing environment variable(s): ${t.join(',')}, exiting...`);throw fatal(e.message),e}}resolveAbsolutePath(){const e='_DIR',t=this._settings.AUTO_CREATE_DIRECTORY;t&&warn('Auto create directory is ON, all missing directory in the configuration will be created automatically.');for(const n of Object.keys(this._settings)){const r=this._settings[n];if(r&&r.length&&-1!==n.indexOf(e,n.length-e.length)&&r.split){const e=r.split(':'),i=e[0],s='rw'===e[1]?'rw':'ro',o=resolve(this.root.path,i);t&&Directory.mkdir(o)&&info(`Created directory '${o}'`),this._settings[n]='rw'==s?Directory.withReadWritePermission(o).path:Directory.withReadPermission(o).path}}}resolveAbsoluteFile(){const e='_FILE';for(const t of Object.keys(this._settings)){const n=this._settings[t];if(n&&n.length&&-1!==t.indexOf(e,t.length-e.length)&&n.split){const e=n.split(':'),r=e[0],i=e[1];this._settings[t]='rw'===i?File.resolve(this.root.path,r,constants.R_OK|constants.W_OK):'ro'===i?File.resolve(this.root.path,r,constants.R_OK):resolve(this.root.path,r)}}}applyCustomSettingFile(){if(this._settings.DATA_DIR){const e=join(this._settings.DATA_DIR,'settings.json');let t={};if(existsSync(e)){accessSync(e,constants.W_OK|constants.R_OK);const n=readFileSync(e,{encoding:'utf8'});try{t=JSON.parse(n)}catch(t){warn(`error parsing setting state file ${e}`)}for(const e of Object.keys(t))this._settings[e]=t[e]}}}}function CreateApplicationSettings(e,t,n){const r=Reflect.construct(n,[]);return Loader.loadSettings(e,t,r),r}class Updater{static updateSetting(t,e,n,r){if(!e.DATA_DIR)throw new Exception('Unable to update settings without config DATA_DIR');const i=join(e.DATA_DIR,'settings.json');let s={};if(existsSync(i)){accessSync(i,constants.W_OK|constants.R_OK);const e=readFileSync(i,{encoding:'utf8'});try{s=JSON.parse(e)}catch(n){t.error(n,`error parsing setting state file ${i}`)}}s.hasOwnProperty(n)&&typeof s[n]!=typeof r&&t.error({origin:typeof s[n],new:typeof r},`Unable to update settings because type mismatch`),s[n]=r;const o=JSON.stringify(s,null,2);writeFileSync(i,o,{encoding:'utf8',mode:420});const a=readFileSync(i,{encoding:'utf8'}),l=JSON.parse(a);return l[n]}}class TypeRegistry{constructor(e){this.parent=e,this.initializers=new Map,this.finalizers=new Map}registerType(e,t,n){if('function'!=typeof e)throw new TypeError('Unable to register non-function type with a factory');if(this.initializers.has(e))throw new TypeError('Type already registered with a factory');if(t=t||e[TypeRegistry.Initializer],'function'!=typeof t)throw new TypeError('Unable to register non-function type as an initializer factory');if(this.initializers.set(e,t),n=n||e[TypeRegistry.Finalizer],n){if('function'!=typeof n)throw new TypeError('Unable to register non-function type as a finalizer factory');this.finalizers.set(e,n)}}deleteType(e){this.initializers.delete(e),this.finalizers.delete(e)}getInitializerOf(e){return this.initializers.get(e)||this.parent&&this.parent.getInitializerOf(e)}getFinalizerOf(e){return this.finalizers.get(e)||this.parent&&this.parent.getFinalizerOf(e)}}TypeRegistry.Singleton=Symbol('Singleton'),TypeRegistry.Initializer=Symbol('TypeInitializer'),TypeRegistry.Finalizer=Symbol('TypeFinalizer');class Resolver{constructor(e,t){this.singletons=new Map,this.types=new Map,this.constructorParams=e,this.registry=new TypeRegistry(t)}construct(e,t){if(t)return this.create(e,!0);let n=this.singletons.get(e);return n||(n=this.create(e,!0),this.singletons.set(e,n)),n}resolve(e,t){if(t)return Promise.resolve(this.create(e));let n=this.singletons.get(e);return n||(n=this.create(e),this.singletons.set(e,n)),Promise.resolve(n)}registerSingleton(e,t){if(this.singletons.has(e))throw new TypeError('Type already registered with a singleton instance');this.singletons.set(e,t)}releaseSingleton(e){const t=this.singletons.get(e);if(t){const n=this.registry.getFinalizerOf(e);n&&Reflect.apply(n,e,[t,...this.constructorParams]),this.singletons.delete(e);const r=this.types.get(e);r&&r.delete(t)}}registerType(e,t,n){this.registry.registerType(e,t,n),this.types.set(e,new Set)}releaseType(e){const t=[],n=this.registry.getFinalizerOf(e);if(n){const r=this.types.get(e);if(r)for(const i of r)t.push(Reflect.apply(n,e,[i,...this.constructorParams]))}return this.singletons.delete(e),this.registry.deleteType(e),this.types.delete(e),t}create(e,t){const n=this.registry.getInitializerOf(e);if(n){const r=Reflect.apply(n,e,this.constructorParams);if(r instanceof Promise){if(t)throw new Exception({type:e.prototype.constructor.name,initializer:n.name},`Factory method return a Promise which is not allowed to happen inside resolver.construct()`);return r.then(t=>{let n=this.types.get(e);return n||(n=new Set,this.types.set(e,n)),n.add(t),t})}return r}if('function'!=typeof e)throw new TypeError('Unable to construct non-function type');return Reflect.construct(e,this.constructorParams)}}class Application extends StoppableEventEmitter{constructor(e){super(),this._id=Date.now(),this._options=ApplicationOptions.parse(e),this._root=Directory.withReadPermission(this._options.root),this._settings=CreateApplicationSettings(this._root,this._options.confDir,this._options.settings),this._logger=CreateApplicationLogger(this._settings),this._resolver=new Resolver([this]),this._identity={id:'0',address:'/ip6/::0/tcp/0'},Printer.printSettings(this._settings,this._logger)}get name(){return this.settings.NAME}setIdentity(e){this._identity=e}get identity(){return this._identity}get logger(){return this._logger}exit(e){this._logger.fatal(e);this.emitStoppableEvent(ApplicationEvents.exiting,new ExitEvent)||process.exit()}get root(){return this._root}directory(e=''){return this._root.directory(e)}file(e){return this._root.file(e)}get settings(){return this._settings}get(e,t){if(IsNullOrUndefined(this._settings[e]))if(IsNullOrUndefined(t))throw new MissingConfigurationValueException(e);else return t;return this._settings[e]}set(e,t){const n=Updater.updateSetting(this,this.settings,e,t);return this._settings[e]=n,n}has(e){return!IsNullOrUndefined(this._settings[e])}child(e){return this._logger.child.apply(this._logger,arguments)}update(e){return this._logger.update.apply(this._logger,arguments)}context(){return this._logger.context()}trace(e,t,...n){this._logger.trace.apply(this._logger,arguments)}debug(e,t,...n){this._logger.debug.apply(this._logger,arguments)}log(e,t,...n){this._logger.log.apply(this._logger,arguments)}info(e,t,...n){this._logger.info.apply(this._logger,arguments)}warn(e,t,...n){this._logger.warn.apply(this._logger,arguments)}error(e,t,...n){this._logger.error.apply(this._logger,arguments)}fatal(e,t,...n){this._logger.fatal.apply(this._logger,arguments)}construct(e,t){return this._resolver.construct(e,t)}resolve(e,t){return this._resolver.resolve(e,t)}registerSingleton(e,t){return this._resolver.registerSingleton(e,t)}releaseSingleton(e){return this._resolver.releaseSingleton(e)}registerType(e,t,n){return this._resolver.registerType(e,t,n)}releaseType(e){return this._resolver.releaseType(e)}}class SingletonAttribute{constructor(e){this.type=e}beforeDecorate(e,t,n){return!0}getInitializer(){return this}initialize(e,t){const n=t[0],r=this.type||e.design&&e.design.type;if(r===Object||!IsFunction(r))throw new TypeError(`Invalid type to inject`);if(n&&'function'==typeof n.construct)return n.construct(this.type||e.design&&e.design.type);throw new TypeError(`Application container not found`)}}class TransitAttribute{constructor(e){this.type=e}beforeDecorate(e,t,n){return!0}getInitializer(){return this}initialize(e,t){const n=t[0],r=this.type||e.design&&e.design.type;if(r===Object||!IsFunction(r))throw new TypeError(`Invalid type to inject`);if(n&&'function'==typeof n.construct)return n.construct(this.type||e.design&&e.design.type,!0);throw new TypeError(`Application container not found`)}}class ServiceAttribute{beforeDecorate(e,t,n){return!0}}function service(){return decorateAgent(new AgentAttribute({features:11}),void 0,[new ServiceAttribute])}function singleton(e){return decorateClassField(new SingletonAttribute(e))}function transit(e){return decorateClassField(new TransitAttribute(e))}const TypeCounter=new WeakMap;class Resolvable{constructor(e){this.settings=e.settings,this.logger=e.logger.child({cn:this.name});let t=TypeCounter.get(this.constructor)||0;t++,TypeCounter.set(this.constructor,t),this.logger.debug(`Creating new instance, total is ${t}`)}get name(){return this.constructor.prototype.constructor.name}}class Middleware extends Array{use(e){this.push(e)}next(e,t,n){let r,i=!1;if(!(n>this.length))return r=this[n]||t,r&&r(e,()=>{if(i)throw new Error('next() called multiple times');i=!0;const r=this.next(e,t,n+1);return Promise.resolve(r)})}compose(e,t){try{return Promise.resolve(this.next(e,t,0))}catch(e){return Promise.reject(e)}}}const STAR=42,SLASH=47,COLON=58;var RouteType;(function(e){e[e.STATIC=0]='STATIC',e[e.PARAM=1]='PARAM',e[e.ANY=2]='ANY'})(RouteType||(RouteType={}));class Route{constructor(e='',t=RouteType.STATIC,n=[],r=Object.create(null)){this.prefix=e,this.key=e.charCodeAt(0),this.type=t,this.children=n,this.data=r}node(e){let t=e.length;const n=[];for(let r=0;r<t;++r){const i=e.charCodeAt(r);if(i===COLON){const i=r+1;for(this.ensureChild(e.substring(0,r),RouteType.STATIC);r<t&&e.charCodeAt(r)!==SLASH;)r++;if(n.push(e.substring(i,r)),e=e.substring(0,i)+e.substring(r),r=i,t=e.length,r===t)return this.ensureChild(e.substring(0,r),RouteType.PARAM).setParams(n);this.ensureChild(e.substring(0,r),RouteType.PARAM)}else if(i===STAR)return this.ensureChild(e.substring(0,r),RouteType.STATIC),n.push('*'),this.ensureChild(e.substring(0,t),RouteType.ANY).setParams(n)}return this.ensureChild(e,RouteType.STATIC).setParams(n)}search(e){const t=[],n=this.findChild(e,t);if(!n)return null;const r=t.length,s=Object.create(null);if(n.parts)for(let e=0;e<r;++e)s[n.parts[e]]=t[e];return{node:n,params:s}}ensureChild(e,t){let n,r,i,s,o,a=this;const d=a.findOwnChildWithLabel(e.charCodeAt(0));if(d)a=d;else return a.createChild(e,t);for(;;){for(n=a.prefix,r=e.length,i=n.length,s=0,o=r<i?r:i;s<o&&e.charCodeAt(s)===n.charCodeAt(s);)s++;if(s<i){const i=new Route(n.substring(s),a.type,a.children,a.data);return a.parts&&a.parts.length&&i.setParams(a.parts),a.prefix=n.substring(0,s),a.type=RouteType.STATIC,a.children=[i],a.data=Object.create(null),s==r?a:a.createChild(e.substring(s),t)}if(s<r){e=e.substring(s);const n=a.findOwnChildWithLabel(e.charCodeAt(0));if(null!=n){a=n;continue}return a.createChild(e,t)}return a}}createChild(e,t){const n=new Route(e,t);return this.children.push(n),n}setParams(e){return this.parts=e.slice(0),this}findChild(e,t){const n=this,r=e.length,i=n.prefix;if(0===r||e===i)return n;const s=i.length;let o=0;for(const n=r<s?r:s;o<n&&e.charCodeAt(o)===i.charCodeAt(o);)o++;o===s&&(e=e.substring(o));const a=n.findOwnChild(e.charCodeAt(0),RouteType.STATIC);if(a){const n=a.findChild(e,t);if(n)return n}if(o!==s)return null;const d=n.findOwnChildByType(RouteType.PARAM);if(d){o=e.length;let n=0;for(;n<o&&e.charCodeAt(n)!==SLASH;)n++;t.push(e.substring(0,n));const r=d.findChild(e.substring(n),t);if(r)return r;t.pop()}const g=n.findOwnChildByType(RouteType.ANY);if(g){t.push(e);const n=g.findChild('',t);if(n)return n}return null}findOwnChild(e,t){for(let n=0,r=this.children.length;n<r;n++){const r=this.children[n];if(e===r.key&&t===r.type)return r}return null}findOwnChildWithLabel(e){for(let t=0,n=this.children.length;t<n;t++){const n=this.children[t];if(e===n.key)return n}return null}findOwnChildByType(e){for(let t=0,n=this.children.length;t<n;t++){const n=this.children[t];if(e===n.type)return n}return null}}class BaseX{constructor(e){this.map={},this.alphabet=e,this.base=e.length,this.leader=e.charAt(0);for(let t,n=0;n<e.length;n++){if(t=e.charAt(n),void 0!==this.map[t])throw new TypeError(t+' is ambiguous');this.map[t]=n}}static get singleton(){const e=this[TypeRegistry.Singleton],t=e?e():Reflect.construct(this,[]);return Reflect.defineProperty(this,'singleton',{value:t}),t}fromBuffer(e){if(0===e.length)return'';const t=[0];for(let n,r=0;r<e.length;++r){n=e[r];for(let e=0;e<t.length;++e)n+=t[e]<<8,t[e]=n%this.base,n=0|n/this.base;for(;0<n;)t.push(n%this.base),n=0|n/this.base}let n='';for(let t=0;0===e[t]&&t<e.length-1;++t)n+=this.leader;for(let r=t.length-1;0<=r;--r)n+=this.alphabet[t[r]];return n}toBuffer(e){let t=this.decodeUnsafe(e);if(t)return t;throw new Error('Non-base'+this.base+' character')}fromHex(e){return 1==e.length%2&&(e='0'+e),this.fromBuffer(Buffer.from(e,'hex'))}toHex(e){return this.toBuffer(e).toString('hex')}fromNumber(e){var t=Math.floor;if(isNaN(+e)||null===e||e===Number.POSITIVE_INFINITY)throw'The input is not valid';if(0>e)throw new Error('Can\'t represent negative numbers now');let n,r=t(e),i='';for(;n=r%this.base,i=this.alphabet.charAt(n)+i,r=t(r/this.base),0!=r;);return i}toNumber(t){let n=0;for(let r=0;r<t.length;r++)n=64*n+ +this.map[t.charAt(r)];return n}decodeUnsafe(e){if('string'!=typeof e)throw new TypeError('Expected String');if(0===e.length)return Buffer.allocUnsafe(0);let t=[0];for(let n,r=0;r<e.length;r++){if(n=this.map[e[r]],void 0===n)throw new Error(`Unknown character ${e[r]} to decode`);let i=n;for(let e=0;e<t.length;++e)i+=t[e]*this.base,t[e]=255&i,i>>=8;for(;0<i;)t.push(255&i),i>>=8}for(let n=0;e[n]===this.leader&&n<e.length-1;++n)t.push(0);return Buffer.from(t.reverse())}}class Base62 extends BaseX{constructor(){super('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')}static fromBuffer(e){return this.singleton.fromBuffer(e)}static toBuffer(e){return this.singleton.toBuffer(e)}static fromHex(e){return this.singleton.fromHex(e)}static toHex(e){return this.singleton.toHex(e)}static fromNumber(e){return this.singleton.fromNumber(e)}static toNumber(e){return this.singleton.toNumber(e)}}class Base58 extends BaseX{constructor(){super('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz')}static fromBuffer(e){return this.singleton.fromBuffer(e)}static toBuffer(e){return this.singleton.toBuffer(e)}static fromHex(e){return this.singleton.fromHex(e)}static toHex(e){return this.singleton.toHex(e)}static fromNumber(e){return this.singleton.fromNumber(e)}static toNumber(e){return this.singleton.toNumber(e)}}function retry(e,t={retries:3,factor:3,minTimeout:1e3,maxTimeout:6e4,randomize:!0}){return new Promise((n,r)=>{const i=operation(t),s=e=>{r(e||new Error('Aborted'))},o=e=>{i.retry(e)||r(i.mainError())};i.attempt(t=>{let r;try{r=e(s,t,i.errors())}catch(e){return o(e)}r&&IsFunction(r.then)?r.then(n,o):n(r)})})}class Identity{}const globalKey=Symbol.for('e2.global');function CreateApplication(e){return global[globalKey]=new Application(e)}function SetCurrentApplication(e){global[globalKey]=e}function CurrentApplication(){return global[globalKey]}const hl=[];for(let e=0;256>e;e++)hl[e]=(15&e>>4).toString(16)+(15&e).toString(16);class Hash52{static toNumber(e){let t,n=e.length-3,r=0,s=8997,o=0,a=33826,l=0,d=40164,g=0,p=52210;for(t=0;t<n;)s^=e.charCodeAt(t++),r=435*s,o=435*a,l=435*d,g=435*p,l+=s<<8,g+=a<<8,o+=r>>>16,s=65535&r,l+=o>>>16,a=65535&o,p=65535&g+(l>>>16),d=65535&l,s^=e.charCodeAt(t++),r=435*s,o=435*a,l=435*d,g=435*p,l+=s<<8,g+=a<<8,o+=r>>>16,s=65535&r,l+=o>>>16,a=65535&o,p=65535&g+(l>>>16),d=65535&l,s^=e.charCodeAt(t++),r=435*s,o=435*a,l=435*d,g=435*p,l+=s<<8,g+=a<<8,o+=r>>>16,s=65535&r,l+=o>>>16,a=65535&o,p=65535&g+(l>>>16),d=65535&l,s^=e.charCodeAt(t++),r=435*s,o=435*a,l=435*d,g=435*p,l+=s<<8,g+=a<<8,o+=r>>>16,s=65535&r,l+=o>>>16,a=65535&o,p=65535&g+(l>>>16),d=65535&l;for(;t<n+3;)s^=e.charCodeAt(t++),r=435*s,o=435*a,l=435*d,g=435*p,l+=s<<8,g+=a<<8,o+=r>>>16,s=65535&r,l+=o>>>16,a=65535&o,p=65535&g+(l>>>16),d=65535&l;return 281474976710656*(15&p)+4294967296*d+65536*a+(s^p>>4)}static toBuffer(e){return new Buffer(this.toArray(e))}static toArray(e){let t,n=e.length-3,r=0,s=8997,o=0,a=33826,l=0,d=40164,g=0,p=52210;for(t=0;t<n;)s^=e.charCodeAt(t++),r=435*s,o=435*a,l=435*d,g=435*p,l+=s<<8,g+=a<<8,o+=r>>>16,s=65535&r,l+=o>>>16,a=65535&o,p=65535&g+(l>>>16),d=65535&l,s^=e.charCodeAt(t++),r=435*s,o=435*a,l=435*d,g=435*p,l+=s<<8,g+=a<<8,o+=r>>>16,s=65535&r,l+=o>>>16,a=65535&o,p=65535&g+(l>>>16),d=65535&l,s^=e.charCodeAt(t++),r=435*s,o=435*a,l=435*d,g=435*p,l+=s<<8,g+=a<<8,o+=r>>>16,s=65535&r,l+=o>>>16,a=65535&o,p=65535&g+(l>>>16),d=65535&l,s^=e.charCodeAt(t++),r=435*s,o=435*a,l=435*d,g=435*p,l+=s<<8,g+=a<<8,o+=r>>>16,s=65535&r,l+=o>>>16,a=65535&o,p=65535&g+(l>>>16),d=65535&l;for(;t<n+3;)s^=e.charCodeAt(t++),r=435*s,o=435*a,l=435*d,g=435*p,l+=s<<8,g+=a<<8,o+=r>>>16,s=65535&r,l+=o>>>16,a=65535&o,p=65535&g+(l>>>16),d=65535&l;const c=new Uint8Array(7);return c[0]=15&p,c[1]=d>>8,c[2]=255&d,c[3]=a>>8,c[4]=255&a,c[5]=s>>8^p>>12,c[6]=255&(s^p>>4),c}}class Hash32{static toNumber(e){const t=this.toArray(e);return 16777216*t[0]+65536*t[1]+256*t[2]+t[3]}static toBuffer(e){return Buffer.from(this.toArray(e))}static toArray(e){let t,n=e.length-3,r=0,s=40389,o=0,a=33052;for(t=0;t<n;)s^=e.charCodeAt(t++),r=403*s,o=403*a,o+=s<<8,a=65535&o+(r>>>16),s=65535&r,s^=e.charCodeAt(t++),r=403*s,o=403*a,o+=s<<8,a=65535&o+(r>>>16),s=65535&r,s^=e.charCodeAt(t++),r=403*s,o=403*a,o+=s<<8,a=65535&o+(r>>>16),s=65535&r,s^=e.charCodeAt(t++),r=403*s,o=403*a,o+=s<<8,a=65535&o+(r>>>16),s=65535&r;for(;t<n+3;)s^=e.charCodeAt(t++),r=403*s,o=403*a,o+=s<<8,a=65535&o+(r>>>16),s=65535&r;const l=new Uint8Array(4);return l[0]=255&a>>>8,l[1]=255&a,l[2]=255&s>>>8,l[3]=255&s,l}}class Hash24{static toNumber(e){const t=this.toArray(e);return 65536*t[0]+256*t[1]+t[2]}static toBuffer(e){return Buffer.from(this.toArray(e))}static toArray(e){const t=Hash32.toArray(e),n=new Uint8Array(3);return n[0]=t[0]^t[3],n[1]=t[1]^t[3],n[2]=t[2]^t[3],n}}class Hash16{static toNumber(e){const t=this.toArray(e);return 256*t[0]+t[1]}static toBuffer(e){const t=this.toArray(e);return Buffer.from(t)}static toArray(e){const t=Hash32.toArray(e),n=new Uint8Array(2);return n[0]=t[0]^t[1],n[1]=t[2]^t[3],n}}const MACHINE_ID=Hash24.toArray(require('os').hostname()),checkForHexRegExp=/^[0-9a-fA-F]{24}$/;class ObjectId{constructor(e){if(this._bsontype='ObjectID',e instanceof ObjectId)return e;if(null==e)this.id=ObjectId.generate(~~(Date.now()/1e3));else if(Buffer.isBuffer(e)){if(12!==e.byteLength)throw new TypeError('Buffer passed in must be 12 bytes length');this.id=e}else if('number'==typeof e)this.id=ObjectId.generate(e);else if(e instanceof Date)this.id=ObjectId.generate(~~(e.getTime()/1e3));else if(24===e.length)this.id=new Buffer(e,'hex');else if(12===e.length)this.id=new Buffer(e,'binary');else throw new TypeError('Argument passed in must be a string of 24 hex characters or a string of 12 binary characters')}get generationTime(){return this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24}set generationTime(e){this.id[3]=255&e,this.id[2]=255&e>>8,this.id[1]=255&e>>16,this.id[0]=255&e>>24}getTimestamp(){const e=new Date,t=this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24;return e.setTime(1e3*Math.floor(t)),e}equals(e){if(e instanceof ObjectId)return 0===Buffer.compare(this.id,e.id);return 12===e.length?e===this.id.toString('binary'):!(24!==e.length)&&e===this.id.toString('hex')}toHexString(){return this.id.toString('hex')}toString(e){return this.id.toString(e||'hex')}inspect(){return this.id.toString('hex')}toJSON(){return this.id.toString('hex')}static createFromTime(e){const t=new Buffer([0,0,0,0,0,0,0,0,0,0,0,0]);return t[3]=255&e,t[2]=255&e>>8,t[1]=255&e>>16,t[0]=255&e>>24,new ObjectId(t)}static createFromHexString(e){return new ObjectId(e)}static isValid(e){if('string'==typeof e)return 24===e.length?checkForHexRegExp.test(e):12===e.length;return!!(Buffer.isBuffer(e)&&12===e.length)||e instanceof ObjectId}static generate(e){const t=('undefined'==typeof process||1===process.pid?Math.floor(1e5*Math.random()):process.pid)%65535,n=ObjectId.get_inc(),r=new Buffer(12);return r[3]=255&e,r[2]=255&e>>8,r[1]=255&e>>16,r[0]=255&e>>24,r[6]=MACHINE_ID[0],r[5]=MACHINE_ID[1],r[4]=MACHINE_ID[2],r[8]=255&t,r[7]=255&t>>8,r[11]=255&n,r[10]=255&n>>8,r[9]=255&n>>16,r}static get_inc(){return ObjectId.index=(ObjectId.index+1)%16777215}}ObjectId.index=~~(16777215*Math.random());function CreateHashedObjectId(e){const t=createHash('md5');for(const n of e)if(Buffer.isBuffer(n))t.update(n);else if('string'==typeof n)t.update(Buffer.from(n,'utf8'));else if('number'==typeof n){if(!Number.isSafeInteger(n))throw new TypeError('Hashed ObjectID input not support unsafe integer');const e=Buffer.alloc(8);e.writeDoubleLE(n,0),t.update(e)}else throw new TypeError('Hashed ObjectID input not support: '+typeof n);const n=t.digest(),r=Buffer.allocUnsafe(12);return n.copy(r,0,0,12),r[8]^=n[12],r[9]^=n[13],r[10]^=n[14],r[11]^=n[15],new ObjectId(r)}export{Exception,FileStreamException,TransporterException,LoggerException,MissingConfigurationValueException,ApplicationNotCreatedException,NotSupportedException,Application,ApplicationSettings,conf,ConfigurationAttribute,LogLevel,parseJSON,parseYAML,dumpJSON,dumpYAML,deserialize,serialize,service,singleton,transit,Resolver,Resolvable,TypeRegistry,Middleware,Route,RouteType,Directory,File,BaseX,Base62,Base58,retry,Identity,CreateApplication,CurrentApplication,SetCurrentApplication,padStart,padEnd,Hash52,Hash32,Hash24,Hash16,ObjectId,CreateHashedObjectId}; //# sourceMappingURL=index.mjs.map