UNPKG

27.5 kBJavaScriptView Raw
1/* Enterprise Web Application Stack */'use strict';Object.defineProperty(exports,'__esModule',{value:!0});function _interopDefault(a){return a&&'object'==typeof a&&'default'in a?a['default']:a}var lib=require('@e2/lib'),crypto=require('crypto'),agentframework=require('agentframework'),path=require('path'),fs=require('fs'),stringify=_interopDefault(require('fast-safe-stringify')),util=require('util');const hl=[];for(let a=0;256>a;a++)hl[a]=(15&a>>4).toString(16)+(15&a).toString(16);class Hash52{static toNumber(a){let b,c=a.length-3,d=0,e=8997,f=0,g=33826,h=0,j=40164,k=0,l=52210;for(b=0;b<c;)e^=a.charCodeAt(b++),d=435*e,f=435*g,h=435*j,k=435*l,h+=e<<8,k+=g<<8,f+=d>>>16,e=65535&d,h+=f>>>16,g=65535&f,l=65535&k+(h>>>16),j=65535&h,e^=a.charCodeAt(b++),d=435*e,f=435*g,h=435*j,k=435*l,h+=e<<8,k+=g<<8,f+=d>>>16,e=65535&d,h+=f>>>16,g=65535&f,l=65535&k+(h>>>16),j=65535&h,e^=a.charCodeAt(b++),d=435*e,f=435*g,h=435*j,k=435*l,h+=e<<8,k+=g<<8,f+=d>>>16,e=65535&d,h+=f>>>16,g=65535&f,l=65535&k+(h>>>16),j=65535&h,e^=a.charCodeAt(b++),d=435*e,f=435*g,h=435*j,k=435*l,h+=e<<8,k+=g<<8,f+=d>>>16,e=65535&d,h+=f>>>16,g=65535&f,l=65535&k+(h>>>16),j=65535&h;for(;b<c+3;)e^=a.charCodeAt(b++),d=435*e,f=435*g,h=435*j,k=435*l,h+=e<<8,k+=g<<8,f+=d>>>16,e=65535&d,h+=f>>>16,g=65535&f,l=65535&k+(h>>>16),j=65535&h;return 281474976710656*(15&l)+4294967296*j+65536*g+(e^l>>4)}static toBuffer(a){return new Buffer(this.toArray(a))}static toArray(a){let b,c=a.length-3,d=0,e=8997,f=0,g=33826,h=0,j=40164,k=0,l=52210;for(b=0;b<c;)e^=a.charCodeAt(b++),d=435*e,f=435*g,h=435*j,k=435*l,h+=e<<8,k+=g<<8,f+=d>>>16,e=65535&d,h+=f>>>16,g=65535&f,l=65535&k+(h>>>16),j=65535&h,e^=a.charCodeAt(b++),d=435*e,f=435*g,h=435*j,k=435*l,h+=e<<8,k+=g<<8,f+=d>>>16,e=65535&d,h+=f>>>16,g=65535&f,l=65535&k+(h>>>16),j=65535&h,e^=a.charCodeAt(b++),d=435*e,f=435*g,h=435*j,k=435*l,h+=e<<8,k+=g<<8,f+=d>>>16,e=65535&d,h+=f>>>16,g=65535&f,l=65535&k+(h>>>16),j=65535&h,e^=a.charCodeAt(b++),d=435*e,f=435*g,h=435*j,k=435*l,h+=e<<8,k+=g<<8,f+=d>>>16,e=65535&d,h+=f>>>16,g=65535&f,l=65535&k+(h>>>16),j=65535&h;for(;b<c+3;)e^=a.charCodeAt(b++),d=435*e,f=435*g,h=435*j,k=435*l,h+=e<<8,k+=g<<8,f+=d>>>16,e=65535&d,h+=f>>>16,g=65535&f,l=65535&k+(h>>>16),j=65535&h;const m=new Uint8Array(7);return m[0]=15&l,m[1]=j>>8,m[2]=255&j,m[3]=g>>8,m[4]=255&g,m[5]=e>>8^l>>12,m[6]=255&(e^l>>4),m}}class Hash32{static toNumber(a){const b=this.toArray(a);return 16777216*b[0]+65536*b[1]+256*b[2]+b[3]}static toBuffer(a){return Buffer.from(this.toArray(a))}static toArray(a){let b,c=a.length-3,d=0,e=40389,f=0,g=33052;for(b=0;b<c;)e^=a.charCodeAt(b++),d=403*e,f=403*g,f+=e<<8,g=65535&f+(d>>>16),e=65535&d,e^=a.charCodeAt(b++),d=403*e,f=403*g,f+=e<<8,g=65535&f+(d>>>16),e=65535&d,e^=a.charCodeAt(b++),d=403*e,f=403*g,f+=e<<8,g=65535&f+(d>>>16),e=65535&d,e^=a.charCodeAt(b++),d=403*e,f=403*g,f+=e<<8,g=65535&f+(d>>>16),e=65535&d;for(;b<c+3;)e^=a.charCodeAt(b++),d=403*e,f=403*g,f+=e<<8,g=65535&f+(d>>>16),e=65535&d;const h=new Uint8Array(4);return h[0]=255&g>>>8,h[1]=255&g,h[2]=255&e>>>8,h[3]=255&e,h}}class Hash24{static toNumber(a){const b=this.toArray(a);return 65536*b[0]+256*b[1]+b[2]}static toBuffer(a){return Buffer.from(this.toArray(a))}static toArray(a){const b=Hash32.toArray(a),c=new Uint8Array(3);return c[0]=b[0]^b[3],c[1]=b[1]^b[3],c[2]=b[2]^b[3],c}}class Hash16{static toNumber(a){const b=this.toArray(a);return 256*b[0]+b[1]}static toBuffer(a){const b=this.toArray(a);return Buffer.from(b)}static toArray(a){const b=Hash32.toArray(a),c=new Uint8Array(2);return c[0]=b[0]^b[1],c[1]=b[2]^b[3],c}}class BaseX{constructor(a){this.map={},this.alphabet=a,this.base=a.length,this.leader=a.charAt(0);for(let b,c=0;c<a.length;c++){if(b=a.charAt(c),void 0!==this.map[b])throw new TypeError(b+' is ambiguous');this.map[b]=c}}static get singleton(){const a=this[lib.Symbols.Singleton],b=a?a():Reflect.construct(this,[]);return Reflect.defineProperty(this,'singleton',{value:b}),b}fromBuffer(a){if(0===a.length)return'';const b=[0];for(let c,d=0;d<a.length;++d){c=a[d];for(let a=0;a<b.length;++a)c+=b[a]<<8,b[a]=c%this.base,c=0|c/this.base;for(;0<c;)b.push(c%this.base),c=0|c/this.base}let c='';for(let b=0;0===a[b]&&b<a.length-1;++b)c+=this.leader;for(let d=b.length-1;0<=d;--d)c+=this.alphabet[b[d]];return c}toBuffer(a){let b=this.decodeUnsafe(a);if(b)return b;throw new Error('Non-base'+this.base+' character')}fromHex(a){return 1==a.length%2&&(a='0'+a),this.fromBuffer(Buffer.from(a,'hex'))}toHex(a){return this.toBuffer(a).toString('hex')}fromNumber(a){var b=Math.floor;if(isNaN(+a)||null===a||a===Number.POSITIVE_INFINITY)throw'The input is not valid';if(0>a)throw new Error('Can\'t represent negative numbers now');let c,d=b(a),e='';for(;c=d%this.base,e=this.alphabet.charAt(c)+e,d=b(d/this.base),0!=d;);return e}toNumber(a){let b=0;for(let c=0;c<a.length;c++)b=64*b+ +this.map[a.charAt(c)];return b}decodeUnsafe(a){if('string'!=typeof a)throw new TypeError('Expected String');if(0===a.length)return Buffer.allocUnsafe(0);let b=[0];for(let c,d=0;d<a.length;d++){if(c=this.map[a[d]],void 0===c)throw new Error(`Unknown character ${a[d]} to decode`);let e=c;for(let a=0;a<b.length;++a)e+=b[a]*this.base,b[a]=255&e,e>>=8;for(;0<e;)b.push(255&e),e>>=8}for(let c=0;a[c]===this.leader&&c<a.length-1;++c)b.push(0);return Buffer.from(b.reverse())}}class Base58 extends BaseX{constructor(){super('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz')}static fromBuffer(a){return this.singleton.fromBuffer(a)}static toBuffer(a){return this.singleton.toBuffer(a)}static fromHex(a){return this.singleton.fromHex(a)}static toHex(a){return this.singleton.toHex(a)}static fromNumber(a){return this.singleton.fromNumber(a)}static toNumber(a){return this.singleton.toNumber(a)}}class Base62 extends BaseX{constructor(){super('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')}static fromBuffer(a){return this.singleton.fromBuffer(a)}static toBuffer(a){return this.singleton.toBuffer(a)}static fromHex(a){return this.singleton.fromHex(a)}static toHex(a){return this.singleton.toHex(a)}static fromNumber(a){return this.singleton.fromNumber(a)}static toNumber(a){return this.singleton.toNumber(a)}}const MACHINE_ID=Hash24.toArray(require('os').hostname()),checkForHexRegExp=/^[0-9a-fA-F]{24}$/;class ObjectId{constructor(a){if(this._bsontype='ObjectID',a instanceof ObjectId)return a;if(null==a)this.id=ObjectId.generate(~~(Date.now()/1e3));else if(Buffer.isBuffer(a)){if(12!==a.byteLength)throw new TypeError('Buffer passed in must be 12 bytes length');this.id=a}else if('number'==typeof a)this.id=ObjectId.generate(a);else if(a instanceof Date)this.id=ObjectId.generate(~~(a.getTime()/1e3));else if(24===a.length)this.id=new Buffer(a,'hex');else if(12===a.length)this.id=new Buffer(a,'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(a){this.id[3]=255&a,this.id[2]=255&a>>8,this.id[1]=255&a>>16,this.id[0]=255&a>>24}getTimestamp(){const a=new Date,b=this.id[3]|this.id[2]<<8|this.id[1]<<16|this.id[0]<<24;return a.setTime(1e3*Math.floor(b)),a}equals(a){if(a instanceof ObjectId)return 0===Buffer.compare(this.id,a.id);return 12===a.length?a===this.id.toString('binary'):!(24!==a.length)&&a===this.id.toString('hex')}toHexString(){return this.id.toString('hex')}toString(a){return this.id.toString(a||'hex')}inspect(){return this.id.toString('hex')}toJSON(){return this.id.toString('hex')}static createFromTime(a){const b=new Buffer([0,0,0,0,0,0,0,0,0,0,0,0]);return b[3]=255&a,b[2]=255&a>>8,b[1]=255&a>>16,b[0]=255&a>>24,new ObjectId(b)}static createFromHexString(a){return new ObjectId(a)}static isValid(a){if('string'==typeof a)return 24===a.length?checkForHexRegExp.test(a):12===a.length;return!!(Buffer.isBuffer(a)&&12===a.length)||a instanceof ObjectId}static generate(a){const b=('undefined'==typeof process||1===process.pid?Math.floor(1e5*Math.random()):process.pid)%65535,c=ObjectId.get_inc(),d=new Buffer(12);return d[3]=255&a,d[2]=255&a>>8,d[1]=255&a>>16,d[0]=255&a>>24,d[6]=MACHINE_ID[0],d[5]=MACHINE_ID[1],d[4]=MACHINE_ID[2],d[8]=255&b,d[7]=255&b>>8,d[11]=255&c,d[10]=255&c>>8,d[9]=255&c>>16,d}static get_inc(){return ObjectId.index=(ObjectId.index+1)%16777215}}ObjectId.index=~~(16777215*Math.random());function CreateHashedObjectId(a,b='md5'){const c=crypto.createHash(b);a=Array.isArray(a)?a:[a];for(const d of a)if(Buffer.isBuffer(d))c.update(d);else if('string'==typeof d)c.update(Buffer.from(d,'utf8'));else if('number'==typeof d){if(!Number.isSafeInteger(d))throw new TypeError('Hashed ObjectID input not support unsafe integer');const a=Buffer.alloc(8);a.writeDoubleLE(d,0),c.update(a)}else{const a=lib.CreateFlattenObject(d),b=Object.keys(a).sort(),e=[];for(const c of b)e.push([c,a[c]]);c.update(JSON.stringify(e))}const d=c.digest(),e=Buffer.allocUnsafe(12);return d.copy(e,0,0,12),e[8]^=d[12],e[9]^=d[13],e[10]^=d[14],e[11]^=d[15],new ObjectId(e)}class FileStreamException extends agentframework.Exception{}class FileWriteException extends agentframework.Exception{}class File{constructor(a,b){this._file=a,this._permission=b}static resolve(a,b,c){b=path.resolve(a,b);let d;try{d=fs.statSync(b)}catch(a){const c=new Error(`File '${b}' is not exist`);throw c.file=b,c.innerError=a,c}if(!d.isFile())throw new Error(`'${b}' is not a file`);try{fs.accessSync(b,c)}catch(a){throw a.file=b,a}return new File(b,c)}toString(){return this._file}get path(){return this._file}get permission(){return this._permission}readAll(){return fs.readFileSync(this._file,'utf8')}}File.Read=fs.constants.R_OK,File.ReadWrite=fs.constants.R_OK|fs.constants.W_OK,File.Write=fs.constants.W_OK;class Directory{constructor(a,b){this._directory=a,this._permission=b}static cwd(){return Directory.resolve(process.cwd(),'.',fs.constants.R_OK)}static withReadPermission(a){return Directory.resolve(process.cwd(),a,fs.constants.R_OK)}static withReadWritePermission(a){return Directory.resolve(process.cwd(),a,fs.constants.R_OK|fs.constants.W_OK)}static mkdir(a,b){const c=a.split(path.sep);let d=1,e=!1;for(;d++<c.length;){const a=c.slice(0,d).join(path.sep);try{fs.mkdirSync(a,b),e=!0}catch(b){let c;try{c=fs.statSync(a)}catch(a){throw b}if(!c.isDirectory())throw new Error(`'${a}' is not a directory`)}}return e}static resolve(a,b,c){b=path.resolve(a,b);let d;try{d=fs.statSync(b)}catch(a){throw new agentframework.Exception(a,`'${b}' not exist`)}if(!d.isDirectory())throw new agentframework.Exception({directory:b},`'${b}' is not a directory`);try{fs.accessSync(b,c|fs.constants.X_OK)}catch(a){throw a.file=b,a}return new Directory(b,c)}toString(){return this._directory}get path(){return this._directory}directory(a){if(path.isAbsolute(a))throw new Error(`'${a}' is not a relative path`);return Directory.resolve(this._directory,a,this._permission)}file(a){if(path.isAbsolute(a))throw new Error(`'${a}' is not a relative path`);return File.resolve(this.path,a,this._permission)}}class StandardOutputTransporter extends lib.Transporter{constructor(a,b){super(a),this.formatter=new lib.ConsoleFormatter(b)}format(a){return this.formatter.format(lib.SafeJSON.deserialize(a))}write(a){process.stdout.write(this.format(a))}writeSync(a){fs.writeSync(2,this.format(a))}}class FileLogTransporter extends lib.Transporter{constructor(a,b){super(a),this.filename=b,this.openWritableFileStream()}openWritableFileStream(){const a=this,b=this.stream=fs.createWriteStream(this.filename,{flags:'a',encoding:'utf8'});b.on('open',function(b){a.fd=b}),b.on('error',function(b){const c=new FileStreamException(b);a.emitEvent('error',c)})}write(a){this.stream.write(a)}writeSync(a){try{this.fd?fs.writeSync(this.fd,a):fs.appendFileSync(this.filename,a)}catch(b){const c=new FileWriteException(b,{file:this.filename,fd:this.fd,transporter:this.constructor.name,data:a},'Unable to write log data');this.emitEvent('error',c)}}}class ApplicationLogger extends lib.Logger{static[lib.Symbols.Initializer](a){const b=a.settings,c={context:{name:b.NAME,pid:0,hostname:'local',v:0},serializers:{}},d=[];if(b.LOG_CONSOLE&&d.push(new StandardOutputTransporter(lib.LogLevel[b.LOG_CONSOLE_LEVEL],b.LOG_CONSOLE_STYLE)),b.LOG_DIR){const a=path.join(b.LOG_DIR,'agent.log');d.push(new FileLogTransporter(lib.LogLevel[b.LOG_LEVEL],a))}return new lib.Logger(c,d)}}function info(a){if(null==a)fs.writeSync(1,`\r\n`);else{const b=new Date,c=b.toLocaleTimeString()+'.'+lib.padStart(b.getMilliseconds(),3,'0');fs.writeSync(1,`[${c}] INFO : ${a}\r\n`)}}function fatal(a){const b=new Date,c=b.toLocaleTimeString()+'.'+lib.padStart(b.getMilliseconds(),3,'0');fs.writeSync(2,`[${c}] FATAL: ${a}\r\n`)}function warn(a){const b=new Date,c=b.toLocaleTimeString()+'.'+lib.padStart(b.getMilliseconds(),3,'0');fs.writeSync(1,`[${c}] WARN : ${a}\r\n`)}const yaml=require('js-yaml');function parseYAML(a){return yaml.load(a.readAll())}function parseJSON(a){return lib.SafeJSON.deserialize(a.readAll())}function dumpYAML(a,b){fs.writeFileSync(b,yaml.dump(a))}function dumpJSON(a,b){fs.writeFileSync(b,JSON.stringify(a))}function nativeStringify(a){try{return JSON.stringify(a)}catch(a){}}function serialize(a){if(null==a)return'null';else{const b=typeof a;return'boolean'==b?a?'"true"':'"false"':'number'==b||'function'==b||'symbol'==b?'"'+a.toString()+'"':nativeStringify(a)||stringify(a)}}class Loader{constructor(a,b,c,d){this.root=b,this._settings=d,this._settings.ENV=a.toLowerCase(),this._settings.SECURE='production'===this._settings.ENV,this._settings.HOME_DIR=b.path,this._settings.CONF_DIR=path.resolve(b.path,c)}static loadSettings(a,b,c){info();const d=this.checkEnvironment(),e=new Loader(d,a,b,c);return e.applyFileSettings('settings.yaml'),'production'!==d&&e.applyFileSettings('production.yaml'),e.applyFileSettings(d+'.yaml'),e.applyFileSettings(d+'.local.yaml'),e.applyPackageInfo(),e.applyEnvironmentSettings(),e.resolveAbsolutePath(),e.resolveAbsoluteFile(),e.applyCustomSettingFile(),info(),e._settings}static checkEnvironment(){let a=process.env.NODE_ENV;return a?info('\x1B[7mApplication loaded using the "'+process.env.NODE_ENV+'" configuration\x1B[0m'):(process.env.NODE_ENV=a='production',info('\x1B[33mNODE_ENV is not defined! Using default "'+process.env.NODE_ENV+'" configuration\x1B[0m')),a}applyFileSettings(a){let b,c;try{b=File.resolve(this._settings.CONF_DIR,a,File.Read)}catch(a){return warn(`Application settings file '${a.file}' is not found, ignoring...`),!1}try{c=parseYAML(b)}catch(a){throw fatal(`Error parsing '${b.path}', reason: '${a.message}', exiting...`),a}if('object'!=typeof c){const a=new Error(`'${b.path}' is not validate settings file`);throw fatal(a.message),a}const d=[];for(const b of Object.keys(c))this._settings[b]=c[b],d.push(b);return info(`Applied ${d.length} key(s) from '${b.path}'`),!0}applyPackageInfo(){let a;try{a=this.root.file(this._settings.PACKAGE_FILE);try{const b=parseJSON(a);this._settings.VERSION=b.version||this._settings.VERSION,this._settings.NAME=b.name||this._settings.NAME}catch(a){warn(`Package file '${this._settings.PACKAGE_FILE}' parsing error, ignoring...`)}}catch(a){warn(`Package file '${a.file}' is not found, ignoring...`)}}applyEnvironmentSettings(){let a=!0;const b=[];for(const c of Object.keys(this._settings)){const d=this._settings[c];if(null!=process.env[c]){info('Applying '+c+' from environment');const a=process.env[c];try{this._settings[c]='string'==typeof a?JSON.parse(a):a}catch(b){this._settings[c]=a}}else null==d&&(a=!1,b.push(c),warn('Missing environment variable: '+c))}if(!a){const a=new Error(`Missing environment variable(s): ${b.join(',')}, exiting...`);throw fatal(a.message),a}}resolveAbsolutePath(){const a='_DIR',b=this._settings.AUTO_CREATE_DIRECTORY;b&&warn('Auto create directory is ON, all missing directory in the configuration will be created automatically.');for(const c of Object.keys(this._settings)){const d=this._settings[c];if(d&&d.length&&-1!==c.indexOf(a,c.length-a.length)&&d.split){const a=d.split(':'),e=a[0],f='rw'===a[1]?'rw':'ro',g=path.resolve(this.root.path,e);b&&Directory.mkdir(g)&&info(`Created directory '${g}'`),this._settings[c]='rw'==f?Directory.withReadWritePermission(g).path:Directory.withReadPermission(g).path}}}resolveAbsoluteFile(){const a='_FILE';for(const b of Object.keys(this._settings)){const c=this._settings[b];if(c&&c.length&&-1!==b.indexOf(a,b.length-a.length)&&c.split){const a=c.split(':'),d=a[0],e=a[1];this._settings[b]='rw'===e?File.resolve(this.root.path,d,fs.constants.R_OK|fs.constants.W_OK):'ro'===e?File.resolve(this.root.path,d,fs.constants.R_OK):path.resolve(this.root.path,d)}}}applyCustomSettingFile(){if(this._settings.DATA_DIR){const a=path.join(this._settings.DATA_DIR,'settings.json');let b={};if(fs.existsSync(a)){fs.accessSync(a,fs.constants.W_OK|fs.constants.R_OK);const c=fs.readFileSync(a,{encoding:'utf8'});try{b=JSON.parse(c)}catch(b){warn(`error parsing setting state file ${a}`)}for(const a of Object.keys(b))this._settings[a]=b[a]}}}}function ParseApplicationOptions(a){return a?{root:a.root||process.cwd(),confDir:a.confDir||'conf',settings:a.settings,registry:a.registry,params:a.params}:{root:process.cwd(),confDir:'conf'}}class ApplicationSettings extends lib.ContainerSettings{constructor(){super(...arguments),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'}static[lib.Symbols.Initializer](a,b){const c=ParseApplicationOptions(b),d=c.settings||this,e=Reflect.construct(d,[]),f=Directory.withReadPermission(c.root);return Loader.loadSettings(f,c.confDir,e),e}}class Updater{static updateSetting(a,b,c,d){if(!b.DATA_DIR)throw new lib.Exception('Unable to update settings without config DATA_DIR');const f=path.join(b.DATA_DIR,'settings.json');let e={};if(fs.existsSync(f)){fs.accessSync(f,fs.constants.W_OK|fs.constants.R_OK);const b=fs.readFileSync(f,{encoding:'utf8'});try{e=JSON.parse(b)}catch(b){a.error(b,`error parsing setting state file ${f}`)}}e.hasOwnProperty(c)&&typeof e[c]!=typeof d&&a.error({origin:typeof e[c],new:typeof d},`Unable to update settings because type mismatch`),e[c]=d;const g=JSON.stringify(e,null,2);fs.writeFileSync(f,g,{encoding:'utf8',mode:420});const h=fs.readFileSync(f,{encoding:'utf8'}),i=JSON.parse(h);return i[c]}}class Printer{static printSettings(a,b){a.PRINT_SETTINGS&&(b.info('Active configuration properties:'),Object.getOwnPropertyNames(a).map(b=>{let c=a[b];const d=b.toUpperCase();if(d.endsWith('_URL')&&'string'==typeof c&&c.length){const a=c.split('/');if(2<=a.length){const b=a[2].indexOf('@'),d=a[2].slice(0,b),e=a[2].slice(b+1),f=d.indexOf(':');if(0<=f){const b=d.slice(0,f),g=d.slice(f+1);a[2]=`${b}:${this.mask(g)}@${e}`,c=a.join('/')}}}else this.sensitive(d)&&(c=this.mask(c));return agentframework.IsObject(c)&&(c=util.inspect(c)),{key:b,value:c}}).forEach(a=>{b.info(`${a.key} = ${a.value}`)}))}static sensitive(a){return a.endsWith('_KEY')||a.endsWith('_PASSWORD')||a.endsWith('_SECRET')||a.endsWith('_TOKEN')}static mask(a){const b=a.length;let c='';for(let d=0;d<b;d++)c+=10<b&&(2>d||d>b-3)?a[d]:'*';return c}}(function(a){a.signals='signals',a.uncaughtException='uncaughtException',a.unhandledRejection='unhandledRejection',a.exiting='exiting',a.exit='exit'})(exports.ApplicationEvents||(exports.ApplicationEvents={}));class ExitEvent extends lib.StoppableEvent{}const Signals={SIGHUP:1,SIGINT:2,SIGQUIT:3,SIGTERM:15};class SignalEvent extends lib.StoppableEvent{constructor(a,b){super(),this.signal=a,this.code=b}}class UnhandledSignalEventException extends lib.StoppableEventException{constructor(a,b,c){super(a,`Received signal '${b}' and now exiting...`),this.code=c}}function GenerateSignalEventHandlers(a,b){return function(){const c=Signals[b];if(a&&Reflect.has(a,'settings')){const d=new SignalEvent(b,c);a.exit(new UnhandledSignalEventException(d,b,c))}else fatal(`Received signal '${b}' and no application been created. exiting...\r\n`),setImmediate(function(){process.exit(c)})}}class UncaughtExceptionEvent extends lib.StoppableEvent{constructor(a){super(),this.exception=a}}class UnhandledException extends lib.StoppableEventException{constructor(a,b){super(a,`Received UncaughtException and now exiting...`,b)}}function GenerateUncaughtExceptionHandlers(a){return function(b){if(a&&Reflect.has(a,'settings')){const c=new UncaughtExceptionEvent(b);if(a.emitStoppableEvent(exports.ApplicationEvents.uncaughtException,c))return;a.exit(new UnhandledException(c,b))}else fatal(`Application [null] exiting...\r\n${b.stack}\r\n`),setImmediate(function(){process.exit(1102)})}}function GenerateExitHandlers(a){return function(b){if(a&&Reflect.has(a,'settings')){const c=a.settings.NAME;0<b?a.fatal(`Application [${c}] exited with code ${b}`):a.info(`Application [${c}] exited successfully`)}else 0<b?fatal(`Application exited with code ${b}`):info(`Application exited successfully`)}}let listeners;function PrepareEvents(a){const b=new Map;for(const c of Object.keys(Signals))b.set(c,GenerateSignalEventHandlers(a,c));return b.set(exports.ApplicationEvents.uncaughtException,GenerateUncaughtExceptionHandlers(a)),b.set(exports.ApplicationEvents.exit,GenerateExitHandlers(a)),b}function RegisterEvents(a){listeners||(listeners=PrepareEvents(a));for(const[b,c]of listeners.entries())process.on.call(process,b,c);return a}class Application extends lib.Container{constructor(a){const b=ParseApplicationOptions(a);super(b.params,b.registry),this.options=b,RegisterEvents(this),Printer.printSettings(this.settings,this.logger)}onCreatingState(){return Object.create(null)}onCreatingIdentity(){return new lib.Identity}onCreatingLogger(){const a=this.construct(ApplicationLogger);return a.addEventListener('error',a=>this.dispatchEvent('error',new lib.LoggerException(a))),a}onCreatingSettings(){return this.construct(ApplicationSettings,!1,[this.options])}onCreatingRootDirectory(){return Directory.withReadPermission(process.cwd())}get root(){const a=this.onCreatingRootDirectory();return lib.defineProperty(this,'root',a),a}directory(a=''){return this.root.directory(a)}file(a){return this.root.file(a)}exit(a){this.logger.fatal(a);this.emitStoppableEvent(exports.ApplicationEvents.exiting,new ExitEvent)||process.exit()}get(a,b){if(agentframework.IsNullOrUndefined(this.settings[a]))if(agentframework.IsNullOrUndefined(b))throw new lib.MissingConfigurationValueException(a);else return b;return this.settings[a]}set(a,b){const c=Updater.updateSetting(this.logger,this.settings,a,b);return this.settings[a]=c,c}has(a){return!agentframework.IsNullOrUndefined(this.settings[a])}}exports.padStart=lib.padStart,exports.padEnd=lib.padEnd,exports.ConfigurationAttribute=lib.ConfigurationAttribute,exports.ControllerAttribute=lib.ControllerAttribute,exports.MethodAttribute=lib.MethodAttribute,exports.MiddlewareAttribute=lib.MiddlewareAttribute,exports.ParamsAttribute=lib.ParamsAttribute,exports.ServiceAttribute=lib.ServiceAttribute,exports.SingletonAttribute=lib.SingletonAttribute,exports.TransitAttribute=lib.TransitAttribute,exports.ModelAttribute=lib.ModelAttribute,exports.KeyAttribute=lib.KeyAttribute,exports.PropertyAttribute=lib.PropertyAttribute,exports.controller=lib.controller,exports.middleware=lib.middleware,exports.param=lib.param,exports.method=lib.method,exports.service=lib.service,exports.singleton=lib.singleton,exports.transit=lib.transit,exports.conf=lib.conf,exports.model=lib.model,exports.key=lib.key,exports.property=lib.property,exports.IsAssignable=lib.IsAssignable,exports.Resolvable=lib.Resolvable,exports.Router=lib.Router,exports.RouterEventHandlers=lib.RouterEventHandlers,exports.CreateObjectSignature=lib.CreateObjectSignature,exports.CreateFlattenObject=lib.CreateFlattenObject,exports.retry=lib.retry,exports.sleep=lib.sleep,exports.TypeRegistry=lib.TypeRegistry,exports.TypeResolver=lib.TypeResolver,exports.Compositor=lib.Compositor,exports.Sequence=lib.Sequence,exports.StoppableEvent=lib.StoppableEvent,exports.PriorityEventEmitter=lib.PriorityEventEmitter,exports.LogLevel=lib.LogLevel,exports.Logger=lib.Logger,exports.Transporter=lib.Transporter,exports.AbstractLogger=lib.AbstractLogger,exports.ChildLogger=lib.ChildLogger,exports.Serializers=lib.Serializers,exports.ConsoleTransporter=lib.ConsoleTransporter,exports.ConsoleFormatter=lib.ConsoleFormatter,exports.ConsoleLogger=lib.ConsoleLogger,exports.DeserializationException=lib.DeserializationException,exports.SerializationException=lib.SerializationException,exports.LoggerException=lib.LoggerException,exports.TransporterException=lib.TransporterException,exports.MissingConfigurationValueException=lib.MissingConfigurationValueException,exports.StoppableEventException=lib.StoppableEventException,exports.NotImplementedException=lib.NotImplementedException,exports.NotSupportedException=lib.NotSupportedException,exports.Route=lib.Route,exports.Identity=lib.Identity,exports.Container=lib.Container,exports.ContainerSettings=lib.ContainerSettings,exports.Symbols=lib.Symbols,exports.SafeJSON=lib.SafeJSON,exports.defineProperty=lib.defineProperty,exports.StringFormatter=lib.StringFormatter,exports.Reflection=agentframework.Reflection,exports.Property=agentframework.Property,exports.Method=agentframework.Method,exports.Parameter=agentframework.Parameter,exports.PropertyFilters=agentframework.PropertyFilters,exports.Reflector=agentframework.Reflector,exports.AgentAttribute=agentframework.AgentAttribute,exports.Decoratable=agentframework.Decoratable,exports.Target=agentframework.Target,exports.decorateAgent=agentframework.decorateAgent,exports.decorateClass=agentframework.decorateClass,exports.decorateClassMember=agentframework.decorateClassMember,exports.decorateClassMethod=agentframework.decorateClassMethod,exports.decorateClassField=agentframework.decorateClassField,exports.decorateParameter=agentframework.decorateParameter,exports.decorate=agentframework.decorate,exports.IsObject=agentframework.IsObject,exports.IsFunction=agentframework.IsFunction,exports.IsNullOrUndefined=agentframework.IsNullOrUndefined,exports.IsObjectOrFunction=agentframework.IsObjectOrFunction,exports.IsSymbol=agentframework.IsSymbol,exports.IsString=agentframework.IsString,exports.IsNumber=agentframework.IsNumber,exports.IsEqual=agentframework.IsEqual,exports.ToPropertyKey=agentframework.ToPropertyKey,exports.GetPrototypeArray=agentframework.GetPrototypeArray,exports.GetPrototypeArrayReverse=agentframework.GetPrototypeArrayReverse,exports.Exception=agentframework.Exception,exports.Hash52=Hash52,exports.Hash32=Hash32,exports.Hash24=Hash24,exports.Hash16=Hash16,exports.BaseX=BaseX,exports.Base58=Base58,exports.Base62=Base62,exports.CreateHashedObjectId=CreateHashedObjectId,exports.ObjectId=ObjectId,exports.FileStreamException=FileStreamException,exports.FileWriteException=FileWriteException,exports.Directory=Directory,exports.File=File,exports.ApplicationLogger=ApplicationLogger,exports.StandardOutputTransporter=StandardOutputTransporter,exports.FileLogTransporter=FileLogTransporter,exports.Application=Application,exports.ApplicationSettings=ApplicationSettings,exports.UncaughtExceptionEvent=UncaughtExceptionEvent,exports.UnhandledException=UnhandledException,exports.SignalEvent=SignalEvent,exports.UnhandledSignalEventException=UnhandledSignalEventException,exports.ExitEvent=ExitEvent,exports.parseYAML=parseYAML,exports.serialize=serialize,exports.parseJSON=parseJSON,exports.dumpYAML=dumpYAML,exports.dumpJSON=dumpJSON;
2//# sourceMappingURL=index.js.map