UNPKG

@browser-network/database

Version:

A type of distributed database built on top of the distributed browser-network

1 lines 480 kB
!function(f){"object"==typeof exports&&"undefined"!=typeof module?module.exports=f():"function"==typeof define&&define.amd?define([],f):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Db=f()}(function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);throw(f=new Error("Cannot find module '"+i+"'")).code="MODULE_NOT_FOUND",f}c=n[i]={exports:{}},e[i][0].call(c.exports,function(r){return o(e[i][1][r]||r)},c,c.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}({1:[function(require,module,exports){var factory;factory=function(require,exports){"use strict";exports.__esModule=!0,exports.LocalDB=void 0;var LocalDB=function(){function LocalDB(appId){var localStorageShim,_this=this;this.keyPrefix="db",this.getByKey=function(key){key=_this.localStorage.getItem(key);return key?JSON.parse(key):null},this.appId=appId,this.localStorage=globalThis.localStorage||(localStorageShim={setItem:function(key,val){localStorageShim[key]=val},getItem:function(key){return localStorageShim[key]},removeItem:function(key){delete localStorageShim[key]}})}return LocalDB.prototype.set=function(val,address){address=this.buildKey(address);this.localStorage.setItem(address,JSON.stringify(val))},LocalDB.prototype.get=function(address){address=this.buildKey(address);return this.getByKey(address)},LocalDB.prototype.getAll=function(){var _this=this;return Object.keys(this.localStorage).filter(function(key){return-1<key.indexOf(_this.buildKey(""))}).map(this.getByKey)},LocalDB.prototype.remove=function(address){address=this.buildKey(address);this.localStorage.removeItem(address)},LocalDB.prototype.clear=function(){var _this=this;this.getAll().forEach(function(wrapped){_this.remove(wrapped.id)})},LocalDB.prototype.buildKey=function(address){return"".concat(this.keyPrefix,"-").concat(this.appId,"-").concat(address)},LocalDB}();exports.LocalDB=LocalDB},"object"==typeof module&&"object"==typeof module.exports&&factory(0,exports)},{}],2:[function(require,module,exports){var factory,__createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&("get"in desc?m.__esModule:!desc.writable&&!desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){o[k2=void 0===k2?k:k2]=m[k]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=this&&this.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(null!=mod)for(var k in mod)"default"!==k&&Object.prototype.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P=P||Promise)(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){var value;result.done?resolve(result.value):((value=result.value)instanceof P?value:new P(function(resolve){resolve(value)})).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},__generator=this&&this.__generator||function(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){var op=[n,v];if(f)throw new TypeError("Generator is already executing.");for(;_=g&&op[g=0]?0:_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,(op=t?[2&op[0],t.value]:op)[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!(t=0<(t=_.trys).length&&t[t.length-1])&&(6===op[0]||2===op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3]))_.label=op[1];else if(6===op[0]&&_.label<t[1])_.label=t[1],t=op;else{if(!(t&&_.label<t[2])){t[2]&&_.ops.pop(),_.trys.pop();continue}_.label=t[2],_.ops.push(op)}}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}}},__rest=this&&this.__rest||function(s,e){var t={};for(p in s)Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0&&(t[p]=s[p]);if(null!=s&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,p=Object.getOwnPropertySymbols(s);i<p.length;i++)e.indexOf(p[i])<0&&Object.prototype.propertyIsEnumerable.call(s,p[i])&&(t[p[i]]=s[p[i]]);return t};factory=function(require,exports){"use strict";exports.__esModule=!0;var bnc=__importStar(require("@browser-network/crypto")),LocalDB_1=require("./LocalDB"),debug=(0,require("./util").debugFactory)("Db"),require=function(){function Db(_a){var secret=_a.secret,appId=_a.appId,_a=_a.network,_this=this;this._denyList={},this._allowList={},this._onChangeHandlers=[],this.getAll=function(){return _this.localDB.getAll()},this.clear=function(){_this.localDB.clear(),_this.runChangeHandlers()},this.deny=function(address){_this._denyList[address]||(_this._denyList[address]=!0,_this.localDB.remove(address))},this.undeny=function(address){delete _this._denyList[address]},this.allow=function(address){_this._allowList[address]||(_this._allowList[address]=!0)},this.unallow=function(address){delete _this._allowList[address],_this.localDB.remove(address)},this.onMessage=function(message){switch(message.type){case"state-offering":return debug(5,"received state-offering:",message),_this.onStateOffering(message.data,message.address);case"state-request":return debug(5,"received state-request:",message),_this.broadcastStateUpdateByStateId(message.data);case"state-update":return debug(5,"received state-update:",message),_this.onStateUpdate(message.data)}},this.broadcastStateOfferings=function(){for(var offerings={},_i=0,_a=_this.localDB.getAll();_i<_a.length;_i++){var state=_a[_i];offerings[state.id]=state.timestamp}_this.network.broadcast({type:"state-offering",appId:_this.appId,data:offerings})},this.runChangeHandlers=function(){_this._onChangeHandlers.forEach(function(handler){return handler()})},this.networkId=_a.networkId,this.appId=appId,this.localDB=new LocalDB_1.LocalDB(appId),this.address=_a.address,this.secret=secret,this.network=_a,this.network.on("message",function(message){message.appId===_this.appId&&_this.onMessage(message)}),this.publicKey=bnc.derivePubKey(secret),setInterval(this.broadcastStateOfferings,5e3)}return Db.prototype.set=function(state){return __awaiter(this,void 0,void 0,function(){var data;return __generator(this,function(_a){switch(_a.label){case 0:return[4,function(state,address,pub,priv){return __awaiter(void 0,void 0,void 0,function(){var wrapp,signature;return __generator(this,function(_a){switch(_a.label){case 0:return wrapp={id:address,timestamp:Date.now(),state:state,publicKey:pub},[4,bnc.sign(priv,wrapp)];case 1:return signature=_a.sent(),[2,Object.assign(wrapp,{signature:signature})]}})})}(state,this.address,this.publicKey,this.secret)];case 1:return data=_a.sent(),this.setLocal(data),this.broadcastStateUpdate(data),[2]}})})},Db.prototype.get=function(address){return this.localDB.get(address)},Db.prototype.onChange=function(handler){this._onChangeHandlers.push(handler)},Db.prototype.removeChangeHandlers=function(){this._onChangeHandlers=[]},Db.prototype.removeChangeHandler=function(func){var _this=this;Array.from(this._onChangeHandlers).forEach(function(handler,i){handler===func&&_this._onChangeHandlers.splice(i,1)})},Db.prototype.onStateOffering=function(offerings,sender){function requestState(address){_this.network.broadcast({type:"state-request",appId:_this.appId,destination:sender,data:address})}var remoteId,_this=this;for(remoteId in offerings){var remoteStateTimestamp=offerings[remoteId],localState=this.localDB.get(remoteId);this.isForbidden(remoteId)||(!localState||localState.timestamp<remoteStateTimestamp)&&requestState(remoteId)}},Db.prototype.onStateUpdate=function(update){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return this.isForbidden(update.publicKey)?[2,debug(5,"state update from pubKey not allowed:",update.publicKey)]:(debug(5,"received update from another node:",update),[4,this.verify(update)]);case 1:return _a.sent()&&this.setLocal(update),[2]}})})},Db.prototype.isForbidden=function(address){return this._denyList[address]||0<Object.keys(this._allowList).length&&!this._allowList[address]},Db.prototype.broadcastStateUpdate=function(data){this.network.broadcast({type:"state-update",appId:this.appId,data:data})},Db.prototype.broadcastStateUpdateByStateId=function(stateId){stateId=this.localDB.get(stateId);stateId&&this.broadcastStateUpdate(stateId)},Db.prototype.setLocal=function(wrapped){this.localDB.set(wrapped,wrapped.id),this.runChangeHandlers()},Db.prototype.verify=function(update){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(_a){switch(_a.label){case 0:return this.isNew(update)?[4,function(update){var signature=update.signature,wrapp=__rest(update,["signature"]);return bnc.verifySignature(wrapp,signature,update.publicKey)}(update)]:[2,!1];case 1:return _a.sent()?[2,!0]:(debug(1,"update does not pass verification! update, local version:",update,this.localDB.get(update.id)),[2,!1])}})})},Db.prototype.isNew=function(update){var local=this.get(update.id);return!local||update.timestamp>local.timestamp},Db}();exports.default=require},"object"==typeof module&&"object"==typeof module.exports&&factory(require,exports)},{"./LocalDB":1,"./util":3,"@browser-network/crypto":4}],3:[function(require,module,exports){var factory,__spreadArray=this&&this.__spreadArray||function(to,from,pack){if(pack||2===arguments.length)for(var ar,i=0,l=from.length;i<l;i++)!ar&&i in from||((ar=ar||Array.prototype.slice.call(from,0,i))[i]=from[i]);return to.concat(ar||Array.prototype.slice.call(from))};factory=function(require,exports){"use strict";exports.__esModule=!0,exports.exhaustive=exports.isPromise=exports.debugFactory=void 0;exports.debugFactory=function(appName){return function(logLevel){for(var args=[],_i=1;_i<arguments.length;_i++)args[_i-1]=arguments[_i];globalThis.DEBUG>=logLevel&&console.log.apply(console,__spreadArray(["[".concat(logLevel,"] ").concat(appName,": ")],args,!1))}},exports.isPromise=function(promise){return promise.hasOwnProperty("then")};exports.exhaustive=function(arg){throw new Error("can not have gotten here")}},"object"==typeof module&&"object"==typeof module.exports&&factory(0,exports)},{}],4:[function(require,module,exports){!function(Buffer){!function(){var factory,__createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){void 0===k2&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);desc&&("get"in desc?m.__esModule:!desc.writable&&!desc.configurable)||(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){o[k2=void 0===k2?k:k2]=m[k]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:!0,value:v})}:function(o,v){o.default=v}),__importStar=this&&this.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(null!=mod)for(var k in mod)"default"!==k&&Object.prototype.hasOwnProperty.call(mod,k)&&__createBinding(result,mod,k);return __setModuleDefault(result,mod),result},__awaiter=this&&this.__awaiter||function(thisArg,_arguments,P,generator){return new(P=P||Promise)(function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){var value;result.done?resolve(result.value):((value=result.value)instanceof P?value:new P(function(resolve){resolve(value)})).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())})},__generator=this&&this.__generator||function(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g={next:verb(0),throw:verb(1),return:verb(2)};return"function"==typeof Symbol&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){var op=[n,v];if(f)throw new TypeError("Generator is already executing.");for(;_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,(op=t?[2&op[0],t.value]:op)[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!(t=0<(t=_.trys).length&&t[t.length-1])&&(6===op[0]||2===op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3]))_.label=op[1];else if(6===op[0]&&_.label<t[1])_.label=t[1],t=op;else{if(!(t&&_.label<t[2])){t[2]&&_.ops.pop(),_.trys.pop();continue}_.label=t[2],_.ops.push(op)}}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}}};factory=function(require,exports){"use strict";exports.__esModule=!0,exports.generateSecret=exports.derivePubKey=exports.verifySignature=exports.sign=exports.hash=exports.stob=exports.btos=void 0;var crypto_1=require("crypto"),eccrypto=__importStar(require("eccrypto"));exports.btos=function(buffer){return buffer.toString("hex")},exports.stob=function(str){return Buffer.from(str,"hex")},exports.hash=function(data){return(0,crypto_1.createHash)("sha256").update(JSON.stringify(data)).digest()},exports.sign=function(secret,obj){return __awaiter(void 0,void 0,void 0,function(){var stringState,keyBuff;return __generator(this,function(_a){switch(_a.label){case 0:return stringState=JSON.stringify(obj),stringState=(0,exports.hash)(stringState),keyBuff=(0,exports.stob)(secret),[4,eccrypto.sign(keyBuff,stringState)];case 1:return keyBuff=_a.sent(),[2,(0,exports.btos)(keyBuff)]}})})},exports.verifySignature=function(object,signature,publicKey){return __awaiter(void 0,void 0,void 0,function(){var stringObj,pubBuf,sigBuf;return __generator(this,function(_a){switch(_a.label){case 0:stringObj=JSON.stringify(object),stringObj=(0,exports.hash)(stringObj),pubBuf=(0,exports.stob)(publicKey),sigBuf=(0,exports.stob)(signature),_a.label=1;case 1:return _a.trys.push([1,3,,4]),[4,eccrypto.verify(pubBuf,stringObj,sigBuf)];case 2:return _a.sent(),[2,!0];case 3:return _a.sent(),[2,!1];case 4:return[2]}})})},exports.derivePubKey=function(secret){return(0,exports.btos)(eccrypto.getPublicCompressed((0,exports.stob)(secret)))};exports.generateSecret=function(){var privBuf=eccrypto.generatePrivate();return(0,exports.btos)(privBuf)}},"object"==typeof module&&"object"==typeof module.exports&&factory(require,exports)}.call(this)}.call(this,require("buffer").Buffer)},{buffer:67,crypto:75,eccrypto:87}],5:[function(require,module,exports){"use strict";exports.bignum=require("bn.js"),exports.define=require("./asn1/api").define,exports.base=require("./asn1/base"),exports.constants=require("./asn1/constants"),exports.decoders=require("./asn1/decoders"),exports.encoders=require("./asn1/encoders")},{"./asn1/api":6,"./asn1/base":8,"./asn1/constants":12,"./asn1/decoders":14,"./asn1/encoders":17,"bn.js":19}],6:[function(require,module,exports){"use strict";const encoders=require("./encoders"),decoders=require("./decoders"),inherits=require("inherits");function Entity(name,body){this.name=name,this.body=body,this.decoders={},this.encoders={}}exports.define=function(name,body){return new Entity(name,body)},Entity.prototype._createNamed=function(Base){const name=this.name;function Generated(entity){this._initNamed(entity,name)}return inherits(Generated,Base),Generated.prototype._initNamed=function(entity,name){Base.call(this,entity,name)},new Generated(this)},Entity.prototype._getDecoder=function(enc){return this.decoders.hasOwnProperty(enc=enc||"der")||(this.decoders[enc]=this._createNamed(decoders[enc])),this.decoders[enc]},Entity.prototype.decode=function(data,enc,options){return this._getDecoder(enc).decode(data,options)},Entity.prototype._getEncoder=function(enc){return this.encoders.hasOwnProperty(enc=enc||"der")||(this.encoders[enc]=this._createNamed(encoders[enc])),this.encoders[enc]},Entity.prototype.encode=function(data,enc,reporter){return this._getEncoder(enc).encode(data,reporter)}},{"./decoders":14,"./encoders":17,inherits:137}],7:[function(require,module,exports){"use strict";var inherits=require("inherits");const Reporter=require("../base/reporter").Reporter,Buffer=require("safer-buffer").Buffer;function DecoderBuffer(base,options){Reporter.call(this,options),Buffer.isBuffer(base)?(this.base=base,this.offset=0,this.length=base.length):this.error("Input not Buffer")}function EncoderBuffer(value,reporter){if(Array.isArray(value))this.length=0,this.value=value.map(function(item){return EncoderBuffer.isEncoderBuffer(item)||(item=new EncoderBuffer(item,reporter)),this.length+=item.length,item},this);else if("number"==typeof value){if(!(0<=value&&value<=255))return reporter.error("non-byte EncoderBuffer value");this.value=value,this.length=1}else if("string"==typeof value)this.value=value,this.length=Buffer.byteLength(value);else{if(!Buffer.isBuffer(value))return reporter.error("Unsupported type: "+typeof value);this.value=value,this.length=value.length}}inherits(DecoderBuffer,Reporter),(exports.DecoderBuffer=DecoderBuffer).isDecoderBuffer=function(data){return data instanceof DecoderBuffer||"object"==typeof data&&Buffer.isBuffer(data.base)&&"DecoderBuffer"===data.constructor.name&&"number"==typeof data.offset&&"number"==typeof data.length&&"function"==typeof data.save&&"function"==typeof data.restore&&"function"==typeof data.isEmpty&&"function"==typeof data.readUInt8&&"function"==typeof data.skip&&"function"==typeof data.raw},DecoderBuffer.prototype.save=function(){return{offset:this.offset,reporter:Reporter.prototype.save.call(this)}},DecoderBuffer.prototype.restore=function(save){var res=new DecoderBuffer(this.base);return res.offset=save.offset,res.length=this.offset,this.offset=save.offset,Reporter.prototype.restore.call(this,save.reporter),res},DecoderBuffer.prototype.isEmpty=function(){return this.offset===this.length},DecoderBuffer.prototype.readUInt8=function(fail){return this.offset+1<=this.length?this.base.readUInt8(this.offset++,!0):this.error(fail||"DecoderBuffer overrun")},DecoderBuffer.prototype.skip=function(bytes,fail){var res;return this.offset+bytes<=this.length?((res=new DecoderBuffer(this.base))._reporterState=this._reporterState,res.offset=this.offset,res.length=this.offset+bytes,this.offset+=bytes,res):this.error(fail||"DecoderBuffer overrun")},DecoderBuffer.prototype.raw=function(save){return this.base.slice((save||this).offset,this.length)},(exports.EncoderBuffer=EncoderBuffer).isEncoderBuffer=function(data){return data instanceof EncoderBuffer||"object"==typeof data&&"EncoderBuffer"===data.constructor.name&&"number"==typeof data.length&&"function"==typeof data.join},EncoderBuffer.prototype.join=function(out,offset){return out=out||Buffer.alloc(this.length),offset=offset||0,0!==this.length&&(Array.isArray(this.value)?this.value.forEach(function(item){item.join(out,offset),offset+=item.length}):("number"==typeof this.value?out[offset]=this.value:"string"==typeof this.value?out.write(this.value,offset):Buffer.isBuffer(this.value)&&this.value.copy(out,offset),offset+=this.length)),out}},{"../base/reporter":10,inherits:137,"safer-buffer":166}],8:[function(require,module,exports){"use strict";exports.Reporter=require("./reporter").Reporter,exports.DecoderBuffer=require("./buffer").DecoderBuffer,exports.EncoderBuffer=require("./buffer").EncoderBuffer,exports.Node=require("./node")},{"./buffer":7,"./node":9,"./reporter":10}],9:[function(require,module,exports){"use strict";const Reporter=require("../base/reporter").Reporter,EncoderBuffer=require("../base/buffer").EncoderBuffer,DecoderBuffer=require("../base/buffer").DecoderBuffer,assert=require("minimalistic-assert");require=["seq","seqof","set","setof","objid","bool","gentime","utctime","null_","enum","int","objDesc","bitstr","bmpstr","charstr","genstr","graphstr","ia5str","iso646str","numstr","octstr","printstr","t61str","unistr","utf8str","videostr"];const methods=["key","obj","use","optional","explicit","implicit","def","choice","any","contains"].concat(require);function Node(enc,parent,name){var state={};(this._baseState=state).name=name,state.enc=enc,state.parent=parent||null,state.children=null,state.tag=null,state.args=null,state.reverseArgs=null,state.choice=null,state.optional=!1,state.any=!1,state.obj=!1,state.use=null,state.useDecoder=null,state.key=null,state.default=null,state.explicit=null,state.implicit=null,state.contains=null,state.parent||(state.children=[],this._wrap())}module.exports=Node;const stateProps=["enc","parent","children","tag","args","reverseArgs","choice","optional","any","obj","use","alteredUse","key","default","explicit","implicit","contains"];Node.prototype.clone=function(){const state=this._baseState,cstate={};stateProps.forEach(function(prop){cstate[prop]=state[prop]});var res=new this.constructor(cstate.parent);return res._baseState=cstate,res},Node.prototype._wrap=function(){const state=this._baseState;methods.forEach(function(method){this[method]=function(){var clone=new this.constructor(this);return state.children.push(clone),clone[method].apply(clone,arguments)}},this)},Node.prototype._init=function(body){var state=this._baseState;assert(null===state.parent),body.call(this),state.children=state.children.filter(function(child){return child._baseState.parent===this},this),assert.equal(state.children.length,1,"Root node can have only one child")},Node.prototype._useArgs=function(args){var state=this._baseState,children=args.filter(function(arg){return arg instanceof this.constructor},this);args=args.filter(function(arg){return!(arg instanceof this.constructor)},this),0!==children.length&&(assert(null===state.children),(state.children=children).forEach(function(child){child._baseState.parent=this},this)),0!==args.length&&(assert(null===state.args),state.args=args,state.reverseArgs=args.map(function(arg){if("object"!=typeof arg||arg.constructor!==Object)return arg;const res={};return Object.keys(arg).forEach(function(key){key==(0|key)&&(key|=0);var value=arg[key];res[value]=key}),res}))},["_peekTag","_decodeTag","_use","_decodeStr","_decodeObjid","_decodeTime","_decodeNull","_decodeInt","_decodeBool","_decodeList","_encodeComposite","_encodeStr","_encodeObjid","_encodeTime","_encodeNull","_encodeInt","_encodeBool"].forEach(function(method){Node.prototype[method]=function(){var state=this._baseState;throw new Error(method+" not implemented for encoding: "+state.enc)}}),require.forEach(function(tag){Node.prototype[tag]=function(){var state=this._baseState,args=Array.prototype.slice.call(arguments);return assert(null===state.tag),state.tag=tag,this._useArgs(args),this}}),Node.prototype.use=function(item){assert(item);var state=this._baseState;return assert(null===state.use),state.use=item,this},Node.prototype.optional=function(){return this._baseState.optional=!0,this},Node.prototype.def=function(val){var state=this._baseState;return assert(null===state.default),state.default=val,state.optional=!0,this},Node.prototype.explicit=function(num){var state=this._baseState;return assert(null===state.explicit&&null===state.implicit),state.explicit=num,this},Node.prototype.implicit=function(num){var state=this._baseState;return assert(null===state.explicit&&null===state.implicit),state.implicit=num,this},Node.prototype.obj=function(){var state=this._baseState,args=Array.prototype.slice.call(arguments);return state.obj=!0,0!==args.length&&this._useArgs(args),this},Node.prototype.key=function(newKey){var state=this._baseState;return assert(null===state.key),state.key=newKey,this},Node.prototype.any=function(){return this._baseState.any=!0,this},Node.prototype.choice=function(obj){var state=this._baseState;return assert(null===state.choice),state.choice=obj,this._useArgs(Object.keys(obj).map(function(key){return obj[key]})),this},Node.prototype.contains=function(item){var state=this._baseState;return assert(null===state.use),state.contains=item,this},Node.prototype._decode=function(input,options){var state=this._baseState;if(null===state.parent)return input.wrapResult(state.children[0]._decode(input,options));let result=state.default,present=!0,prevKey=null;if(null!==state.key&&(prevKey=input.enterKey(state.key)),state.optional){let tag=null;if(null!==state.explicit?tag=state.explicit:null!==state.implicit?tag=state.implicit:null!==state.tag&&(tag=state.tag),null!==tag||state.any){if(present=this._peekTag(input,tag,state.any),input.isError(present))return present}else{var save=input.save();try{null===state.choice?this._decodeGeneric(state.tag,input,options):this._decodeChoice(input,options),present=!0}catch(e){present=!1}input.restore(save)}}let prevObj;if(state.obj&&present&&(prevObj=input.enterObject()),present){if(null!==state.explicit){save=this._decodeTag(input,state.explicit);if(input.isError(save))return save;input=save}save=input.offset;if(null===state.use&&null===state.choice){let save;state.any&&(save=input.save());var body=this._decodeTag(input,null!==state.implicit?state.implicit:state.tag,state.any);if(input.isError(body))return body;state.any?result=input.raw(save):input=body}if(options&&options.track&&null!==state.tag&&options.track(input.path(),save,input.length,"tagged"),options&&options.track&&null!==state.tag&&options.track(input.path(),input.offset,input.length,"content"),state.any||(result=null===state.choice?this._decodeGeneric(state.tag,input,options):this._decodeChoice(input,options)),input.isError(result))return result;state.any||null!==state.choice||null===state.children||state.children.forEach(function(child){child._decode(input,options)}),!state.contains||"octstr"!==state.tag&&"bitstr"!==state.tag||(body=new DecoderBuffer(result),result=this._getUse(state.contains,input._reporterState.obj)._decode(body,options))}return state.obj&&present&&(result=input.leaveObject(prevObj)),null===state.key||null===result&&!0!==present?null!==prevKey&&input.exitKey(prevKey):input.leaveKey(prevKey,state.key,result),result},Node.prototype._decodeGeneric=function(tag,input,options){var state=this._baseState;return"seq"===tag||"set"===tag?null:"seqof"===tag||"setof"===tag?this._decodeList(input,tag,state.args[0],options):/str$/.test(tag)?this._decodeStr(input,tag,options):"objid"===tag&&state.args?this._decodeObjid(input,state.args[0],state.args[1],options):"objid"===tag?this._decodeObjid(input,null,null,options):"gentime"===tag||"utctime"===tag?this._decodeTime(input,tag,options):"null_"===tag?this._decodeNull(input,options):"bool"===tag?this._decodeBool(input,options):"objDesc"===tag?this._decodeStr(input,tag,options):"int"===tag||"enum"===tag?this._decodeInt(input,state.args&&state.args[0],options):null!==state.use?this._getUse(state.use,input._reporterState.obj)._decode(input,options):input.error("unknown tag: "+tag)},Node.prototype._getUse=function(entity,obj){var state=this._baseState;return state.useDecoder=this._use(entity,obj),assert(null===state.useDecoder._baseState.parent),state.useDecoder=state.useDecoder._baseState.children[0],state.implicit!==state.useDecoder._baseState.implicit&&(state.useDecoder=state.useDecoder.clone(),state.useDecoder._baseState.implicit=state.implicit),state.useDecoder},Node.prototype._decodeChoice=function(input,options){const state=this._baseState;let result=null,match=!1;return Object.keys(state.choice).some(function(key){var save=input.save(),node=state.choice[key];try{var value=node._decode(input,options);if(input.isError(value))return!1;result={type:key,value:value},match=!0}catch(e){return input.restore(save),!1}return!0},this),match?result:input.error("Choice not matched")},Node.prototype._createEncoderBuffer=function(data){return new EncoderBuffer(data,this.reporter)},Node.prototype._encode=function(data,reporter,parent){var state=this._baseState;if(null===state.default||state.default!==data){state=this._encodeValue(data,reporter,parent);if(void 0!==state&&!this._skipDefault(state,reporter,parent))return state}},Node.prototype._encodeValue=function(data,reporter,parent){var state=this._baseState;if(null===state.parent)return state.children[0]._encode(data,reporter||new Reporter);let result=null;if(this.reporter=reporter,state.optional&&void 0===data){if(null===state.default)return;data=state.default}let content=null,primitive=!1;if(state.any)result=this._createEncoderBuffer(data);else if(state.choice)result=this._encodeChoice(data,reporter);else if(state.contains)content=this._getUse(state.contains,parent)._encode(data,reporter),primitive=!0;else if(state.children)content=state.children.map(function(child){var prevKey;return"null_"===child._baseState.tag?child._encode(null,reporter,data):null===child._baseState.key?reporter.error("Child should have a key"):(prevKey=reporter.enterKey(child._baseState.key),"object"!=typeof data?reporter.error("Child expected, but input is not object"):(child=child._encode(data[child._baseState.key],reporter,data),reporter.leaveKey(prevKey),child))},this).filter(function(child){return child}),content=this._createEncoderBuffer(content);else if("seqof"===state.tag||"setof"===state.tag){if(!state.args||1!==state.args.length)return reporter.error("Too many args for : "+state.tag);if(!Array.isArray(data))return reporter.error("seqof/setof, but data is not Array");var child=this.clone();child._baseState.implicit=null,content=this._createEncoderBuffer(data.map(function(item){var state=this._baseState;return this._getUse(state.args[0],data)._encode(item,reporter)},child))}else null!==state.use?result=this._getUse(state.use,parent)._encode(data,reporter):(content=this._encodePrimitive(state.tag,data),primitive=!0);return state.any||null!==state.choice||(child=null!==state.implicit?state.implicit:state.tag,parent=null===state.implicit?"universal":"context",null===child?null===state.use&&reporter.error("Tag could be omitted only for .use()"):null===state.use&&(result=this._encodeComposite(child,primitive,parent,content))),result=null!==state.explicit?this._encodeComposite(state.explicit,!1,"context",result):result},Node.prototype._encodeChoice=function(data,reporter){var state=this._baseState,node=state.choice[data.type];return node||assert(!1,data.type+" not found in "+JSON.stringify(Object.keys(state.choice))),node._encode(data.value,reporter)},Node.prototype._encodePrimitive=function(tag,data){var state=this._baseState;if(/str$/.test(tag))return this._encodeStr(data,tag);if("objid"===tag&&state.args)return this._encodeObjid(data,state.reverseArgs[0],state.args[1]);if("objid"===tag)return this._encodeObjid(data,null,null);if("gentime"===tag||"utctime"===tag)return this._encodeTime(data,tag);if("null_"===tag)return this._encodeNull();if("int"===tag||"enum"===tag)return this._encodeInt(data,state.args&&state.reverseArgs[0]);if("bool"===tag)return this._encodeBool(data);if("objDesc"===tag)return this._encodeStr(data,tag);throw new Error("Unsupported tag: "+tag)},Node.prototype._isNumstr=function(str){return/^[0-9 ]*$/.test(str)},Node.prototype._isPrintstr=function(str){return/^[A-Za-z0-9 '()+,-./:=?]*$/.test(str)}},{"../base/buffer":7,"../base/reporter":10,"minimalistic-assert":141}],10:[function(require,module,exports){"use strict";require=require("inherits");function Reporter(options){this._reporterState={obj:null,path:[],options:options||{},errors:[]}}function ReporterError(path,msg){this.path=path,this.rethrow(msg)}(exports.Reporter=Reporter).prototype.isError=function(obj){return obj instanceof ReporterError},Reporter.prototype.save=function(){var state=this._reporterState;return{obj:state.obj,pathLen:state.path.length}},Reporter.prototype.restore=function(data){var state=this._reporterState;state.obj=data.obj,state.path=state.path.slice(0,data.pathLen)},Reporter.prototype.enterKey=function(key){return this._reporterState.path.push(key)},Reporter.prototype.exitKey=function(index){var state=this._reporterState;state.path=state.path.slice(0,index-1)},Reporter.prototype.leaveKey=function(index,key,value){var state=this._reporterState;this.exitKey(index),null!==state.obj&&(state.obj[key]=value)},Reporter.prototype.path=function(){return this._reporterState.path.join("/")},Reporter.prototype.enterObject=function(){var state=this._reporterState,prev=state.obj;return state.obj={},prev},Reporter.prototype.leaveObject=function(prev){var state=this._reporterState,now=state.obj;return state.obj=prev,now},Reporter.prototype.error=function(msg){let err;var state=this._reporterState,inherited=msg instanceof ReporterError;if(err=inherited?msg:new ReporterError(state.path.map(function(elem){return"["+JSON.stringify(elem)+"]"}).join(""),msg.message||msg,msg.stack),state.options.partial)return inherited||state.errors.push(err),err;throw err},Reporter.prototype.wrapResult=function(result){var state=this._reporterState;return state.options.partial?{result:this.isError(result)?null:result,errors:state.errors}:result},require(ReporterError,Error),ReporterError.prototype.rethrow=function(msg){if(this.message=msg+" at: "+(this.path||"(shallow)"),Error.captureStackTrace&&Error.captureStackTrace(this,ReporterError),!this.stack)try{throw new Error(this.message)}catch(e){this.stack=e.stack}return this}},{inherits:137}],11:[function(require,module,exports){"use strict";function reverse(map){const res={};return Object.keys(map).forEach(function(key){(0|key)==key&&(key|=0);var value=map[key];res[value]=key}),res}exports.tagClass={0:"universal",1:"application",2:"context",3:"private"},exports.tagClassByName=reverse(exports.tagClass),exports.tag={0:"end",1:"bool",2:"int",3:"bitstr",4:"octstr",5:"null_",6:"objid",7:"objDesc",8:"external",9:"real",10:"enum",11:"embed",12:"utf8str",13:"relativeOid",16:"seq",17:"set",18:"numstr",19:"printstr",20:"t61str",21:"videostr",22:"ia5str",23:"utctime",24:"gentime",25:"graphstr",26:"iso646str",27:"genstr",28:"unistr",29:"charstr",30:"bmpstr"},exports.tagByName=reverse(exports.tag)},{}],12:[function(require,module,exports){"use strict";exports._reverse=function(map){const res={};return Object.keys(map).forEach(function(key){(0|key)==key&&(key|=0);var value=map[key];res[value]=key}),res},exports.der=require("./der")},{"./der":11}],13:[function(require,module,exports){"use strict";var inherits=require("inherits");const bignum=require("bn.js"),DecoderBuffer=require("../base/buffer").DecoderBuffer,Node=require("../base/node"),der=require("../constants/der");function DERDecoder(entity){this.enc="der",this.name=entity.name,this.entity=entity,this.tree=new DERNode,this.tree._init(entity.body)}function DERNode(parent){Node.call(this,"der",parent)}function derDecodeTag(buf,fail){let tag=buf.readUInt8(fail);if(buf.isError(tag))return tag;var cls=der.tagClass[tag>>6],primitive=0==(32&tag);if(31==(31&tag)){let oct=tag;for(tag=0;128==(128&oct);){if(oct=buf.readUInt8(fail),buf.isError(oct))return oct;tag=(tag<<=7)|127&oct}}else tag&=31;var tagStr=der.tag[tag];return{cls:cls,primitive:primitive,tag:tag,tagStr:tagStr}}function derDecodeLen(buf,primitive,fail){let len=buf.readUInt8(fail);if(!buf.isError(len)){if(!primitive&&128===len)return null;if(0!=(128&len)){var num=127&len;if(4<num)return buf.error("length octect is too long");for(let i=len=0;i<num;i++){len<<=8;var j=buf.readUInt8(fail);if(buf.isError(j))return j;len|=j}}}return len}(module.exports=DERDecoder).prototype.decode=function(data,options){return DecoderBuffer.isDecoderBuffer(data)||(data=new DecoderBuffer(data,options)),this.tree._decode(data,options)},inherits(DERNode,Node),DERNode.prototype._peekTag=function(buffer,tag,any){var state,decodedTag;return!buffer.isEmpty()&&(state=buffer.save(),decodedTag=derDecodeTag(buffer,'Failed to peek tag: "'+tag+'"'),buffer.isError(decodedTag)?decodedTag:(buffer.restore(state),decodedTag.tag===tag||decodedTag.tagStr===tag||decodedTag.tagStr+"of"===tag||any))},DERNode.prototype._decodeTag=function(buffer,tag,any){var decodedTag=derDecodeTag(buffer,'Failed to decode tag of "'+tag+'"');if(buffer.isError(decodedTag))return decodedTag;var len=derDecodeLen(buffer,decodedTag.primitive,'Failed to get length of "'+tag+'"');if(buffer.isError(len))return len;if(!any&&decodedTag.tag!==tag&&decodedTag.tagStr!==tag&&decodedTag.tagStr+"of"!==tag)return buffer.error('Failed to match tag: "'+tag+'"');if(!decodedTag.primitive&&null===len){any=buffer.save(),decodedTag=this._skipUntilEnd(buffer,'Failed to skip indefinite length body: "'+this.tag+'"');if(buffer.isError(decodedTag))return decodedTag;len=buffer.offset-any.offset,buffer.restore(any)}return buffer.skip(len,'Failed to match body of: "'+tag+'"')},DERNode.prototype._skipUntilEnd=function(buffer,fail){for(;;){var tag=derDecodeTag(buffer,fail);if(buffer.isError(tag))return tag;var len=derDecodeLen(buffer,tag.primitive,fail);if(buffer.isError(len))return len;let res;if(res=tag.primitive||null!==len?buffer.skip(len):this._skipUntilEnd(buffer,fail),buffer.isError(res))return res;if("end"===tag.tagStr)break}},DERNode.prototype._decodeList=function(buffer,tag,decoder,options){for(var result=[];!buffer.isEmpty();){var possibleEnd=this._peekTag(buffer,"end");if(buffer.isError(possibleEnd))return possibleEnd;var res=decoder.decode(buffer,"der",options);if(buffer.isError(res)&&possibleEnd)break;result.push(res)}return result},DERNode.prototype._decodeStr=function(buffer,tag){var unused;if("bitstr"===tag)return unused=buffer.readUInt8(),buffer.isError(unused)?unused:{unused:unused,data:buffer.raw()};if("bmpstr"!==tag)return"numstr"===tag?(unused=buffer.raw().toString("ascii"),this._isNumstr(unused)?unused:buffer.error("Decoding of string type: numstr unsupported characters")):"octstr"===tag||"objDesc"===tag?buffer.raw():"printstr"===tag?(unused=buffer.raw().toString("ascii"),this._isPrintstr(unused)?unused:buffer.error("Decoding of string type: printstr unsupported characters")):/str$/.test(tag)?buffer.raw().toString():buffer.error("Decoding of string type: "+tag+" unsupported");{var raw=buffer.raw();if(raw.length%2==1)return buffer.error("Decoding of string type: bmpstr length mismatch");let str="";for(let i=0;i<raw.length/2;i++)str+=String.fromCharCode(raw.readUInt16BE(2*i));return str}},DERNode.prototype._decodeObjid=function(buffer,values,relative){let result;var identifiers=[];let ident=0,subident=0;for(;!buffer.isEmpty();)subident=buffer.readUInt8(),ident=(ident<<=7)|127&subident,0==(128&subident)&&(identifiers.push(ident),ident=0);if(128&subident&&identifiers.push(ident),result=relative?identifiers:[identifiers[0]/40|0,identifiers[0]%40].concat(identifiers.slice(1)),values){let tmp=values[result.join(" ")];void 0!==(tmp=void 0===tmp?values[result.join(".")]:tmp)&&(result=tmp)}return result},DERNode.prototype._decodeTime=function(buffer,tag){var str=buffer.raw().toString();let year,mon,day,hour,min,sec;if("gentime"===tag)year=0|str.slice(0,4),mon=0|str.slice(4,6),day=0|str.slice(6,8),hour=0|str.slice(8,10),min=0|str.slice(10,12),sec=0|str.slice(12,14);else{if("utctime"!==tag)return buffer.error("Decoding "+tag+" time is not supported yet");year=0|str.slice(0,2),mon=0|str.slice(2,4),day=0|str.slice(4,6),hour=0|str.slice(6,8),min=0|str.slice(8,10),sec=0|str.slice(10,12),year=year<70?2e3+year:1900+year}return Date.UTC(year,mon-1,day,hour,min,sec,0)},DERNode.prototype._decodeNull=function(){return null},DERNode.prototype._decodeBool=function(buffer){var res=buffer.readUInt8();return buffer.isError(res)?res:0!==res},DERNode.prototype._decodeInt=function(buffer,values){buffer=buffer.raw();let res=new bignum(buffer);return res=values?values[res.toString(10)]||res:res},DERNode.prototype._use=function(entity,obj){return(entity="function"==typeof entity?entity(obj):entity)._getDecoder("der").tree}},{"../base/buffer":7,"../base/node":9,"../constants/der":11,"bn.js":19,inherits:137}],14:[function(require,module,exports){"use strict";exports.der=require("./der"),exports.pem=require("./pem")},{"./der":13,"./pem":15}],15:[function(require,module,exports){"use strict";var inherits=require("inherits");const Buffer=require("safer-buffer").Buffer,DERDecoder=require("./der");function PEMDecoder(entity){DERDecoder.call(this,entity),this.enc="pem"}inherits(PEMDecoder,DERDecoder),(module.exports=PEMDecoder).prototype.decode=function(data,options){var lines=data.toString().split(/[\r\n]+/g),label=options.label.toUpperCase(),re=/^-----(BEGIN|END) ([^-]+)-----$/;let start=-1,end=-1;for(let i=0;i<lines.length;i++){var match=lines[i].match(re);if(null!==match&&match[2]===label){if(-1!==start){if("END"!==match[1])break;end=i;break}if("BEGIN"!==match[1])break;start=i}}if(-1===start||-1===end)throw new Error("PEM section not found for: "+label);data=lines.slice(start+1,end).join(""),data.replace(/[^a-z0-9+/=]+/gi,""),data=Buffer.from(data,"base64");return DERDecoder.prototype.decode.call(this,data,options)}},{"./der":13,inherits:137,"safer-buffer":166}],16:[function(require,module,exports){"use strict";var inherits=require("inherits");const Buffer=require("safer-buffer").Buffer,Node=require("../base/node"),der=require("../constants/der");function DEREncoder(entity){this.enc="der",this.name=entity.name,this.entity=entity,this.tree=new DERNode,this.tree._init(entity.body)}function DERNode(parent){Node.call(this,"der",parent)}function two(num){return num<10?"0"+num:num}(module.exports=DEREncoder).prototype.encode=function(data,reporter){return this.tree._encode(data,reporter).join()},inherits(DERNode,Node),DERNode.prototype._encodeComposite=function(tag,primitive,cls,content){tag=function(tag,primitive,cls,reporter){let res;"seqof"===tag?tag="seq":"setof"===tag&&(tag="set");if(der.tagByName.hasOwnProperty(tag))res=der.tagByName[tag];else{if("number"!=typeof tag||(0|tag)!==tag)return reporter.error("Unknown tag: "+tag);res=tag}if(31<=res)return reporter.error("Multi-octet tag encoding unsupported");primitive||(res|=32);return res|=der.tagClassByName[cls||"universal"]<<6}(tag,primitive,cls,this.reporter);if(content.length<128){const header=Buffer.alloc(2);return header[0]=tag,header[1]=content.length,this._createEncoderBuffer([header,content])}let lenOctets=1;for(let i=content.length;256<=i;i>>=8)lenOctets++;const header=Buffer.alloc(2+lenOctets);header[0]=tag,header[1]=128|lenOctets;for(let i=1+lenOctets,j=content.length;0<j;i--,j>>=8)header[i]=255&j;return this._createEncoderBuffer([header,content])},DERNode.prototype._encodeStr=function(str,tag){if("bitstr"===tag)return this._createEncoderBuffer([0|str.unused,str.data]);if("bmpstr"!==tag)return"numstr"===tag?this._isNumstr(str)?this._createEncoderBuffer(str):this.reporter.error("Encoding of string type: numstr supports only digits and space"):"printstr"===tag?this._isPrintstr(str)?this._createEncoderBuffer(str):this.reporter.error("Encoding of string type: printstr supports only latin upper and lower case letters, digits, space, apostrophe, left and rigth parenthesis, plus sign, comma, hyphen, dot, slash, colon, equal sign, question mark"):/str$/.test(tag)||"objDesc"===tag?this._createEncoderBuffer(str):this.reporter.error("Encoding of string type: "+tag+" unsupported");var buf=Buffer.alloc(2*str.length);for(let i=0;i<str.length;i++)buf.writeUInt16BE(str.charCodeAt(i),2*i);return this._createEncoderBuffer(buf)},DERNode.prototype._encodeObjid=function(id,values,relative){if("string"==typeof id){if(!values)return this.reporter.error("string objid given, but no values map found");if(!values.hasOwnProperty(id))return this.reporter.error("objid not found in values map");id=values[id].split(/[\s.]+/g);for(let i=0;i<id.length;i++)id[i]|=0}else if(Array.isArray(id)){id=id.slice();for(let i=0;i<id.length;i++)id[i]|=0}if(!Array.isArray(id))return this.reporter.error("objid() should be either array or string, got: "+JSON.stringify(id));if(!relative){if(40<=id[1])return this.reporter.error("Second objid identifier OOB");id.splice(0,2,40*id[0]+id[1])}let size=0;for(let i=0;i<id.length;i++){let ident=id[i];for(size++;128<=ident;ident>>=7)size++}var objid=Buffer.alloc(size);let offset=objid.length-1;for(let i=id.length-1;0<=i;i--){let ident=id[i];for(objid[offset--]=127&ident;0<(ident>>=7);)objid[offset--]=128|127&ident}return this._createEncoderBuffer(objid)},DERNode.prototype._encodeTime=function(time,tag){let str;time=new Date(time);return"gentime"===tag?str=[two(time.getUTCFullYear()),two(time.getUTCMonth()+1),two(time.getUTCDate()),two(time.getUTCHours()),two(time.getUTCMinutes()),two(time.getUTCSeconds()),"Z"].join(""):"utctime"===tag?str=[two(time.getUTCFullYear()%100),two(time.getUTCMonth()+1),two(time.getUTCDate()),two(time.getUTCHours()),two(time.getUTCMinutes()),two(time.getUTCSeconds()),"Z"].join(""):this.reporter.error("Encoding "+tag+" time is not supported yet"),this._encodeStr(str,"octstr")},DERNode.prototype._encodeNull=function(){return this._createEncoderBuffer("")},DERNode.prototype._encodeInt=function(num,values){if("string"==typeof num){if(!values)return this.reporter.error("String int or enum given, but no values map");if(!values.hasOwnProperty(num))return this.reporter.error("Values map doesn't contain: "+JSON.stringify(num));num=values[num]}if("number"==typeof num||Buffer.isBuffer(num)||(values=num.toArray(),!num.sign&&128&values[0]&&values.unshift(0),num=Buffer.from(values)),Buffer.isBuffer(num)){let size=num.length;0===num.length&&size++;const out=Buffer.alloc(size);return num.copy(out),0===num.length&&(out[0]=0),this._createEncoderBuffer(out)}if(num<128)return this._createEncoderBuffer(num);if(num<256)return this._createEncoderBuffer([0,num]);let size=1;for(let i=num;256<=i;i>>=8)size++;const out=new Array(size);for(let i=out.length-1;0<=i;i--)out[i]=255&num,num>>=8;return 128&out[0]&&out.unshift(0),this._createEncoderBuffer(Buffer.from(out))},DERNode.prototype._encodeBool=function(value){return this._createEncoderBuffer(value?255:0)},DERNode.prototype._use=function(entity,obj){return(entity="function"==typeof entity?entity(obj):entity)._getEncoder("der").tree},DERNode.prototype._skipDefault=function(dataBuffer,reporter,parent){var state=this._baseState;let i;if(null===state.default)return!1;var data=dataBuffer.join();if(void 0===state.defaultBuffer&&(state.defaultBuffer=this._encodeValue(state.default,reporter,parent).join()),data.length!==state.defaultBuffer.length)return!1;for(i=0;i<data.length;i++)if(data[i]!==state.defaultBuffer[i])return!1;return!0}},{"../base/node":9,"../constants/der":11,inherits:137,"safer-buffer":166}],17:[function(require,module,exports){"use strict";exports.der=require("./der"),exports.pem=require("./pem")},{"./der":16,"./pem":18}],18:[function(require,module,exports){"use strict";var inherits=require("inherits");const DEREncoder=require("./der");function PEMEncoder(entity){DEREncoder.call(this,entity),this.enc="pem"}inherits(PEMEncoder,DEREncoder),(module.exports=PEMEncoder).prototype.encode=function(data,options){var p=DEREncoder.prototype.encode.call(this,data).toString("base64"),out=["-----BEGIN "+options.label+"-----"];for(let i=0;i<p.length;i+=64)out.push(p.slice(i,i+64));return out.push("-----END "+options.label+"-----"),out.join("\n")}},{"./der":16,inherits:137}],19:[function(require,module,exports){!function(module,exports){"use strict";function assert(val,msg){if(!val)throw new Error(msg||"Assertion failed")}function inherits(ctor,superCtor){ctor.super_=superCtor;function TempCtor(){}TempCtor.prototype=superCtor.prototype,ctor.prototype=new TempCtor,ctor.prototype.constructor=ctor}function BN(number,base,endian){if(BN.isBN(number))return number;this.negative=0,this.words=null,this.length=0,(this.red=null)!==number&&("le"!==base&&"be"!==base||(endian=base,base=10),this._init(number||0,base||10,endian||"be"))}var Buffer;"object"==typeof module?module.exports=BN:exports.BN=BN,(BN.BN=BN).wordSize=26;try{Buffer=("undefined"!=typeof window&&void 0!==window.Buffer?window:require("buffer")).Buffer}catch(e){}function parseHex4Bits(string,index){string=string.charCodeAt(index);return 65<=string&&string<=70?string-55:97<=string&&string<=102?string-87:string-48&15}function parseHexByte(string,lowerBound,index){var r=parseHex4Bits(string,index);return lowerBound<=index-1&&(r|=parseHex4Bits(string,index-1)<<4),r}function parseBase(str,start,end,mul){for(var r=0,len=Math.min(str.length,end),i=start;i<len;i++)var c=str.charCodeAt(i)-48,r=r*mul+(49<=c?c-49+10:17<=c?c-17+10:c);return r}BN.isBN=function(num){return num instanceof BN||null!==num&&"object"==typeof num&&num.constructor.wordSize===BN.wordSize&&Array.isArray(num.words)},BN.max=function(left,right){return 0<left.cmp(right)?left:right},BN.min=function(left,right){return left.cmp(right)<0?left:right},BN.prototype._init=function(number,base,endian){if("number"==typeof number)return this._initNumber(number,base,endian);if("object"==typeof number)return this._initArray(number,base,endian);assert((base="hex"===base?16:base)===(0|base)&&2<=base&&base<=36);var start=0;"-"===(number=number.toString().replace(/\s+/g,""))[0]&&(start++,this.negative=1),start<number.length&&(16===base?this._parseHex(number,start,endian):(this._parseBase(number,base,start),"le"===endian&&this._initArray(this.toArray(),base,endian)))},BN.prototype._initNumber=function(number,base,endian){number<0&&(this.negative=1,number=-number),number<67108864?(this.words=[67108863&number],this.length=1):number<4503599627370496?(this.words