-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
1 lines (1 loc) · 69.2 KB
/
index.js
1
module.exports=function(e){var t={};function i(s){if(t[s])return t[s].exports;var r=t[s]={i:s,l:!1,exports:{}};return e[s].call(r.exports,r,r.exports,i),r.l=!0,r.exports}return i.m=e,i.c=t,i.d=function(e,t,s){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:s})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var s=Object.create(null);if(i.r(s),Object.defineProperty(s,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)i.d(s,r,function(t){return e[t]}.bind(null,r));return s},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=10)}([function(e,t){e.exports=require("util")},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=i(0);function r(e){return null===e||void 0===e}t.makeJsonObject=function(e,t,i){o.argument("iterable",()=>o.notNull(e)),o.argument("getKey",()=>o.notNull(t)),o.argument("getValue",()=>o.notNull(i));let s={};for(let r of e)s[t(r)]=i(r);return s},t.callWithTimeout=async function(e,t){let i=!1;return new Promise((s,r)=>{let a=setTimeout(()=>{i||(i=!0,r(new n(`Async call timeout (${t}ms)`)))},t);e().then(e=>{clearTimeout(a),i||(i=!0,s(e))}).catch(e=>{clearTimeout(a),i||(i=!0,r(e))})})},t.deepCopy=function(e){return e?JSON.parse(JSON.stringify(e)):e},t.partialCopy=function(e,t,i){o.argument("src",()=>o.notNull(e)),o.argument("keysOrKeyFilter",()=>o.notNull(t));let r=s.isFunction(t)?Object.keys(e).filter(t):t,n=i||{};for(let t of r)Reflect.has(e,t)&&(n[t]=e[t]);return n},t.isPrimitiveKey=function(e){return null!==e&&void 0!==e&&(s.isString(e)||s.isNumber(e))},t.nullOrUndefined=r;t.NotImplementError=class extends Error{constructor(e){super(e)}};class n extends Error{constructor(e){super(e)}}t.TimeoutError=n;class a extends Error{constructor(e){super(`Code contract Error, ${e}`)}}t.CodeContractError=a;t.AsyncEventEmitter=class{constructor(){this.eventHandlers=new Map}registerEventListener(e,t){this.eventHandlers.has(e)||this.eventHandlers.set(e,new Array),this.eventHandlers.get(e).push(t)}on(e,t,i=!1){this.registerEventListener(e,{isSync:i,handler:t})}async emit(e,...t){const i=this.eventHandlers.get(e)||[];for(let{isSync:e,handler:s}of i)e?s(...t):await s(...t)}emitSync(e,...t){const i=this.eventHandlers.get(e)||[];for(let{isSync:e,handler:s}of i){if(!e)throw new Error("Can not call async function");s(...t)}}getListeners(e){return this.eventHandlers.get(e)||[]}};class o{static verify(e,t){if(void 0===e||null===e)throw new Error("Invalid verify condition");const i=s.isFunction(e)?e():e,r=s.isFunction(t)?t():t;if(!i)throw new a(r)}static argument(e,t,i){if(r(e)||r(t))throw new Error("argName or verify can not be null or undefined");if(i)o.verify(t,i);else{const i=t();o.verify(i.result,`argument '${e}' ${i.message}`)}}static notNull(e){const t=!r(e);return{result:t,message:t?void 0:"cannot be null or undefined"}}static notNullOrEmpty(e){const t=o.notNull(e)&&""!==e;return{result:t,message:t?void 0:"cannot be null or undefined or empty"}}static notNullOrWhitespace(e){const t=o.notNullOrEmpty(e)&&""!==e.trim();return{result:t,message:t?void 0:"cannot be null or undefined or whitespace"}}}t.CodeContract=o},function(e,t,i){"use strict";var s;Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.all=0]="all",e[e.log=0]="log",e[e.trace=1]="trace",e[e.debug=2]="debug",e[e.info=3]="info",e[e.warn=4]="warn",e[e.error=5]="error",e[e.fatal=6]="fatal",e[e.none=99]="none"}(s=t.LogLevel||(t.LogLevel={}));class r{get logEnabled(){return this.level<=s.log}get traceEnabled(){return this.level<=s.trace}get debugEnabled(){return this.level<=s.debug}get infoEnabled(){return this.level<=s.info}get warnEnabled(){return this.level<=s.warn}get errorEnabled(){return this.level<=s.error}get fatalEnabled(){return this.level<=s.fatal}get logLevel(){return this.level}set logLevel(e){this.level=e}constructor(e,t,i,s){this.name=e,this.level=s,this.format=i,this.logger=t,i||(this.log=t.log,this.debug=t.debug,this.trace=t.trace,this.info=t.info,this.warn=t.warn,this.error=t.error,this.fatal=t.fatal)}fromatMessage(e,t){return`${(new Date).toLocaleTimeString()} [${t}] [${this.name}] ${e}`}info(e,...t){this.infoEnabled&&(e=this.format?this.fromatMessage(e,"INFO"):`[${this.name}] ${e}`,this.logger.info(e,...t))}debug(e,...t){this.debugEnabled&&(e=this.format?this.fromatMessage(e,"DEBUG"):`[${this.name}] ${e}`,this.logger.debug(e,...t))}log(e,...t){this.logEnabled&&(e=this.format?this.fromatMessage(e,"LOG"):`[${this.name}] ${e}`,this.logger.log(e,...t))}trace(e,...t){this.traceEnabled&&(e=this.format?this.fromatMessage(e,"TRACE"):`[${this.name}] ${e}`,this.logger.log(e,...t))}warn(e,...t){this.warnEnabled&&(e=this.format?this.fromatMessage(e,"WARN"):`[${this.name}] ${e}`,this.logger.warn(e,...t))}error(e,...t){this.errorEnabled&&(e=this.format?this.fromatMessage(e,"ERROR"):`[${this.name}] ${e}`,this.logger.error(e,...t))}fatal(e,...t){this.fatalEnabled&&(e=this.format?this.fromatMessage(e,"FATAL"):`[${this.name}] ${e}`,this.logger.error(e,...t))}}class n{static get defaultLogger(){return n.consoleLogger=n.consoleLogger||new r("default",console,!0,n.defaultLogLevel),n.consoleLogger}static set defaultLevel(e){n.defaultLogLevel=e}static get logFactory(){return n.factory}static set logFactory(e){n.factory=e}static getLogger(e){if(!n.factory)return n.defaultLogger;const t=n.factory.createLog(e),i=n.factory.getLevel(),s=n.factory.format;return new r(e||"",t,s,i)}}n.defaultLogLevel=s.all,n.factory={createLog:e=>console,format:!0,getLevel:()=>n.defaultLogLevel},t.LogManager=n},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=i(21);class r{constructor(){this.doTime=(e=>{this.traceName=e,this.uptime=process.uptime()}),this.doEndtime=(e=>{const t=process.uptime();console.log(`${this.traceName} cost ${t-this.uptime} s`),e&&(this.uptime=t)}),this.doRestartTime=(e=>{this.doEndtime(!0),this.traceName=e})}get time(){return this.isEnabled?this.doTime:e=>{}}get endTime(){return this.isEnabled?this.doEndtime:e=>{}}get restartTime(){return this.isEnabled?this.doRestartTime:e=>{}}get enabled(){return this.isEnabled}set enabled(e){this.isEnabled=e}}t.PerformanceHelper=r;class n{static get Array(){return n._array}static get String(){return n._string}static get Collection(){return n._collection}static get Function(){return n._function}static get Object(){return n._object}static get Lang(){return n._lang}static get Performace(){return n._performance}}n._performance=new r,n._array={chunk:s.chunk,compact:s.compact,concat:s.concat,difference:s.difference,differenceBy:s.differenceBy,differenceWith:s.differenceWith,drop:s.drop,dropRight:s.dropRight,dropRightWhile:s.dropRightWhile,dropWhile:s.dropWhile,fill:s.fill,findIndex:s.findIndex,findLastIndex:s.findLastIndex,first:s.first,head:s.head,flatten:s.flatten,flattenDeep:s.flattenDeep,flattenDepth:s.flattenDepth,fromPairs:s.fromPairs,indexOf:s.indexOf,initial:s.initial,intersection:s.intersection,intersectionBy:s.intersectionBy,intersectionWith:s.intersectionWith,join:s.join,last:s.last,lastIndexOf:s.lastIndexOf,nth:s.nth,pull:s.pull,pullAll:s.pullAll,pullAllBy:s.pullAllBy,pullAllWith:s.pullAllWith,pullAt:s.pullAt,remove:s.remove,reverse:s.reverse,slice:s.slice,sortedIndex:s.sortedIndex,sortedIndexBy:s.sortedIndexBy,sortedIndexOf:s.sortedIndexOf,sortedLastIndex:s.sortedLastIndex,sortedLastIndexBy:s.sortedLastIndexBy,sortedLastIndexOf:s.sortedLastIndexOf,sortedUniq:s.sortedUniq,sortedUniqBy:s.sortedUniqBy,tail:s.tail,take:s.take,takeRight:s.takeRight,takeRightWhile:s.takeRightWhile,takeWhile:s.takeWhile,union:s.union,unionBy:s.unionBy,unionWith:s.unionWith,uniq:s.uniq,uniqBy:s.uniqBy,uniqWith:s.uniqWith,unzip:s.unzip,unzipWith:s.unzipWith,without:s.without,xor:s.xor,xorBy:s.xorBy,xorWith:s.xorWith,zip:s.zip,zipObject:s.zipObject,zipObjectDeep:s.zipObjectDeep,zipWith:s.zipWith},n._lang={castArray:s.castArray,clone:s.clone,cloneDeep:s.cloneDeep,cloneDeepWith:s.cloneDeepWith,cloneWith:s.cloneWith,conformsTo:s.conformsTo,eq:s.eq,gt:s.gt,gte:s.gte,isArguments:s.isArguments,isArray:s.isArray,isArrayBuffer:s.isArrayBuffer,isArrayLike:s.isArrayLike,isArrayLikeObject:s.isArrayLikeObject,isBoolean:s.isBoolean,isBuffer:s.isBuffer,isDate:s.isDate,isElement:s.isElement,isEmpty:s.isEmpty,isEqual:s.isEqual,isEqualWith:s.isEqualWith,isError:s.isError,isFinite:s.isFinite,isFunction:s.isFunction,isInteger:s.isInteger,isLength:s.isLength,isMap:s.isMap,isMatch:s.isMatch,isMatchWith:s.isMatchWith,isNaN:s.isNaN,isNative:s.isNative,isNil:s.isNil,isNull:s.isNull,isNumber:s.isNumber,isObject:s.isObject,isObjectLike:s.isObjectLike,isPlainObject:s.isPlainObject,isRegExp:s.isRegExp,isSafeInteger:s.isSafeInteger,isSet:s.isSet,isString:s.isString,isSymbol:s.isSymbol,isTypedArray:s.isTypedArray,isUndefined:s.isUndefined,isWeakMap:s.isWeakMap,isWeakSet:s.isWeakSet,lt:s.lt,lte:s.lte,toArray:s.toArray,toFinite:s.toFinite,toInteger:s.toInteger,toLength:s.toLength,toNumber:s.toNumber,toPlainObject:s.toPlainObject,toSafeInteger:s.toSafeInteger,toString:s.toString},n._collection={countBy:s.countBy,each:s.each,eachRight:s.eachRight,every:s.every,filter:s.filter,find:s.find,findLast:s.findLast,flatMap:s.flatMap,flatMapDeep:s.flatMapDeep,flatMapDepth:s.flatMapDepth,forEach:s.forEach,forEachRight:s.forEachRight,groupBy:s.groupBy,includes:s.includes,invokeMap:s.invokeMap,keyBy:s.keyBy,map:s.map,orderBy:s.orderBy,partition:s.partition,reduce:s.reduce,reduceRight:s.reduceRight,reject:s.reject,sample:s.sample,sampleSize:s.sampleSize,shuffle:s.shuffle,size:s.size,some:s.some,sortBy:s.sortBy},n._function={after:s.after,ary:s.ary,before:s.before,bind:s.bind,bindKey:s.bindKey,curry:s.curry,curryRight:s.curryRight,debounce:s.debounce,defer:s.defer,delay:s.delay,flip:s.flip,memoize:s.memoize,negate:s.negate,once:s.once,overArgs:s.overArgs,partial:s.partial,partialRight:s.partialRight,rearg:s.rearg,rest:s.rest,spread:s.spread,throttle:s.throttle,unary:s.unary,wrap:s.wrap},n._string={camelCase:s.camelCase,capitalize:s.capitalize,deburr:s.deburr,endsWith:s.endsWith,escape:s.escape,escapeRegExp:s.escapeRegExp,kebabCase:s.kebabCase,lowerCase:s.lowerCase,lowerFirst:s.lowerFirst,pad:s.pad,padEnd:s.padEnd,padStart:s.padStart,parseInt:s.parseInt,repeat:s.repeat,replace:s.replace,snakeCase:s.snakeCase,split:s.split,startCase:s.startCase,startsWith:s.startsWith,template:s.template,toLower:s.toLower,toUpper:s.toUpper,trim:s.trim,trimEnd:s.trimEnd,trimStart:s.trimStart,truncate:s.truncate,unescape:s.unescape,upperCase:s.upperCase,upperFirst:s.upperFirst,words:s.words},n._object={assign:s.assign,assignIn:s.assignIn,assignInWith:s.assignInWith,assignWith:s.assignWith,at:s.at,create:s.create,defaults:s.defaults,defaultsDeep:s.defaultsDeep,entries:s.entries,entriesIn:s.entriesIn,extend:s.extend,findKey:s.findKey,findLastKey:s.findLastKey,forIn:s.forIn,forInRight:s.forInRight,forOwn:s.forOwn,forOwnRight:s.forOwnRight,functions:s.functions,functionsIn:s.functionsIn,get:s.get,has:s.has,hasIn:s.hasIn,invert:s.invert,invertBy:s.invertBy,invoke:s.invoke,keys:s.keys,keysIn:s.keysIn,mapKeys:s.mapKeys,mapValues:s.mapValues,merge:s.merge,mergeWith:s.mergeWith,omit:s.omit,omitBy:s.omitBy,pick:s.pick,pickBy:s.pickBy,result:s.result,set:s.set,setWith:s.setWith,toPairs:s.toPairs,toPairsIn:s.toPairsIn,transform:s.transform,unset:s.unset,update:s.update,updateWith:s.updateWith,values:s.values,valuesIn:s.valuesIn},t.Utils=n},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e){e[e.Transient=-1]="Transient",e[e.Persistent=0]="Persistent",e[e.New=1]="New",e[e.Modified=2]="Modified",e[e.Deleted=3]="Deleted"}(t.EntityState||(t.EntityState={})),t.ENTITY_VERSION_PROPERTY="_version_",t.ENTITY_EXTENSION_SYMBOL="__extension__",function(e){e[e.New=1]="New",e[e.Modify=2]="Modify",e[e.Delete=3]="Delete"}(t.EntityChangeType||(t.EntityChangeType={}))},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=i(0),r=i(1),n=i(3),a=i(4);var o;!function(e){e.String="String",e.Number="Number",e.BigInt="BigInt",e.Text="Text",e.JSON="Json"}(o=t.FieldTypes||(t.FieldTypes={}));t.InvalidEntityKeyError=class extends Error{constructor(e,t){super(`Invalid entity key,( model = ${e}, key = '${JSON.stringify(t)}' ) `)}};class c{constructor(e,t){this.schema=n.Utils.Lang.cloneDeep(e),this.name=t,this.memory=!0===e.memory,this.readonly=!0===e.readonly,this.local=!0===e.local,this.maxCachedCount=this.memory?Number.POSITIVE_INFINITY:e.maxCached,this.propertiesSet=new Set,this.uniquePropertiesSet=new Set,this.attachVersionField(),this.parseProperties()}attachVersionField(){this.schema.tableFields.some(e=>e.name===a.ENTITY_VERSION_PROPERTY)||this.schema.tableFields.push({name:"_version_",type:o.Number,default:0})}convertType(e){return e}getIndexes(e,t){let i=new Map;return e.filter(e=>void 0!==e[t]).forEach(e=>{let r=e[t];if(!s.isBoolean(r)&&!s.isString(r))throw new Error("index or unique should be true or a valid name");const n=e.name;if(!0===r)i.set(e.name,[n]);else if(s.isString(r)){const e=r;i.has(e)||i.set(e,new Array),i.get(e).push(n)}}),[...i.keys()].map(e=>({name:e,properties:i.get(e)}))}parseNormalIndexes(e){return this.getIndexes(e.tableFields,"index")}parseUniqueIndexes(e){return this.getIndexes(e.tableFields,"unique")}parseProperties(){const e=this.schema.tableFields.filter(e=>!0===e.primary_key).map(e=>e.name);if(this.compositKeyProperties=this.schema.tableFields.filter(e=>!0===e.composite_key).map(e=>e.name),this.primaryKeyProperty=1===e.length?e[0]:void 0,!(void 0!==this.primaryKeyProperty!=this.compositKeyProperties.length>1))throw new Error("model must have primary key or composite keys, but cannot be both");this.allPropertyTypes=new Map,this.schema.tableFields.forEach(e=>this.allPropertyTypes.set(e.name,this.convertType(e.type))),this.allProperties=this.schema.tableFields.map(e=>e.name),this.allJsonProperties=this.schema.tableFields.filter(e=>e.type===o.JSON).map(e=>e.name),this.allNormalIndexes=this.parseNormalIndexes(this.schema),this.allUniqueIndexes=this.parseUniqueIndexes(this.schema),this.allProperties.forEach(e=>this.propertiesSet.add(e)),this.allUniqueIndexes.forEach(e=>e.properties.forEach(e=>this.uniquePropertiesSet.add(e)))}get properties(){return this.allProperties}get jsonProperties(){return this.allJsonProperties}get schemaObject(){return this.schema}get isCompsiteKey(){return this.compositeKeys.length>1}get primaryKey(){return this.primaryKeyProperty}get compositeKeys(){return this.compositKeyProperties}get indexes(){return this.allNormalIndexes}get uniqueIndexes(){return this.allUniqueIndexes}get maxCached(){return this.maxCachedCount}get modelName(){return this.name}get isLocal(){return this.local}get isReadonly(){return this.readonly}get memCached(){return this.memory}hasUniqueProperty(...e){return e.some(e=>this.uniquePropertiesSet.has(e))}isValidProperty(e){return this.propertiesSet.has(e)}isValidEntityKey(e){return this.isValidPrimaryKey(e)||this.isValidUniqueKey(e)}isNormalizedPrimaryKey(e){if(!s.isObject(e))return;const t=e,i=Object.keys(t);return this.isCompsiteKey?this.isValidPrimaryKey(t):1===i.length&&i[0]===this.primaryKey}setPrimaryKey(e,t){if(!this.isValidPrimaryKey(t))throw new Error(`Invalid PrimaryKey of model '${this.modelName}', key=''${JSON.stringify(t)}`);return!this.isCompsiteKey&&r.isPrimitiveKey(t)?e[this.primaryKey]=t:this.isCompsiteKey?r.partialCopy(t,this.compositeKeys,e):r.partialCopy(t,[this.primaryKey],e),e}getPrimaryKey(e){return this.isCompsiteKey?r.partialCopy(e,this.compositeKeys):e[this.primaryKey]}getNormalizedPrimaryKey(e){return this.isCompsiteKey?r.partialCopy(e,this.compositeKeys):r.partialCopy(e,[this.primaryKey])}normalizePrimaryKey(e){if(!r.isPrimitiveKey(e))return e;let t={};return t[this.primaryKey]=e,t}isValidPrimaryKey(e){return!this.isCompsiteKey&&(r.isPrimitiveKey(e)||this.isNormalizedPrimaryKey(e))||0===n.Utils.Array.xor(Object.keys(e),this.compositeKeys).length}isValidUniqueKey(e){return void 0!==this.getUniqueName(e)}getUniqueName(e){if(this.isValidPrimaryKey(e))return c.PRIMARY_KEY_NAME;let t=Object.keys(e);if(1===t.length&&t[0]===this.primaryKey)return c.PRIMARY_KEY_NAME;const i=this.uniqueIndexes.find(e=>0===n.Utils.Array.xor(e.properties,t).length);return void 0===i?void 0:i.name}isPrimaryKeyUniqueName(e){return e===c.PRIMARY_KEY_NAME}getUniqueIndex(e){return this.allUniqueIndexes.find(t=>t.name===e)}resolveKey(e){const t=this.getUniqueName(e);if(void 0!==t)return this.isPrimaryKeyUniqueName(t)?{isPrimaryKey:!0,uniqueName:t,key:this.setPrimaryKey({},e)}:{isUniqueKey:!0,uniqueName:t,key:e}}copyProperties(e,t=!0){return e?r.partialCopy(e,t?this.allProperties:e=>this.allProperties.includes(e)):e}setDefaultValues(e){this.schema.tableFields.forEach(t=>{void 0!==t.default&&(null===e[t.name]||void 0===e[t.name])&&(e[t.name]=t.default)})}splitEntityAndVersion(e){const t=e[a.ENTITY_VERSION_PROPERTY];return Reflect.deleteProperty(e,a.ENTITY_VERSION_PROPERTY),{version:t,entity:e}}}c.PRIMARY_KEY_NAME="__PrimaryKey__",t.ModelSchema=c},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=i(14),r="__last_block_height__";t.LevelBlock=class{constructor(e,t={}){const i=new s.SubLevelMeta("blk","height",[{fieldName:"id"},{fieldName:"delegate"}]),r=new s.SubLevelMeta("his","height",[]);this.db=new s.LevelDB(e,[i,r],t),this.lastHeight=-1}async getLastBlockHeightFromDb(){let e=await this.blockDb.get(r,{});return void 0===e&&(e=this.getLastHeightJson(-1),await this.blockDb.put(r,e)),e.height}async open(){await this.db.open(),this.blockDb=this.db.getSubLevel("blk"),this.historyDb=this.db.getSubLevel("his"),this.lastHeight=await this.getLastBlockHeightFromDb()}async close(){await this.db.close()}get lastBlockHeight(){return this.lastHeight}isKeyNotFoundError(e){return"NotFoundError"===e.name}getLastHeightJson(e){return{height:e,id:"NULL",delegate:"NULL"}}async appendBlock(e,t){if(!e||!e.id||!e.delegate||void 0===e.height)throw new Error("Invalid block data");await this.historyDb.put(e.height,t),await this.blockDb.batch([{type:"put",key:e.height,value:e},{type:"put",key:r,value:this.getLastHeightJson(e.height)}]),this.lastHeight=e.height}async getBlock(e){try{return await this.blockDb.get(e)}catch(e){if(!this.isKeyNotFoundError(e))throw e}}async getHistoryChanges(e,t){let i=new Map;for(let s=e;s<=t;s++){const e=await this.historyDb.get(s);e&&i.set(s,e)}return i}async deleteLastBlock(e){if(e!==this.lastBlockHeight)throw new Error(`invalid last block height '${e}'`);await this.blockDb.batch([{type:"del",key:e},{type:"put",key:r,value:this.getLastHeightJson(e-1)}]),await this.historyDb.del(e),this.lastHeight--}async getBlockById(e){const t=await this.blockDb.getBy("id",e);return t&&t.height>this.lastHeight?void 0:t}async getBlocksByHeightRange(e,t){let i=new Array;for(let s=e;s<=t;s++){let e=await this.getBlock(s);e&&i.push(e)}return i}async getBlocksByIds(e){let t=new Array;for(let i=0;i<e.length;i++){let s=await this.getBlockById(e[i]);s&&t.push(s)}return t}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=i(2),r=i(0),n=i(18),a=i(5),o=i(8),c=i(1),l=i(23),h=i(24),u=i(3);class d extends c.AsyncEventEmitter{constructor(e,t,i){super(),this.currentEntityTransactionId=void 0;const r=Object.assign({},i),a=r.name;this.log=s.LogManager.getLogger(d.name+(void 0===a?"":`_${a}`)),this.sessionSerial=-1,this.connection=e,this.unconfirmedLocks=new Set,this.confirmedLocks=new Set,this.confirmedTransactionIdQueue=[],this.confirmedTransactionIdSet=new Set,this.schemas=new Map,this.sessionCache=new n.LRUEntityCache(this.schemas),this.sqlBuilder=new o.JsonSqlBuilder;const c=r.maxHistoryVersionsHold||d.DEFAULT_HISTORY_VERSION_HOLD;this.entityTracker=new h.SnapshotEntityTracker(this.sessionCache,this.schemas,c,t),this.trackerSqlBuilder=new l.BasicTrackerSqlBuilder(this.entityTracker,this.schemas,this.sqlBuilder)}makeByKeyCondition(e,t){return e.resolveKey(t).key}trackPersistentEntities(e,t,i=!1){let s=new Array;return t.forEach(t=>{let r=e.getPrimaryKey(t),n=this.entityTracker.getTrackingEntity(e,r),a=i&&void 0!==n?n:this.entityTracker.trackPersistent(e,t);s.push(e.copyProperties(a,!0))}),s}reset(e=!1){e&&this.sessionCache.clear()}undefinedIfDeleted(e){return c.deepCopy(e)}async queryEntities(e,t){const i=await this.connection.query(t.query,t.parameters);return this.replaceEntitiesJsonPropertis(e,i)}queryEntitiesSync(e,t){const i=this.connection.querySync(t.query,t.parameters);return this.replaceEntitiesJsonPropertis(e,i)}get isOpen(){return this.connection&&this.connection.isConnected}get confirmedTransactionIds(){return[...this.confirmedTransactionIdQueue]}syncSchema(e){this.sqlBuilder.buildSchema(e).forEach(e=>{this.connection.executeSync(e)})}async updateSchema(e){if(await this.exists(e,{}))throw new Error(`Can not update schema(${e.modelName}) because table is not empty`);const t=this.sqlBuilder.buildDropSchema(e);await this.connection.execute(t),this.syncSchema(e),this.registerSchema(e)}registerSchema(...e){e.forEach(e=>{this.schemas.set(e.modelName,e)})}async initSerial(e){this.sessionSerial=e;const t=this.entityTracker;e>=0&&await t.initVersion(e)}async close(){this.reset(!0),await this.connection.disconnect()}getAll(e,t){if(!e.memCached)throw new Error("getAll only support in memory model");const i=e=>void 0!==this.undefinedIfDeleted(e),s=t?e=>t(e)&&i(e):i;return this.sessionCache.getAll(e.modelName,s)}loadAll(e){if(e.memCached&&this.sessionCache.existsModel(e.modelName)){let t=this.sessionCache.getAll(e.modelName)||[];return this.trackPersistentEntities(e,t,!0)}return[]}async getMany(e,t,i=!0){const s=this.sqlBuilder.buildSelect(e,e.properties,t);let r=await this.queryEntities(e,s);return i?this.trackPersistentEntities(e,r,!0):r}async query(e,t,i,s,r,n){const a=this.sqlBuilder.buildSelect(e,r||e.properties,t,i,s,n);return await this.queryEntities(e,a)}async queryByJson(e,t){const i=this.sqlBuilder.buildSelect(e,t);return await this.queryEntities(e,i)}async exists(e,t){let{query:i,parameters:s}=this.sqlBuilder.buildSelect(e,[],t);i=`select exists(${i.replace(o.MULTI_SQL_SEPARATOR,"")}) as exist`;const n=await this.connection.query(i,s);return r.isArray(n)&&parseInt(n[0].exist)>0}async count(e,t){let i=await this.queryByJson(e,{fields:"count(*) as count",condition:t});return r.isArray(i)?parseInt(i[0].count):0}async sqlQuery(e,t={}){return await this.connection.query(e,t)}async queryAggregate(e,t,i){const s=`${t.func}(${t.args.join(",")}) as value`;let{query:n,parameters:a}=this.sqlBuilder.buildAggregate(e,s,i);const o=await this.connection.query(n,a);return o&&r.isArray(o)?o[0].value:void 0}create(e,t){const i=e.getNormalizedPrimaryKey(t);if(void 0===i)throw new Error(`entity must contains primary key ( model = '${e.modelName}' entity = '${t}' )`);if(this.sessionCache.exists(e.modelName,i))throw new Error(`entity exists already ( model = '${e.modelName}' key = '${JSON.stringify(i)}' )`);return c.deepCopy(this.entityTracker.trackNew(e,t))}loadEntityByKeySync(e,t){const i=this.makeByKeyCondition(e,t),s=this.sqlBuilder.buildSelect(e,e.properties,i),r=this.queryEntitiesSync(e,s);if(r.length>1)throw new Error(`entity key is duplicated ( model = '${e.modelName}' key = '${JSON.stringify(t)}' )`);return 1===r.length?r[0]:void 0}async loadEntityByKey(e,t){const i=this.makeByKeyCondition(e,t),s=this.sqlBuilder.buildSelect(e,e.properties,i),r=await this.queryEntities(e,s);if(r.length>1)throw new Error(`entity key is duplicated ( model = '${e.modelName}' key = '${JSON.stringify(t)}' )`);return 1===r.length?r[0]:void 0}replaceJsonProperties(e,t){if(0===e.jsonProperties.length)return t;let i=Object.assign({},t);return e.jsonProperties.forEach(e=>{Reflect.has(i,e)&&(i[e]=JSON.parse(String(t[e])))}),i}replaceEntitiesJsonPropertis(e,t){return 0===e.jsonProperties.length?t:t.map(t=>this.replaceJsonProperties(e,t))}async load(e,t){const i=this.getCachedEntity(e,t);if(void 0!==i)return i;const s=await this.loadEntityByKey(e,t);if(void 0===s)return;const r=this.entityTracker.trackPersistent(e,s);return e.copyProperties(r,!0)}loadSync(e,t){const i=this.getCachedEntity(e,t);if(void 0!==i)return i;const s=this.loadEntityByKeySync(e,t);if(void 0===s)return;const r=this.entityTracker.trackPersistent(e,s);return e.copyProperties(r,!0)}getChanges(){return this.entityTracker.getConfirmedChanges()}normalizeEntityKey(e,t){const i=e.resolveKey(t);if(void 0===i)throw new a.InvalidEntityKeyError(e.modelName,t);return i}getCached(e,t){const i=this.normalizeEntityKey(e,t),s=this.entityTracker.getTrackingEntity(e,i.key);return s||(i.isPrimaryKey?this.sessionCache.get(e.modelName,i.key):this.sessionCache.getUnique(e.modelName,i.uniqueName,i.key))}getTrackingOrCachedEntity(e,t){const i=this.getCached(e,t);return void 0===i?void 0:this.undefinedIfDeleted(i)}getCachedEntity(e,t){const i=this.getCached(e,t);return void 0===i?void 0:this.undefinedIfDeleted(i)}clearEntityTransactionIds(){this.currentEntityTransactionId=void 0,this.confirmedTransactionIdSet=new Set,this.confirmedTransactionIdQueue=[]}clearLocks(){this.unconfirmedLocks.clear(),this.confirmedLocks.clear()}confirmLocks(){this.unconfirmedLocks.forEach(e=>this.confirmedLocks.add(e))}lockInThisSession(e,t=!1){if(!(this.confirmedLocks.has(e)||this.unconfirmedLocks.has(e))){return(this.entityTracker.isConfirming?this.unconfirmedLocks:this.confirmedLocks).add(e),this.log.trace(`SUCCESS lock name = '${e}'`),!0}if(this.log.warn(`FAILED lock ${e}`),!t)throw new Error(`Lock name = ${e} exists already`);return!1}async saveChanges(e){const t=e||++this.sessionSerial;this.log.debug(`BEGIN saveChanges ( serial = ${t} )`),await this.emit(d.events.beforeSaveChanges,t),this.commitEntityTransaction(),u.Utils.Performace.time("Build sqls");const i=this.trackerSqlBuilder.buildChangeSqls();u.Utils.Performace.restartTime(`Execute sqls (${i.length})`);const s=await this.connection.beginTrans();try{return await this.connection.executeBatch(i),await this.emit(d.events.saveChanges,t),u.Utils.Performace.restartTime("Accept changes"),this.entityTracker.acceptChanges(t),u.Utils.Performace.endTime(),this.clearLocks(),this.clearEntityTransactionIds(),await s.commit(),this.sessionSerial=t,this.log.debug(`SUCCESS saveChanges ( serial = ${t} )`),await this.emit(d.events.afterSaveChanges,t),t}catch(e){throw this.log.error(`FAILED saveChanges ( serial = ${t} )`,e),s.inTransaction&&(await s.rollback(),this.entityTracker.rejectChanges(),this.entityTracker.rollbackChanges(t)),e}}async rollbackChanges(e){if(this.sessionSerial<e)return this.sessionSerial;const t=this.sessionSerial;this.log.trace(`BEGIN rollbackChanges ( serial = ${e} )`),await this.emit(d.events.beforeRollbackChanges,{from:t,to:e});const i=await this.trackerSqlBuilder.buildRollbackChangeSqls(e+1),s=await this.connection.beginTrans();try{return await this.connection.executeBatch(i),await this.emit(d.events.rollbackChanges,{from:t,to:e}),this.entityTracker.rejectChanges(),await this.entityTracker.rollbackChanges(e+1),this.clearLocks(),this.clearEntityTransactionIds(),await s.commit(),this.sessionSerial=e,this.log.trace(`SUCCESS rollbackChanges (serial : ${t} -> ${e})`),await this.emit(d.events.afterRollbackChanges,{from:t,to:e}),this.sessionSerial}catch(i){throw this.log.error(`FAILED rollbackChanges (serial : ${t} -> ${e})`,i),s.inTransaction&&await s.rollback(),i}}ensureEntityTracking(e,t){let i=this.getCached(e,t);if(void 0===i){const s=this.loadEntityByKeySync(e,t);if(void 0===s)throw Error(`Entity not found ( model = '${e.modelName}', key = '${JSON.stringify(t)}' )`);i=this.entityTracker.trackPersistent(e,s)}return i}update(e,t,i){const s=this.ensureEntityTracking(e,t);this.entityTracker.trackModify(e,s,i)}increase(e,t,i){const s=this.ensureEntityTracking(e,t);let r={};return Object.keys(i).forEach(e=>{r[e]=void 0===s[e]?i[e]:i[e]+s[e]}),this.entityTracker.trackModify(e,s,r),r}delete(e,t){const i=this.ensureEntityTracking(e,t);this.entityTracker.trackDelete(e,i)}async beginTransaction(){return await this.connection.beginTrans()}beginEntityTransaction(e){if(void 0!==this.currentEntityTransactionId)throw new Error("Entity transactions cannot be nested");if(this.confirmedTransactionIdSet.has(e))throw new Error(`Transaction ${e} confirmed already`);this.entityTracker.beginConfirm(),this.currentEntityTransactionId=e}commitEntityTransaction(){this.entityTracker.confirm(),this.log.trace("commit locks",this.unconfirmedLocks),this.unconfirmedLocks.forEach(e=>this.confirmedLocks.add(e));const e=this.currentEntityTransactionId;e&&(this.log.trace("commit transactionId",e),this.confirmedTransactionIdSet.add(e),this.confirmedTransactionIdQueue.push(e),this.currentEntityTransactionId=void 0)}rollbackEntityTransaction(){this.entityTracker.cancelConfirm(),this.log.trace("rollback locks",this.unconfirmedLocks),this.unconfirmedLocks.clear(),this.currentEntityTransactionId=void 0}}d.DEFAULT_HISTORY_VERSION_HOLD=10,d.events={beforeSaveChanges:"beforeSaveChanges",saveChanges:"saveChanges",afterSaveChanges:"afterSaveChanges",beforeRollbackChanges:"beforeRollbackChanges",rollbackChanges:"rollbackChanges",afterRollbackChanges:"afterRollbackChanges"},t.DbSession=d},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=i(5),r=i(1),n=i(0),a=i(3),o=i(22)({separatedValues:!1});var c;t.MULTI_SQL_SEPARATOR=";",function(e){e[e.Schema=0]="Schema",e[e.Select=1]="Select",e[e.Insert=2]="Insert",e[e.Update=3]="Update",e[e.Delete=4]="Delete",e[e.Other=9]="Other"}(c=t.SqlType||(t.SqlType={}));class l{getTableName(e){return a.Utils.String.snakeCase(e)+"s"}getPrimaryKeyCondition(e,t){return e.setPrimaryKey({},t)}buildDropSchema(e){return`drop table "${this.getTableName(e.modelName)}"`}buildSchema(e){let t=new Array;const i=Object.assign({type:"create"},r.deepCopy(e.schemaObject));e.jsonProperties.forEach(e=>i.tableFields.find(t=>t.name===e).type=s.FieldTypes.Text),i.tableFields.filter(e=>n.isString(e.unique)).forEach(e=>Reflect.deleteProperty(e,"unique"));let a=o.build(i);t.push(a.query);const c=this.getTableName(e.modelName);e.indexes.forEach(e=>{t.push(o.build({type:"index",table:c,name:c+"_"+e.name,indexOn:e.properties.join(",")}).query)});const l=i.tableFields.filter(e=>!0===e.unique).map(e=>e.name),h=e.uniqueIndexes.filter(e=>!(1===e.properties.length&&l.some(t=>t===e.properties[0])));return e.isCompsiteKey&&h.push({name:"composite_primary_key",properties:e.compositeKeys}),h.forEach(e=>{t.push(o.build({type:"unique",table:c,name:c+"_"+e.name,uniqueOn:e.properties.join(",")}).query)}),t}buildInsert(e,t){let i={type:c.Insert};return Object.assign(i,o.build({type:"insert",table:this.getTableName(e.modelName),values:this.escapeObjectSingleQuotes(this.replaceJsonFields(e,t))}))}buildDelete(e,t){let i={type:c.Delete};return Object.assign(i,o.build({type:"remove",table:this.getTableName(e.modelName),condition:this.escapeObjectSingleQuotes(this.getPrimaryKeyCondition(e,t))}))}buildUpdate(e,t,i,s){const r=this.getTableName(e.modelName);let n=this.getPrimaryKeyCondition(e,t);n._version_=s;let a={type:c.Update};return Object.assign(a,o.build({type:"update",table:r,modifier:this.escapeObjectSingleQuotes(this.replaceJsonFields(e,i)),condition:this.escapeObjectSingleQuotes(n)}))}buildSelect(e,t,i,s,r,a){const l=this.getTableName(e.modelName);let h;if(n.isArray(t)){let o=t||e.properties.map(t=>e.schemaObject.table+"."+t),c=n.isNumber(s)?{limit:s}:s||{},u=r||{};for(let e of Reflect.ownKeys(u)){let t=u[e]||-1;u[e]="ASC"===t?1:"DESC"===t?-1:t}h={type:"select",table:l,fields:o,condition:this.escapeObjectSingleQuotes(Object.assign({},i)),limit:c.limit,offset:c.offset,sort:u,join:a}}else{let e=t;h=Object.assign({type:"select",table:l},e)}let u={type:c.Select};return Object.assign(u,o.build(h))}buildAggregate(e,t,i){const s={type:"select",table:this.getTableName(e.modelName),fields:[{expression:t}],condition:this.escapeObjectSingleQuotes(Object.assign({},i))};let r={type:c.Select};return Object.assign(r,o.build(s))}escapeSingleQuotes(e){return a.Utils.Lang.isString(e)?e.replace(l.singleQuoteRegex,"''"):e}escapeObjectSingleQuotes(e){return void 0===e||null===e?e:(Reflect.ownKeys(e).forEach(t=>{let i=e[t];a.Utils.Lang.isString(i)?e[t]=this.escapeSingleQuotes(i):a.Utils.Lang.isObject(i)&&this.escapeObjectSingleQuotes(i)}),e)}escapeStringSingleQuotes(e,t){return e.schemaObject.tableFields.forEach(e=>{e.type!==s.FieldTypes.String&&e.type!==s.FieldTypes.Text||(t[e.name]=this.escapeSingleQuotes(t[e.name]))}),t}replaceJsonFields(e,t){if(0===e.jsonProperties.length)return t;let i=Object.assign({},t);return e.jsonProperties.forEach(e=>{let s=t[e];Reflect.has(t,e)&&(i[e]=JSON.stringify(s))}),i}}l.singleQuoteRegex=new RegExp(/'/g),t.JsonSqlBuilder=l},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=i(26),r=i(8);class n{constructor(e){this.transacting=!0,this.connection=e}get inTransaction(){return this.transacting}async commit(){await this.connection.execute("COMMIT;"),this.transacting=!1}async rollback(){await this.connection.execute("ROLLBACK;"),this.transacting=!1}}t.SqliteConnection=class{constructor(e){this.options=e,this.sqlite=new s.SqliteWrapper}get connectionOptions(){return this.options}get isConnected(){return this.sqlite.isConnected}async connect(){return this.sqlite.asynOpen(this.options.storage)}async disconnect(){return await this.sqlite.asynClose()}async query(e,t){return await this.sqlite.asynQuery(e,t)}querySync(e,t){return this.sqlite.query(e,t)}ensureExecuteEffected(e){if(0===e.rowsEffected)throw new Error("None row effected")}executeBatchSync(e){return this.sqlite.executeBatch(e||[],this.ensureExecuteEffected)}async executeBatch(e){return await this.sqlite.asyncExecuteBatch(e||[],this.ensureExecuteEffected)}executeSync(e,t,i=!1){const s=this.sqlite.execute(e,t);return i&&this.ensureExecuteEffected(s),s}async execute(e,t,i=!1){const s=await this.sqlite.asynExecute(e,t);return i&&this.ensureExecuteEffected(s),s}async runScript(e){e.split(r.MULTI_SQL_SEPARATOR).forEach(async e=>await(""!==e.trim())&&this.sqlite.execute(e,[]))}async beginTrans(){return await this.execute("BEGIN TRANSACTION;"),new n(this)}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=i(11),r=i(5),n=i(7),a=i(9),o=i(2),c=i(6);!function(e){e.SmartDB=s.SmartDB,e.ModelSchema=r.ModelSchema,e.LogManager=o.LogManager,e.LogLevel=o.LogLevel,e.DbSession=n.DbSession,e.LevelBlock=c.LevelBlock,e.SqliteConnection=a.SqliteConnection}(t.AschCore||(t.AschCore={}))},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=i(0),r=i(12),n=i(13),a=i(1),o=i(6),c=i(7),l=i(9),h=i(2),u=i(28),d=i(4),g=i(3),m=5e3,y=10,f=10;class p extends a.AsyncEventEmitter{constructor(e,t,i){super(),a.CodeContract.argument("dbPath",()=>a.CodeContract.notNullOrWhitespace(e)),a.CodeContract.argument("levelBlockDir",()=>a.CodeContract.notNullOrWhitespace(t));const s={cachedBlockCount:f,maxBlockHistoryHold:y,blockTimeout:m};this.options=Object.assign({},s,i),this.schemas=new Map,this.log=h.LogManager.getLogger("SmartDB"),this.blockHeadersDB=new o.LevelBlock(t),this.cachedBlocks=new u.BlockCache(this.options.cachedBlockCount);const n=e.endsWith(".db")?r.dirname(e):e,d=r.join(n,this.options.blockChainDbName||"blockchain.db");this.blockConnection=new l.SqliteConnection({storage:d});const g={name:"Block",maxHistoryVersionsHold:this.options.maxBlockHistoryHold};this.blockSession=new c.DbSession(this.blockConnection,this.loadHistroyFromLevelDB.bind(this),g),this.blockSession.on(c.DbSession.events.saveChanges,this.onBlockSessionSaveChanges.bind(this)),this.blockSession.on(c.DbSession.events.rollbackChanges,this.onBlockSessionRollback.bind(this));const p=r.join(n,this.options.localDbName||"local.db");this.localConnection=new l.SqliteConnection({storage:p}),this.localSession=new c.DbSession(this.localConnection,null,{name:"Local"}),this.blockTimeout=this.options.blockTimeout}async onBlockSessionSaveChanges(e){await this.emit(p.events.commitBlock,e)}async onBlockSessionRollback(e){await this.emit(p.events.rollbackBlock,e)}getSchema(e,t=!1,i=!1){const r=s.isString(e)?String(e):e.name,n=this.schemas.get(r);return t&&a.CodeContract.verify(void 0!==n,`unregistered model '${r}'`),i&&a.CodeContract.verify(!n.isReadonly,`model '${r}' is readonly`),n}async loadHistroyFromLevelDB(e,t){return await this.blockHeadersDB.getHistoryChanges(e,t)}getSession(e){return e.isLocal?this.localSession:this.blockSession}get transactionSchema(){return this.getSchema(p.TRANSACTION_MODEL_NAME,!0,!0)}async init(e){a.CodeContract.argument("schemas",()=>a.CodeContract.notNull(e)),await this.blockConnection.connect(),await this.localConnection.connect(),await this.blockHeadersDB.open(),await this.syncSchemas(e),await this.ensureLastBlockLoaded(),await this.blockSession.initSerial(this.lastBlockHeight),this.lastLocalSessionSerial=0,await this.localSession.initSerial(0);const t=await this.checkSmartDB();t.consistent||(await this.tryRecover(t),await this.ensureLastBlockLoaded(),await this.blockSession.initSerial(this.lastBlockHeight)),this.emit("ready",this)}async tryRecover(e){if(e.consistent)return;const{blockHeight:t,dbHeight:i,maxTransactionHeight:s}=e;if(this.log.warn("SmartDB is inconsistent, try to recover...",{blockHeight:t,dbHeight:i,maxTransactionHeight:s}),!(t===i+1&&s<=i)){const t="SmartDB cannot be recovered automatically";throw this.log.error(t,e),new Error(t)}this.log.info("BEGIN recover SmartDB");try{await this.blockHeadersDB.deleteLastBlock(this.lastBlockHeight),this.cachedBlocks.evitUntil(this.lastBlockHeight),this.log.info("SUCCESS recover SmartDB, last height is",this.lastBlockHeight)}catch(e){this.log.error("FAILED recover SmartDB")}}async checkSmartDB(){const e=this.lastBlockHeight,{model:t,keyObject:i,valueField:s}=this.getBlockHeightSchema(),r=await this.load(t,i),n=r?Number.parseInt(r[s]):e,a=await this.queryAggregate(p.TRANSACTION_MODEL_NAME,{func:"max",args:["height"]})||-1;return{consistent:e===n&&n>=a,dbHeight:n,blockHeight:e,maxTransactionHeight:a}}async syncSchemas(e){for(const t of e){this.schemas.set(t.modelName,t);let e=this.getSession(t);if(e.registerSchema(t),e.syncSchema(t),this.log.info(`sync schema model = ${t.modelName} `),t.memCached){let i=await e.getMany(t,{},!0);this.log.info(`model ${t.modelName} cached ${i.length} entities `)}}if(void 0===this.transactionSchema)throw new Error("Transaction model is not found")}async updateSchema(e){a.CodeContract.argument("schema",()=>a.CodeContract.notNull(e));const t=this.getSchema(e.modelName),i=this.getSession(t);await i.updateSchema(e),this.log.info(`model ${e.modelName} schema updated `)}async close(){await this.blockSession.close(),await this.localSession.close(),await this.blockHeadersDB.close(),this.emit("closed",this)}get lastBlockHeight(){return this.blockHeadersDB.lastBlockHeight}get blocksCount(){return this.lastBlockHeight+1}get lastBlock(){return this.cachedBlocks.get(this.lastBlockHeight)}lockInCurrentBlock(e,t=!1){return this.blockSession.lockInThisSession(e,t)}lock(e){this.lockInCurrentBlock(e,!1)}tryLock(e){return this.lockInCurrentBlock(e,!0)}beginContract(e){this.blockSession.beginEntityTransaction(e)}async commitContract(){await this.emit(p.events.beforeCommitContract),this.blockSession.commitEntityTransaction(),await this.emit(p.events.afterCommitContract)}async rollbackContract(){await this.emit(p.events.beforeRollbackContract),this.blockSession.rollbackEntityTransaction(),await this.emit(p.events.afterRollbackContract)}async beginBlock(e){a.CodeContract.argument("block",()=>a.CodeContract.notNull(e)),a.CodeContract.argument("block",e.height===this.lastBlockHeight+1,`invalid block height ${e.height}, last = ${this.lastBlockHeight}`),this.log.info(`BEGIN block height = ${e.height}`),this.currentBlock=e,e.version&&e.version>0&&await this.saveBlockHeight(e.height)}async saveBlockHeight(e){const{model:t,keyObject:i,valueField:s}=this.getBlockHeightSchema(),r={};r[s]=String(e),this.createOrLoad(t,Object.assign({},i,r)),this.update(t,r,i),await this.commitContract(),this.log.trace(`save block height = ${e}`)}getBlockHeightSchema(){const{parametersModel:e="Variable",keyField:t="key",valueField:i="value"}=this.options.external||{},s={};return s[t]="last_block_height",{model:e,keyObject:s,valueField:i}}getChangesHash(e=!1){return this.calcTransactionChangesHash(this.blockSession.getChanges(),e)}getConfirmedTransactionIds(){return this.blockSession.confirmedTransactionIds}calcTransactionChangesHash(e,t=!1){if(e.length<=0)return"";const i=n.createHash("sha256");let s=!0;if(t)s=e.every(e=>!this.updateEntityChangesHash(e,i));else for(const t of e)this.updateEntityChangesHash(t,i)&&(s=!1);return s?"":i.digest().toString("hex")}updateEntityChangesHash(e,t){let i=!1;for(const s of e.propertyChanges.sort((e,t)=>e.name.localeCompare(t.name)))s.name!==d.ENTITY_VERSION_PROPERTY&&(a.nullOrUndefined(s.current)&&a.nullOrUndefined(s.original)||(i=!0,t.update(s.name),a.nullOrUndefined(s.current)||t.update(JSON.stringify(s.current)),a.nullOrUndefined(s.original)||t.update(JSON.stringify(s.original))));return i}setBlockTimeout(e){this.blockTimeout=e}async commitBlock(){if(!this.currentBlock)throw new Error("Current block is null");const e=(this.currentBlock.transactions||[]).map(e=>e.id);this.ensureTransactionsConfirmed(e);let t=Object.assign({},this.currentBlock);Reflect.deleteProperty(t,"transactions"),this.log.debug(`BEGIN commitBlock height = ${this.currentBlock.height}`),await this.emit(p.events.beforeCommitBlock,this.currentBlock.height);try{const e=await this.doCommitBlock(t);return this.currentBlock=null,this.log.info(`SUCCESS commitBlock height = ${this.lastBlockHeight}`),await this.emit(p.events.afterCommitBlock,this.lastBlockHeight),e}catch(e){throw this.log.error(`FAILED commitBlock ( height = ${t.height} )`,e),e}}ensureTransactionsConfirmed(e){const t=this.blockSession.confirmedTransactionIds;if(!(e.length===t.length&&e.every((e,i)=>e===t[i]))){const i="Invalid confirmed transactions";throw this.log.error(`${i}, expect is`,e,"exact is ",t),new Error(i)}}async callWithCheckTimeout(e,t,i,s){if(i<=0)return await e();let r=!1;const n=setTimeout(()=>{r||this.emit(t,Object.assign({},s,{timeout:i}))},i);try{return await e()}finally{r=!0,clearTimeout(n)}}async doCommitBlock(e){return await this.callWithCheckTimeout(async()=>{await this.blockHeadersDB.appendBlock(e,this.blockSession.getChanges());try{return await this.blockSession.saveChanges(e.height),this.cachedBlocks.push(e),this.lastBlockHeight}catch(t){throw await this.blockHeadersDB.deleteLastBlock(e.height),t}},p.events.commitBlockTimeout,this.blockTimeout,{height:e.height})}async rollbackBlock(e){a.CodeContract.argument("height",void 0===e||e<=this.lastBlockHeight&&e>=0,`height must less or equal lastBlockHeight ${this.lastBlockHeight}`);const t=this.lastBlockHeight,i=void 0===e?this.lastBlockHeight:e;this.log.debug(`BEGIN rollbackBlock ( height : ${this.lastBlockHeight} -> ${i} )`),await this.emit(p.events.beforeRollbackBlock,{from:t,to:i});try{for(await this.blockSession.rollbackChanges(this.lastBlockHeight);this.lastBlockHeight>i;)await this.doRollbackLastBlock(this.lastBlockHeight-1);this.currentBlock=null,this.log.info(`SUCCESS rollbackBlock ( height : ${t} -> ${i} )`),await this.emit(p.events.afterRollbackBlock,{from:t,to:i})}catch(e){throw this.log.error(`FAILED rollbackBlock ( height : ${t} -> ${i} )`,e),e}}async doRollbackLastBlock(e){return this.callWithCheckTimeout(async()=>{await this.blockSession.rollbackChanges(e),await this.blockHeadersDB.deleteLastBlock(e+1),this.cachedBlocks.evitUntil(e),await this.ensureLastBlockLoaded()},p.events.rollbackBlockTimeout,this.blockTimeout,{height:e})}async saveLocalChanges(){return this.lastLocalSessionSerial=await this.localSession.saveChanges(),this.lastLocalSessionSerial}async rollbackLocalChanges(e){a.CodeContract.argument("serial",void 0===e||e>=0,"serial must great or equal zero");const t=void 0===e?this.lastLocalSessionSerial:e;await this.localSession.rollbackChanges(t),this.lastLocalSessionSerial=t}create(e,t){a.CodeContract.argument("model",()=>a.CodeContract.notNull(e)),a.CodeContract.argument("entity",()=>a.CodeContract.notNull(t));const i=this.getSchema(e,!0,!0);return this.getSession(i).create(i,t)}createOrLoad(e,t){a.CodeContract.argument("model",()=>a.CodeContract.notNull(e)),a.CodeContract.argument("entity",()=>a.CodeContract.notNull(t));const i=this.getSchema(e,!0,!0),s=this.loadSync(e,i.getNormalizedPrimaryKey(t));return{create:void 0===s,entity:s||this.create(e,t)}}increase(e,t,i){a.CodeContract.argument("model",()=>a.CodeContract.notNull(e)),a.CodeContract.argument("increasements",()=>a.CodeContract.notNull(t)),a.CodeContract.argument("key",()=>a.CodeContract.notNull(i));const s=this.getSchema(e,!0,!0);return this.getSession(s).increase(s,i,t)}update(e,t,i){a.CodeContract.argument("model",()=>a.CodeContract.notNull(e)),a.CodeContract.argument("modifier",()=>a.CodeContract.notNull(t)),a.CodeContract.argument("key",()=>a.CodeContract.notNull(i));const s=this.getSchema(e,!0,!0);if(!0===this.options.checkModifier){const e=Object.keys(t),i=g.Utils.Array.without(s.properties,...e);if(i.length>0)throw new Error(`modifier or entity contains property which is not defined in model (${JSON.stringify(i)})`)}this.getSession(s).update(s,i,t)}del(e,t){a.CodeContract.argument("model",()=>a.CodeContract.notNull(e)),a.CodeContract.argument("key",()=>a.CodeContract.notNull(t));const i=this.getSchema(e,!0,!0);this.getSession(i).delete(i,t)}async load(e,t){a.CodeContract.argument("model",()=>a.CodeContract.notNull(e)),a.CodeContract.argument("key",()=>a.CodeContract.notNull(t));const i=this.getSchema(e,!0);return await this.getSession(i).load(i,t)}loadSync(e,t){a.CodeContract.argument("model",()=>a.CodeContract.notNull(e)),a.CodeContract.argument("key",()=>a.CodeContract.notNull(t));const i=this.getSchema(e,!0);return this.getSession(i).loadSync(i,t)}async loadMany(e,t,i=!0){a.CodeContract.argument("model",()=>a.CodeContract.notNull(e));const s=this.getSchema(e,!0);return await this.getSession(s).getMany(s,t,i)}get(e,t){a.CodeContract.argument("model",()=>a.CodeContract.notNull(e)),a.CodeContract.argument("key",()=>a.CodeContract.notNull(t));const i=this.getSchema(e,!0);return this.getSession(i).getCachedEntity(i,t)}getAll(e,t){a.CodeContract.argument("model",()=>a.CodeContract.notNull(e));const i=this.getSchema(e,!0);return a.CodeContract.argument("model",i.memCached,"getAll only support for memory model"),this.getSession(i).getAll(i,t)}async find(e,t,i,s,r,n){a.CodeContract.argument("model",()=>a.CodeContract.notNull(e));const o=this.getSchema(e,!0);return await this.getSession(o).query(o,t,i,s,r,n)}async findOne(e,t){let i=await this.findAll(e,t);if(i.length>1){const i=this.getSchema(e,!0);throw new Error(`many entities found ( model = '${i.modelName}' , params = '${JSON.stringify(t)}' )`)}return 0===i.length?void 0:i[0]}async queryAggregate(e,t,i){a.CodeContract.argument("model",()=>a.CodeContract.notNull(e));const s=this.getSchema(e,!0);return await this.getSession(s).queryAggregate(s,t,i)}async sqlQuery(e,t,i={}){a.CodeContract.argument("model",()=>a.CodeContract.notNull(e));const s=this.getSchema(e,!0),r=this.getSession(s);return await r.sqlQuery(t,i)||[]}async findAll(e,t){a.CodeContract.argument("model",()=>a.CodeContract.notNull(e));const i=this.getSchema(e,!0);return await this.getSession(i).queryByJson(i,t)}async exists(e,t){a.CodeContract.argument("model",()=>a.CodeContract.notNull(e));const i=this.getSchema(e,!0);return await this.getSession(i).exists(i,t)}async count(e,t){a.CodeContract.argument("model",()=>a.CodeContract.notNull(e));const i=this.getSchema(e,!0);return await this.getSession(i).count(i,t)}async ensureLastBlockLoaded(){if(void 0===this.lastBlock&&this.lastBlockHeight>=0){const e=await this.getBlockByHeight(this.lastBlockHeight,!0);a.CodeContract.verify(!!e,`Fail to load block, height = ${this.lastBlockHeight} `),this.log.trace(`SUCCESS load last block (height = ${e.height}, id = '${e.id}')`),this.cachedBlocks.push(e)}}async getBlockByHeight(e,t=!1){a.CodeContract.argument("height",e>=0,"height must great or equal zero");let i=this.copyCachedBlock(()=>this.cachedBlocks.get(e),t);if(i)return i;let s=await this.blockHeadersDB.getBlock(e);if(!t||void 0===s)return s;return(await this.attachTransactions([s],async()=>await this.blockSession.query(this.transactionSchema,{height:s.height})))[0]}async getBlockById(e,t=!1){a.CodeContract.argument("blockId",()=>a.CodeContract.notNullOrWhitespace(e));let i=this.copyCachedBlock(()=>this.cachedBlocks.getById(e),t);if(i)return i;let s=await this.blockHeadersDB.getBlockById(e);if(!t||void 0===s)return s;return(await this.attachTransactions([s],async()=>await this.blockSession.query(this.transactionSchema,{height:s.height})))[0]}async getBlocksByHeightRange(e,t,i=!1){a.CodeContract.argument("minHeight, maxHeight",e>=0&&t>=e,"minHeight or maxHeight is invalid");let s=await this.blockHeadersDB.getBlocksByHeightRange(e,t);return i?await this.attachTransactions(s,async()=>await this.blockSession.query(this.transactionSchema,{height:{$in:s.map(e=>e.height)}})):s}async getBlocksByIds(e,t=!1){a.CodeContract.argument("blockIds",()=>a.CodeContract.notNull(e));let i=await this.blockHeadersDB.getBlocksByIds(e);return t?await this.attachTransactions(i,async()=>await this.blockSession.query(this.transactionSchema,{height:{$in:i.map(e=>e.height)}})):i}async attachTransactions(e,t){let i=new Map;return(await t()).forEach(e=>{i.has(e.blockId)||i.set(e.blockId,new Array),i.get(e.blockId).push(e)}),e.forEach(e=>e.transactions=i.get(e.id)||[]),e}copyCachedBlock(e,t){let i=e();if(void 0===i)return;let s=Object.assign({},i);return t||Reflect.deleteProperty(s,"transactions"),s}}p.TRANSACTION_MODEL_NAME="Transaction",p.events={beforeCommitBlock:"beforeCommitBlock",commitBlock:"commitBlock",afterCommitBlock:"afterCommitBlock",beforeRollbackBlock:"beforeRollbackBlock",rollbackBlock:"rollbackBlock",afterRollbackBlock:"afterRollbackBlock",beforeCommitContract:"beforeCommitContract",afterCommitContract:"afterCommitContract",beforeRollbackContract:"beforeRollbackContract",afterRollbackContract:"afterRollbackContract",commitBlockTimeout:"commitBlockTimeout",rollbackBlockTimeout:"rollbackBlockTimeout"},t.SmartDB=p},function(e,t){e.exports=require("path")},function(e,t){e.exports=require("crypto")},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=i(0),r=i(15),n=i(16),a=i(17);function o(e){let t=null;return e||(t=(e=function(){let e,t=new Promise((t,i)=>{e=((e,s)=>e?i(e):t(s))});return e.promise=t,e}()).promise),{callback:e,promise:t}}t.SubLevelMeta=class{constructor(e,t,i=new Array){this.subName=e,this.keyField=t,this.indexFields=(new Array).concat(i)}findIndexOfFieldName(e){return this.indexFields.findIndex(t=>e===t.fieldName)}existsIndex(e){return this.findIndexOfFieldName(e)>-1}addIndex(e,t){if(this.existsIndex(e))throw new Error(`Index of field '${e}' already exists`);return this.indexFields.push({fieldName:e,calcIndex:t}),this}removeIndex(e){const t=this.findIndexOfFieldName(e);return t>-1&&this.indexFields.slice(t,1),this}};class c{constructor(e,t,i={}){this.dbDir=e,this.subMetas=(new Array).concat(t),this.subLevels=new Map,this.leveldb=null}async init(){this.leveldb=n(this.dbDir,{valueEncoding:"json"}),this.subLeveldb=r(this.leveldb),this.subMetas.forEach(e=>this.registerSubLevel(e))}registerSubLevel(e){const t=this.subLeveldb.sublevel(e.subName),i=new l(t,e.subName,e.keyField,...e.indexFields);this.subLevels.set(e.subName,i)}static isKeyNotFoundError(e){return e&&"NotFoundError"===e.name}get level(){return this.leveldb}getSubLevel(e){const t=this.subLevels.get(e);if(!t)throw new Error(`No such subLevel name = '${e}'`);return t}open(e){let t=this,{callback:i,promise:s}=o(e);return this.isOpen?(process.nextTick(i,null,t),s):((async()=>{try{await this.init(),process.nextTick(i,null,t)}catch(e){process.nextTick(i,e,t)}})(),s)}close(e){let t=this,{callback:i,promise:s}=o(e);return this.isClosed?(process.nextTick(i,null,t),s):((async()=>{try{await this.leveldb.close(),this.leveldb=null,process.nextTick(i,null,t)}catch(e){process.nextTick(i,e)}})(),s)}get isOpen(){return this.leveldb&&this.leveldb.isOpen()}get isClosed(){return!this.leveldb||this.leveldb.isClosed()}dump(){return new Promise((e,t)=>{let i=new Array;this.leveldb.createReadStream().on("data",e=>i.push(`key= ${e.key}, value= ${e.value}`)).on("error",e=>t(e)).on("end",()=>e(i.join("\r\n")))})}}t.LevelDB=c;class l{get name(){return this.subName}get indexes(){return this.indexArray}constructor(e,t,i,...s){this.subLevelDb=e,this.subName=t,this.keyField=i,this.indexArray=(new Array).concat(...s),this.indexedSubLevels=new Map,this.indexArray.forEach(t=>{let i=a(e,t.fieldName,t.calcIndex);this.indexedSubLevels.set(t.fieldName,i)})}get key(){return this.keyField}keyNotFoundThenUndefined(e){return e?(t,i)=>{e(c.isKeyNotFoundError(t)?null:t,i)}:void 0}async get(e,t,i){const s=this.subLevelDb;let{callback:r,promise:n}=o(i);try{s.get(e,t,this.keyNotFoundThenUndefined(r))}catch(e){r(c.isKeyNotFoundError(e)?void 0:e,void 0)}return n}byIndex(e){const t=this.indexedSubLevels.get(e);if(!t)throw new Error(`No such index field = '${e}'`);return t}async getBy(e,t,i){const s=this.byIndex(e);let{callback:r,promise:n}=o(i);try{s.get(t,this.keyNotFoundThenUndefined(r))}catch(e){r(c.isKeyNotFoundError(e)?void 0:e,void 0)}return n}async put(e,t,i){let{callback:s,promise:r}=o(i);try{this.subLevelDb.put(e,t,s)}catch(e){s(e,void 0)}return r}async del(e,t){let{callback:i,promise:s}=o(t);try{this.subLevelDb.del(e,i)}catch(e){i(e,void 0)}return s}async batch(e,t,i){if(0===arguments.length)return this.subLevelDb.batch();let r=t&&!s.isFunction(t),n=r?i:t,{callback:a,promise:c}=o(n);try{r?this.subLevelDb.batch(e,t,a):this.subLevelDb.batch(e,a)}catch(e){a(e,void 0)}return c}createReadStream(e){return this.subLevelDb.createReadStream(e)}createKeyStream(e){return this.subLevelDb.createKeyStream(e)}createValueStream(e){return this.subLevelDb.createValueStream(e)}}},function(e,t){e.exports=require("level-sublevel")},function(e,t){e.exports=require("level")},function(e,t){e.exports=require("level-secondary")},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=i(19),r=i(20),n=i(2);class a{constructor(e,t){this.modelSchema=e,this.lruCache=new s({max:t,dispose:this.doEvit.bind(this)})}doEvit(e,t){this.postEvit&&this.postEvit(e,t)}get onEvit(){return this.postEvit}set onEvit(e){this.postEvit=e}get model(){return this.modelSchema}clear(){this.lruCache.reset()}has(e){return this.lruCache.has(e)}get(e){return this.lruCache.get(e)}forEach(e){this.lruCache.forEach(e)}set(e,t){this.lruCache.set(e,t)}evit(e){this.lruCache.del(e)}exists(e){return this.lruCache.has(e)}}class o extends r.UniquedEntityCache{constructor(e){super(n.LogManager.getLogger("LRUEntityCache"),e)}getMaxCachedCount(e){const t=e.maxCached||o.DEFULT_MAX_CACHED_COUNT;return Math.max(o.MIN_CACHED_COUNT,t)}createCache(e){return new a(e,this.getMaxCachedCount(e))}}o.MIN_CACHED_COUNT=100,o.DEFULT_MAX_CACHED_COUNT=1e4,t.LRUEntityCache=o},function(e,t){e.exports=require("lru-cache")},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=i(1),r=i(0);class n{constructor(e,t){this.name=e,this.indexFields=t,this.indexMap=new Map}get indexName(){return this.name}get fields(){return this.indexFields}getIndexKey(e){return JSON.stringify(e)}exists(e){return this.indexMap.has(this.getIndexKey(e))}get(e){return this.indexMap.get(this.getIndexKey(e))}add(e,t){const i=this.getIndexKey(e);if(this.indexMap.has(i))throw new Error(`Unique named '${this.name}' key = '${i}' exists already`);this.indexMap.set(i,t)}delete(e){this.indexMap.delete(this.getIndexKey(e))}}t.DefaultEntityUniqueIndex=n;class a{constructor(e,t){this.cache=e,this.cache.onEvit=this.afterEvit.bind(this),this.indexes=new Map,t.forEach(e=>this.indexes.set(e.name,this.createUniqueIndex(e)))}createUniqueIndex(e){return new n(e.name,e.properties)}afterEvit(e,t){this.indexes.forEach(e=>{let i=s.partialCopy(t,e.fields);e.delete(i)})}has(e){return this.cache.has(e)}set(e,t){this.cache.has(e)&&this.evit(e),this.cache.set(e,t),this.indexes.forEach(i=>{if(i.fields.some(e=>s.nullOrUndefined(t[e])))return;let r=s.partialCopy(t,i.fields);i.add(r,String(e))})}get(e){return this.cache.get(e)}forEach(e){this.cache.forEach(e)}evit(e){let t=this.cache.get(e);void 0!==t&&(this.cache.evit(e),this.afterEvit(e,t))}getUnique(e,t){let i=this.indexes.get(e).get(t);return void 0===i?void 0:this.cache.get(i)}clear(){this.forEach((e,t)=>this.evit(t))}}t.UniquedCache=a;t.UniquedEntityCache=class{constructor(e,t){this.log=e,this.modelSchemas=t,this.modelCaches=new Map}createCache(e){throw new s.NotImplementError}registerModel(e,t){const i=e.modelName;if(this.modelCaches.has(i))throw new Error(`model '${i}' exists already`);let s=this.createCache(e);this.modelCaches.set(i,new a(s,t))}unRegisterModel(e){this.modelCaches.delete(e)}getModelCache(e){const t=this.modelSchemas.get(e);if(void 0===t)throw new Error(`Model schema ( name = '${e}' ) does not exists`);return this.modelCaches.has(e)||this.registerModel(t,t.uniqueIndexes),this.modelCaches.get(e)}getCacheKey(e){return s.isPrimitiveKey(e)?String(e):JSON.stringify(e)}clear(e){if(r.isString(e))return this.getModelCache(e).clear(),void this.modelCaches.delete(e);for(let e of this.modelCaches.values())e.clear();this.modelCaches.clear()}get models(){return new Array(...this.modelSchemas.values())}get(e,t){let i=this.getModelCache(e),s=this.getCacheKey(t);return this.modelCaches.has(e)&&i.has(s)?i.get(s):void 0}getUnique(e,t,i){return this.getModelCache(e).getUnique(t,i)}existsUnique(e,t,i){return void 0!==this.getUnique(e,t,i)}refreshCached(e,t,i){const s=this.get(e,t);if(void 0===s)return!1;const r=i.map(e=>e.name);return this.modelSchemas.get(e).hasUniqueProperty(...r)?(this.log.trace("refresh cached with uniqued index, key = %t modifier = %t",t,i),this.evit(e,t),i.forEach(e=>s[e.name]=e.value),this.put(e,t,s),!0):(this.log.trace("refresh cached entity, key = %t modifier = %t",t,i),i.forEach(e=>s[e.name]=e.value),!1)}getAll(e,t){let i=new Array,s=this.getModelCache(e);if(void 0!==s)return s.forEach(e=>{t&&!t(e)||i.push(e)}),i}put(e,t,i){this.log.trace(`put cache, model = ${e}, key = %t, entity = %t`,t,i),this.getModelCache(e).set(this.getCacheKey(t),i)}evit(e,t){let i=this.getCacheKey(t);this.log.trace(`evit cache, model = ${e}, key = %t`,i);const s=this.getModelCache(e);s&&s.evit(i)}exists(e,t){return void 0!==this.get(e,this.getCacheKey(t))}existsModel(e){return this.modelCaches.has(e)}dumpCache(){let e="-------------- DUMP CACHE ----------------\n\n";return this.modelCaches.forEach((t,i)=>{e+=`--------------Model ${i}----------------\n`,t.forEach((t,i)=>{e+=`key = ${this.getCacheKey(i)}, entity = {${JSON.stringify(t)}} \n`}),e+="\n"}),e+="-------------- END DUMP ----------------\n"}}},function(e,t){e.exports=require("lodash")},function(e,t){e.exports=require("json-sql")},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=i(1),r=i(4);class n{constructor(e,t,i){this.tracker=e,this.schemas=t,this.sqlBuilder=i}get entityTracker(){return this.tracker}buildChangeSqls(){return this.tracker.getConfirmedChanges().map(e=>this.buildSqlAndParameters(this.schemas.get(e.model),e.primaryKey,e))}async buildRollbackChangeSqls(e){let t=new Array;const i=await this.tracker.getChangesUntil(e);let s;for(;void 0!==(s=i.pop());){const e=this.schemas.get(s.model);t.push(this.buildRollbackSqlAndParameters(e,s.primaryKey,s))}return t}static fieldValuesFromChanges(e,t=!1){return t?s.makeJsonObject(e.propertyChanges,e=>e.name,e=>e.original):s.makeJsonObject(e.propertyChanges,e=>e.name,e=>e.current)}buildSqlAndParameters(e,t,i){const s=n.fieldValuesFromChanges(i);switch(s[r.ENTITY_VERSION_PROPERTY]=i.dbVersion,i.type){case r.EntityChangeType.New:return this.sqlBuilder.buildInsert(e,s);case r.EntityChangeType.Modify:return this.sqlBuilder.buildUpdate(e,t,s,i.dbVersion-1);case r.EntityChangeType.Delete:return this.sqlBuilder.buildDelete(e,t);default:throw new Error(`Invalid EntityChangeType '${i.type}'`)}}buildRollbackSqlAndParameters(e,t,i){const s=n.fieldValuesFromChanges(i,!0);switch(i.type){case r.EntityChangeType.New:return this.sqlBuilder.buildDelete(e,t);case r.EntityChangeType.Modify:return s[r.ENTITY_VERSION_PROPERTY]=i.dbVersion-1,this.sqlBuilder.buildUpdate(e,t,s,i.dbVersion);case r.EntityChangeType.Delete:return this.sqlBuilder.buildInsert(e,s);default:throw new Error(`Invalid EntityChangeType '${i.type}'`)}}}t.BasicTrackerSqlBuilder=n},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=i(25),r=i(2);t.SnapshotEntityTracker=class extends s.BasicEntityTracker{constructor(e,t,i,s){super(e,t,i,r.LogManager.getLogger("SnapshotEntityTracker"),s)}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=i(3),r=i(1),n=i(4),a=i(0);t.Stack=Array;t.BasicEntityTracker=class{constructor(e,i,s,r,n){this.log=r,this.cache=e,this.confirming=!1,this.schemas=i,this.doLoadHistory=n,this.history=new Map,this.allTrackingEntities=new Map,this.unconfirmedChanges=new t.Stack,this.confirmedChanges=new t.Stack,this.currentVersion=-1,this.maxHistoryVersionsHold=s}async loadHistory(e,t){return a.isFunction(this.doLoadHistory)?await this.doLoadHistory(e,t):new Map}getMinVersionHold(){if(0===this.history.size)return-1;let e=Number.MAX_SAFE_INTEGER;for(const t of this.history.keys())e=Math.min(e,t);return e}async initVersion(e){this.currentVersion>=0&&(this.currentVersion=-1,this.history.clear());const t=await this.loadHistory(e,e);this.attachHistory(t)}makeModelAndKey(e,t){let i={m:e.modelName,k:t};return JSON.stringify(i)}splitModelAndKey(e){let t=JSON.parse(e);return{model:t.m,key:t.k}}get trackingEntities(){return this.allTrackingEntities.values()}isTracking(e,t){const i=this.makeModelAndKey(e,t);return this.allTrackingEntities.has(i)}getConfirmedChanges(){return this.confirmedChanges}get changesStack(){return this.isConfirming?this.unconfirmedChanges:this.confirmedChanges}buildTrackingEntity(e,t,i){return t}ensureNotracking(e,t){if(void 0!==this.getTrackingEntity(e,t))throw Error(`Entity (model='${e.modelName}', key='${JSON.stringify(t)}') is tracking already`)}getTracking(e,t){const i=this.getTrackingEntity(e,t);if(void 0===i)throw Error(`Entity (model='${e.modelName}', key='${JSON.stringify(t)}') is not tracking`);return i}trackNew(e,t){const i=e.getNormalizedPrimaryKey(t);this.ensureNotracking(e,i);let r=s.Utils.Lang.cloneDeep(t);e.setDefaultValues(r),r[n.ENTITY_VERSION_PROPERTY]=1;let a=this.buildTrackingEntity(e,r,n.EntityState.New);return this.cache.put(e.modelName,i,a),this.changesStack.push(this.buildCreateChanges(e,r)),a}trackPersistent(e,t){const i=e.getNormalizedPrimaryKey(t);this.ensureNotracking(e,i);const r=s.Utils.Lang.cloneDeep(t);let a=this.buildTrackingEntity(e,r,n.EntityState.Persistent);return this.cache.put(e.modelName,i,a),a}trackDelete(e,t){this.changesStack.push(this.buildDeleteChanges(e,t,t._version_)),this.cache.evit(e.modelName,e.getNormalizedPrimaryKey(t))}trackModify(e,t,i){const r=Object.keys(i).filter(r=>e.isValidProperty(r)&&r!==n.ENTITY_VERSION_PROPERTY&&!s.Utils.Lang.isEqual(t[r],i[r])).map(e=>({name:e,value:i[e]}));0!==r.length&&(this.changesStack.push(this.buildModifyChanges(e,t,r,++t._version_)),this.cache.refreshCached(e.modelName,e.getNormalizedPrimaryKey(t),r))}getTrackingEntity(e,t){const i=e.resolveKey(t);if(void 0!==i)return i.isPrimaryKey?this.cache.get(e.modelName,i.key):this.cache.getUnique(e.modelName,i.uniqueName,i.key)}acceptChanges(e){this.log.trace(`BEGIN acceptChanges Version = ${e}`),this.history.set(e,this.confirmedChanges),this.confirmedChanges=new t.Stack,this.removeExpiredHistory(),this.allTrackingEntities.clear(),this.currentVersion=e,this.log.trace(`SUCCESS acceptChanges Version = ${e}`)}buildCreateChanges(e,t){let i=new Array;for(const s in t)e.isValidProperty(s)&&i.push({name:s,current:t[s]});return{type:n.EntityChangeType.New,model:e.modelName,primaryKey:e.getNormalizedPrimaryKey(t),dbVersion:1,propertyChanges:i}}buildModifyChanges(e,t,i,s){let r=new Array;return i.forEach(e=>r.push({name:e.name,current:e.value,original:t[e.name]})),r.push({name:n.ENTITY_VERSION_PROPERTY,current:s,original:s-1}),{type:n.EntityChangeType.Modify,model:e.modelName,primaryKey:e.getNormalizedPrimaryKey(t),dbVersion:s,propertyChanges:r}}buildDeleteChanges(e,t,i){let s=new Array;for(const i in t)e.isValidProperty(i)&&s.push({name:i,original:t[i]});return{type:n.EntityChangeType.Delete,model:e.modelName,primaryKey:e.getNormalizedPrimaryKey(t),dbVersion:i,propertyChanges:s}}undoEntityChanges(e){switch(e.type){case n.EntityChangeType.New:this.cache.get(e.model,e.primaryKey)&&this.cache.evit(e.model,e.primaryKey);break;case n.EntityChangeType.Modify:const t=e.propertyChanges.map(e=>({name:e.name,value:e.original}));this.cache.refreshCached(e.model,e.primaryKey,t);break;case n.EntityChangeType.Delete:let i=r.makeJsonObject(e.propertyChanges,e=>e.name,e=>e.original);const s=this.schemas.get(e.model),a=this.buildTrackingEntity(s,i,n.EntityState.Persistent);this.trackPersistent(s,a)}}undoChanges(e){let t;for(;void 0!==(t=e.pop());)this.undoEntityChanges(t)}rejectChanges(){this.cancelConfirm(),this.undoChanges(this.confirmedChanges)}async rollbackChanges(e){if(e>this.currentVersion)return;const t=this.currentVersion;for(this.log.trace(`BEGIN rollbackChanges Version : ${t}`),await this.loadHistoryUntil(e);this.currentVersion>=e;){const e=this.getHistoryByVersion(this.currentVersion);this.undoChanges(e),this.history.delete(this.currentVersion),this.currentVersion--}this.log.trace(`SUCCESS rollbackChanges Version : ${t} -> ${this.currentVersion}`)}get isConfirming(){return this.confirming}beginConfirm(){this.confirming=!0,this.unconfirmedChanges.length>0&&this.log.warn(`${this.unconfirmedChanges.length} unconfimred changes detected, did you forget to call confirm / cancelConfirm ?`),this.unconfirmedChanges=new t.Stack,this.log.trace("BEGIN beginConfirm")}confirm(){this.confirmedChanges.push(...this.unconfirmedChanges),this.unconfirmedChanges=new t.Stack,this.confirming=!1,this.log.trace("SUCCESS confirm ")}cancelConfirm(){this.undoChanges(this.unconfirmedChanges),this.confirming=!1,this.log.trace("SUCCESS cancelConfirm ")}attachHistory(e){this.log.info("BEGIN attachHistory history version =",{min:this.getMinVersionHold(),max:this.currentVersion}),e.forEach((e,t)=>{this.history.set(t,e),this.currentVersion=Math.max(t,this.currentVersion)}),this.log.info(`SUCCESS attachHistory version = ${JSON.stringify([...e.keys()])}`)}getHistoryByVersion(e,i=!1){return!this.history.has(e)&&i&&this.history.set(e,new t.Stack),this.history.get(e)}async loadHistoryUntil(e){const t=this.getMinVersionHold(),i=t<0?this.currentVersion:t-1;if(e<t||t<0){const t=await this.loadHistory(e,i);this.attachHistory(t)}}removeExpiredHistory(){this.history.size>this.maxHistoryVersionsHold&&this.clearHistoryBefore(this.currentVersion-this.maxHistoryVersionsHold)}async getChangesUntil(e){await this.loadHistoryUntil(e);const i=new t.Stack;let s=e;for(;s<=this.currentVersion;){let e=this.getHistoryByVersion(s++);e&&i.push(...e)}return i}clearHistoryBefore(e){const t=this.getMinVersionHold();if(!(t>=e||this.currentVersion<e))for(let i=t;i<e;i++)this.history.delete(i)}}},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const s=i(0),r=i(2),n=i(27);t.SqliteWrapper=class{constructor(){this.log=r.LogManager.getLogger("SqliteWrapper")}open(e,t){let i={err:null,result:!0};try{this.db=new n(e),this.log.debug(`SUCCESS open ( db = ${e} )`)}catch(s){if(i={err:s,result:!1},this.log.error(`FAILED open ( db = ${e} )`,s),!t)throw s}return t&&t(i.err,i.result),i.result}get isConnected(){return this.db.open}async asynOpen(e){return s.promisify(this.open).call(this,e)}close(e){let t={err:null,result:!0};try{this.db&&this.isConnected?(this.db.close(),this.log.trace("SUCCESS close")):this.log.info("closed already")}catch(i){if(t={err:i,result:!1},this.log.error("FAILED close",i),!e)throw i}return e&&e(t.err,t.result),t.result}asynClose(){return s.promisify(this.close).call(this)}execute(e,t,i){let s={err:null,result:{lastInsertRowId:"0",rowsEffected:0}};try{const r=this.db.prepare(e).run(t||[]);s.result={lastInsertRowId:r.lastInsertROWID.toString(),rowsEffected:r.changes},this.log.trace(`SUCCESS execute sql = ${e} param = %t, effected = ${s.result.rowsEffected}`,t)}catch(r){if(s.err=r,this.log.error(`FAILED execute sql = ${e} param = %t`,t,r),!i)throw r}return i&&i(s.err,s.result),s.result}query(e,t,i){let s={err:null,result:new Array};try{s.result=this.db.prepare(e).all(t||[]),this.log.trace(`SUCCESS query sql = ${e} param = %t, result count = ${s.result.length}`,t)}catch(r){if(s.err=r,this.log.error(`FAILED query sql = ${e} param = %t`,t,r),!i)throw r}return i&&i(s.err,s.result),s.result}executeBatch(e,t,i){let s,r={err:null,result:new Array};try{e.forEach(e=>{s=e;let i=this.execute(e.query,e.parameters);t&&t(i,e),r.result.push(i)})}catch(e){if(r.err=e,this.log.error("FAILED executeBatch, ",s,e),!i)throw e}return i&&i(r.err,r.result),r.result}async asynExecute(e,t){return s.promisify(this.execute).call(this,e,t)}async asynQuery(e,t){return s.promisify(this.query).call(this,e,t)}asyncExecuteBatch(e,t){return s.promisify(this.executeBatch).call(this,e,t)}}},function(e,t){e.exports=require("better-sqlite3")},function(e,t,i){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.BlockCache=class{constructor(e){this.cache=new Map,this.minHeight=-1,this.maxHeight=-1,this.maxCachedCount=e}isCached(e){return e>0&&e>=this.minHeight&&e<=this.maxHeight}get cachedHeightRange(){return{min:this.minHeight,max:this.maxHeight}}push(e){if(this.maxHeight>=0&&e.height!==this.maxHeight+1)throw new Error(`invalid block height, expected : ${this.maxHeight+1} actual : ${e.height}`);this.cache.set(e.height,e),this.maxHeight=e.height,this.minHeight=-1===this.minHeight?e.height:this.minHeight,this.cache.size>=this.maxCachedCount&&this.cache.delete(this.minHeight++)}get(e){return this.cache.get(e)}getById(e){for(const t of this.cache.values())if(t.id===e)return t}evitUntil(e){if(e>=this.maxHeight)return;let t=this.maxHeight;for(;t>e;)this.cache.delete(t),t--;this.cache.size>0?this.maxHeight=e:(this.minHeight=-1,this.maxHeight=-1)}}}]);