aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorhostgame <hostgame@users.noreply.github.com>2019-04-03 17:09:41 +0600
committerhostgame <hostgame@users.noreply.github.com>2019-04-03 17:09:41 +0600
commit491948dbcb6bee740158037a8aefe5096becb76e (patch)
treefd96db200002a1479cbac7a0562ff5398e1b7fdd
parent7a11300336844b822a8f3ec4f85586b79c5954f4 (diff)
downloadBIP39-491948dbcb6bee740158037a8aefe5096becb76e.tar.gz
BIP39-491948dbcb6bee740158037a8aefe5096becb76e.tar.zst
BIP39-491948dbcb6bee740158037a8aefe5096becb76e.zip
Nebulas. Add test spec. Replace nebulas.js by account part of nebulas.js only.
-rw-r--r--src/index.html2
-rw-r--r--src/js/index.js16
-rw-r--r--src/js/nebulas-account.js (renamed from src/js/nebulas.js)19403
-rw-r--r--tests/spec/tests.js7
4 files changed, 3442 insertions, 15986 deletions
diff --git a/src/index.html b/src/index.html
index 73d0084..b6a9fc6 100644
--- a/src/index.html
+++ b/src/index.html
@@ -927,7 +927,7 @@
927 <script src="js/ethereumjs-util.js"></script> 927 <script src="js/ethereumjs-util.js"></script>
928 <script src="js/ripple-util.js"></script> 928 <script src="js/ripple-util.js"></script>
929 <script src="js/bchaddrjs-0.2.1.js"></script> 929 <script src="js/bchaddrjs-0.2.1.js"></script>
930 <script src="js/nebulas.js"></script> 930 <script src="js/nebulas-account.js"></script>
931 <script src="js/sjcl-bip39.js"></script> 931 <script src="js/sjcl-bip39.js"></script>
932 <script src="js/wordlist_english.js"></script> 932 <script src="js/wordlist_english.js"></script>
933 <script src="js/wordlist_japanese.js"></script> 933 <script src="js/wordlist_japanese.js"></script>
diff --git a/src/js/index.js b/src/js/index.js
index 8699733..8c23e61 100644
--- a/src/js/index.js
+++ b/src/js/index.js
@@ -929,17 +929,13 @@
929 pubkey = ethUtil.addHexPrefix(pubkey); 929 pubkey = ethUtil.addHexPrefix(pubkey);
930 } 930 }
931 if ((networks[DOM.network.val()].name == "NAS - Nebulas")) { 931 if ((networks[DOM.network.val()].name == "NAS - Nebulas")) {
932 var NasAccount = require("nebulas").Account; 932 var NasAccount = require("nebulas-account");
933 var privKeyBuffer = keyPair.d.toBuffer(32); 933 var privKeyBuffer = keyPair.d.toBuffer(32);
934 // privkey = privKeyBuffer.toString('hex'); 934 var nebulasAccount = new NasAccount();
935 console.log(privkey); 935 nebulasAccount.setPrivateKey(privKeyBuffer);
936 var nasAccount = NasAccount.NewAccount(privKeyBuffer); 936 address = nebulasAccount.getAddressString();
937 // var addressBuffer = ethUtil.privateToAddress(privKeyBuffer); 937 privkey = nebulasAccount.getPrivateKeyString();
938 // var hexAddress = addressBuffer.toString('hex'); 938 pubkey = nebulasAccount.getPublicKeyString();
939 // var checksumAddress = ethUtil.toChecksumAddress(hexAddress);
940 address = nasAccount.getAddressString();
941 privkey = nasAccount.getPrivateKeyString();
942 pubkey = nasAccount.getPublicKeyString();
943 } 939 }
944 // Ripple values are different 940 // Ripple values are different
945 if (networks[DOM.network.val()].name == "XRP - Ripple") { 941 if (networks[DOM.network.val()].name == "XRP - Ripple") {
diff --git a/src/js/nebulas.js b/src/js/nebulas-account.js
index b8983f7..45d8724 100644
--- a/src/js/nebulas.js
+++ b/src/js/nebulas-account.js
@@ -1,2430 +1,4 @@
1require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ 1require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2"use strict";
3
4var Buffer = require('safe-buffer').Buffer;
5var Base58 = require('bs58');
6var cryptoUtils = require('./utils/crypto-utils.js');
7var utils = require('./utils/utils.js');
8
9var AddressLength = 26;
10var AddressPrefix = 25;
11var NormalType = 87;
12var ContractType = 88;
13
14var KeyVersion3 = 3;
15var KeyCurrentVersion = 4;
16
17/**
18 * @typedef {Object} KeyOptions
19 * @property {Buffer} salt
20 * @property {Buffer} iv
21 * @property {String} kdf
22 * @property {Number} dklen
23 * @property {Number} c
24 * @property {Number} n
25 * @property {Number} r
26 * @property {Number} p
27 * @property {String} cipher
28 * @property {Buffer} uuid
29 * @global
30 */
31
32/**
33 * Key Object.
34 * @typedef {Object} Key
35 * @property {Number} version
36 * @property {Buffer} id
37 * @property {HexString} address
38 * @property {Object} crypto
39 * @global
40 */
41
42/**
43 * Account constructor.
44 * Class encapsulate main operation with account entity.
45 * @constructor
46 *
47 * @param {Hash} priv Account private key.
48 * @param {String} path
49 *
50 * @example var account = new Account(new Buffer("ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6", "hex") );
51 *
52 */
53var Account = function (priv, path) {
54 priv = priv || cryptoUtils.crypto.randomBytes(32);
55 this.setPrivateKey(priv);
56 this.path = path;
57};
58
59/**
60 * Account factory method.
61 * Create random account.
62 * @static
63 *
64 * @return {Account} Instance of Account constructor.
65 *
66 * @example var account = Account.NewAccount();
67 */
68Account.NewAccount = function () {
69 return new Account(cryptoUtils.crypto.randomBytes(32));
70};
71
72/**
73 * Address validation method.
74 *
75 * @static
76 * @param {String/Hash} addr - Account address.
77 * @param {Number} type - NormalType / ContractType
78 *
79 * @return {Boolean} Is address has correct format.
80 *
81 * @example
82 * if ( Account.isValidAddress("n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5") ) {
83 * // some code
84 * };
85 */
86Account.isValidAddress = function (addr, type) {
87 /*jshint maxcomplexity:10 */
88
89 if (utils.isString(addr)) {
90 try {
91 addr = Base58.decode(addr);
92 } catch (e) {
93 console.log("invalid address.");
94 // if address can't be base58 decode, return false.
95 return false;
96 }
97 } else if (!Buffer.isBuffer(addr)) {
98 return false;
99 }
100 // address not equal to 26
101 if (addr.length !== AddressLength) {
102 return false;
103 }
104
105 // check if address start with AddressPrefix
106 var buff = Buffer.from(addr);
107 if (buff.readUIntBE(0, 1) !== AddressPrefix) {
108 return false;
109 }
110
111 // check if address type is NormalType or ContractType
112 var t = buff.readUIntBE(1, 1);
113 if (utils.isNumber(type) && (type === NormalType || type === ContractType)) {
114 if (t !== type) {
115 return false;
116 }
117 } else if (t !== NormalType && t !== ContractType) {
118 return false;
119 }
120 var content = addr.slice(0, 22);
121 var checksum = addr.slice(-4);
122 return Buffer.compare(cryptoUtils.sha3(content).slice(0, 4), checksum) === 0;
123};
124
125/**
126 * Restore account from address.
127 * Receive addr or Account instance.
128 * If addr is Account instance return new Account instance with same PrivateKey.
129 *
130 * @static
131 * @param {(Hash|Object)} - Client address or Account instance.
132 *
133 * @return {Account} Instance of Account restored from address.
134 *
135 * @example var account = Account.fromAddress("n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5");
136 */
137Account.fromAddress = function (addr) {
138 var acc = new Account();
139 if (addr instanceof Account) {
140 acc.setPrivateKey(addr.getPrivateKey());
141 return acc;
142 }
143 if (utils.isString(addr) && this.isValidAddress(addr)) {
144 acc.address = Base58.decode(addr);
145 return acc;
146 }
147
148 var buf = cryptoUtils.toBuffer(addr);
149 if (this.isValidAddress(buf)) {
150 acc.address = buf;
151 return acc;
152 }
153 throw new Error("invalid address");
154};
155
156/**
157 * Restore account from public key.
158 *
159 * @static
160 * @param {(String/Hash)} - Public key.
161 *
162 * @return {Account} Instance of Account restored from address.
163 *
164 * @example var account = Account.fromPubKey("f18ec04019dd131bbcfada4020b001d547244d768f144ef947577ce53a13ad690eb43e4b02a8daa3c168045cd122c0685f083e1656756ba7982721322ebe4da7");
165 */
166Account.fromPubKey = function (publicKey) {
167 var acc = new Account();
168 acc.pubKey = cryptoUtils.toBuffer(publicKey);
169 return acc;
170};
171
172Account.getNormalType = function () {
173 return NormalType;
174};
175
176Account.getContractType = function () {
177 return ContractType;
178};
179
180Account.prototype = {
181 /**
182 * Private Key setter.
183 *
184 * @param {Hash} priv - Account private key.
185 *
186 * @example account.setPrivateKey("ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6");
187 */
188 setPrivateKey: function (priv) {
189 if (utils.isString(priv) || Buffer.isBuffer(priv)) {
190 this.privKey = priv.length === 32 ? priv : Buffer(priv, 'hex');
191 this.pubKey = null;
192 this.address = null;
193 }
194 },
195 /**
196 * Private Key getter.
197 *
198 * @return {Buffer} Account private key.
199 *
200 * @example var privKey = account.getPrivateKey();
201 * //<Buffer 5b ed 67 f9 9c b3 31 9e 0c 6f 6a 03 54 8b e3 c8 c5 2a 83 64 46 4f 88 6f> 24
202 */
203 getPrivateKey: function () {
204 return this.privKey;
205 },
206 /**
207 * Get Private Key in hex string format.
208 *
209 * @return {HexString} Account private key in String format.
210 *
211 * @example var privKey = account.getPrivateKeyString();
212 * //"ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6"
213 */
214 getPrivateKeyString: function () {
215 return this.getPrivateKey().toString('hex');
216 },
217 /**
218 * Public Key getter.
219 *
220 * @return {Buffer} Account public key.
221 *
222 * @example var publicKey = account.getPublicKey();
223 * //<Buffer c0 96 aa 4e 66 c7 4a 9a c7 18 31 f1 24 72 2a c1 3e b5 df 7f 97 1b 13 1d 46 a2 8a e6 81 c6 1d 96 f7 07 d0 aa e9 a7 67 436b 68 af a8 f0 96 65 17 24 29 ... >
224 */
225 getPublicKey: function () {
226 if (utils.isNull(this.pubKey)) {
227 this.pubKey = cryptoUtils.privateToPublic(this.privKey);
228 }
229 return this.pubKey;
230 },
231 /**
232 * Get Public Key in hex string format.
233 *
234 * @return {HexString} Account public key in String format.
235 *
236 * @example var publicKey = account.getPublicKey();
237 * //"f18ec04019dd131bbcfada4020b001d547244d768f144ef947577ce53a13ad690eb43e4b02a8daa3c168045cd122c0685f083e1656756ba7982721322ebe4da7"
238 */
239 getPublicKeyString: function () {
240 return this.getPublicKey().toString('hex');
241 },
242 /**
243 * Accaunt address getter.
244 *
245 * @return {Buffer} Account address.
246 *
247 * @example var publicKey = account.getAddress();
248 * //<Buffer 7f 87 83 58 46 96 12 7d 1a c0 57 1a 42 87 c6 25 36 08 ff 32 61 36 51 7c>
249 */
250 getAddress: function () {
251 if (utils.isNull(this.address)) {
252
253 var pubKey = this.getPublicKey();
254 if (pubKey.length !== 64) {
255 pubKey = cryptoUtils.secp256k1.publicKeyConvert(pubKey, false).slice(1);
256 }
257
258 // The uncompressed form consists of a 0x04 (in analogy to the DER OCTET STRING tag) plus
259 // the concatenation of the binary representation of the X coordinate plus the binary
260 // representation of the y coordinate of the public point.
261 pubKey = Buffer.concat([cryptoUtils.toBuffer(4), pubKey]);
262
263 // Only take the lower 160bits of the hash
264 var content = cryptoUtils.sha3(pubKey);
265 content = cryptoUtils.ripemd160(content);
266 // content = AddressPrefix + NormalType + content(local address only use normal type)
267 content = Buffer.concat([cryptoUtils.toBuffer(AddressPrefix), cryptoUtils.toBuffer(NormalType), content]);
268 var checksum = cryptoUtils.sha3(content).slice(0, 4);
269 this.address = Buffer.concat([content, checksum]);
270 }
271 return this.address;
272 },
273 /**
274 * Get account address in hex string format.
275 *
276 * @return {HexString} Account address in String format.
277 *
278 * @example var publicKey = account.getAddressString();
279 * //"802d529bf55d6693b3ac72c59b4a7d159da53cae5a7bf99c"
280 */
281 getAddressString: function () {
282 var addr = this.getAddress();
283 return Base58.encode(addr);
284 },
285 /**
286 * Generate key buy passphrase and options.
287 *
288 * @param {Password} password - Provided password.
289 * @param {KeyOptions} opts - Key options.
290 *
291 * @return {Key} Key Object.
292 *
293 * @example var key = account.toKey("passphrase");
294 */
295 toKey: function (password, opts) {
296 /*jshint maxcomplexity:17 */
297
298 opts = opts || {};
299 var salt = opts.salt || cryptoUtils.crypto.randomBytes(32);
300 var iv = opts.iv || cryptoUtils.crypto.randomBytes(16);
301 var derivedKey;
302 var kdf = opts.kdf || 'scrypt';
303 var kdfparams = {
304 dklen: opts.dklen || 32,
305 salt: salt.toString('hex')
306 };
307 if (kdf === 'pbkdf2') {
308 kdfparams.c = opts.c || 262144;
309 kdfparams.prf = 'hmac-sha256';
310 derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), salt, kdfparams.c, kdfparams.dklen, 'sha256');
311 } else if (kdf === 'scrypt') {
312 kdfparams.n = opts.n || 4096;
313 kdfparams.r = opts.r || 8;
314 kdfparams.p = opts.p || 1;
315 derivedKey = cryptoUtils.scrypt(new Buffer(password), salt, kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen);
316 } else {
317 throw new Error('Unsupported kdf');
318 }
319 var cipher = cryptoUtils.crypto.createCipheriv(opts.cipher || 'aes-128-ctr', derivedKey.slice(0, 16), iv);
320 if (!cipher) {
321 throw new Error('Unsupported cipher');
322 }
323 var ciphertext = Buffer.concat([cipher.update(this.privKey), cipher.final()]);
324 // var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex')])); // KeyVersion3 deprecated
325 var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex'), iv, new Buffer(opts.cipher || 'aes-128-ctr')]));
326 return {
327 version: KeyCurrentVersion,
328 id: cryptoUtils.uuid.v4({
329 random: opts.uuid || cryptoUtils.crypto.randomBytes(16)
330 }),
331 address: this.getAddressString(),
332 crypto: {
333 ciphertext: ciphertext.toString('hex'),
334 cipherparams: {
335 iv: iv.toString('hex')
336 },
337 cipher: opts.cipher || 'aes-128-ctr',
338 kdf: kdf,
339 kdfparams: kdfparams,
340 mac: mac.toString('hex'),
341 machash: "sha3256"
342 }
343 };
344 },
345 /**
346 * Generate key buy passphrase and options.
347 * Return in JSON format.
348 *
349 * @param {Password} password - Provided password.
350 * @param {KeyOptions} opts - Key options.
351 *
352 * @return {String} JSON stringify Key.
353 *
354 * @example var key = account.toKeyString("passphrase");
355 */
356 toKeyString: function (password, opts) {
357 return JSON.stringify(this.toKey(password, opts));
358 },
359 /**
360 * Restore account from key and passphrase.
361 *
362 * @param {Key} input - Key Object.
363 * @param {Password} password - Provided password.
364 * @param {Boolean} nonStrict - Strict сase sensitivity flag.
365 *
366 * @return {@link Account} - Instance of Account restored from key and passphrase.
367 */
368 fromKey: function (input, password, nonStrict) {
369 /*jshint maxcomplexity:10 */
370
371 var json = typeof input === 'object' ? input : JSON.parse(nonStrict ? input.toLowerCase() : input);
372 if (json.version !== KeyVersion3 && json.version !== KeyCurrentVersion) {
373 throw new Error('Not supported wallet version');
374 }
375 var derivedKey;
376 var kdfparams;
377 if (json.crypto.kdf === 'scrypt') {
378 kdfparams = json.crypto.kdfparams;
379 derivedKey = cryptoUtils.scrypt(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen);
380 } else if (json.crypto.kdf === 'pbkdf2') {
381 kdfparams = json.crypto.kdfparams;
382 if (kdfparams.prf !== 'hmac-sha256') {
383 throw new Error('Unsupported parameters to PBKDF2');
384 }
385 derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.c, kdfparams.dklen, 'sha256');
386 } else {
387 throw new Error('Unsupported key derivation scheme');
388 }
389 var ciphertext = new Buffer(json.crypto.ciphertext, 'hex');
390 var mac;
391
392 if (json.version === KeyCurrentVersion) {
393 mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext, new Buffer(json.crypto.cipherparams.iv, 'hex'), new Buffer(json.crypto.cipher)]));
394 } else {
395 // KeyVersion3
396 mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext]));
397 }
398
399 if (mac.toString('hex') !== json.crypto.mac) {
400 throw new Error('Key derivation failed - possibly wrong passphrase');
401 }
402 var decipher = cryptoUtils.crypto.createDecipheriv(json.crypto.cipher, derivedKey.slice(0, 16), new Buffer(json.crypto.cipherparams.iv, 'hex'));
403 var seed = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
404 while (seed.length < 32) {
405 var nullBuff = new Buffer([0x00]);
406 seed = Buffer.concat([nullBuff, seed]);
407 }
408 this.setPrivateKey(seed);
409 return this;
410 }
411
412};
413
414module.exports = Account;
415
416},{"./utils/crypto-utils.js":19,"./utils/utils.js":21,"bs58":105,"safe-buffer":247}],2:[function(require,module,exports){
417
418"use strict";
419
420var utils = require('./utils/utils.js');
421
422/**
423 * Admin API constructor.
424 * Class encapsulate methods for admin APIs commands.
425 * @see [Admin API documentation:]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md}.
426 * @constructor
427 *
428 * @param {Neb} neb - Instance of Neb library.
429 *
430 * @example
431 * var admin = new Admin( new Neb() );
432 * // or just
433 * var admin = new Neb().admin;
434 */
435var Admin = function (neb) {
436 this._setRequest(neb._request);
437};
438
439/**
440 * @private
441 * @param {Request} request - transport wrapper.
442 */
443Admin.prototype._setRequest = function (request) {
444 this._request = request;
445 this._path = '/admin';
446};
447
448/**
449 * Method get info about nodes in Nebulas Network.
450 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#nodeinfo}
451 *
452 * @return [nodeInfoObject]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#nodeinfo}
453 *
454 * @example
455 * var admin = new Neb().admin;
456 * admin.nodeInfo().then(function(info) {
457 * //code
458 * });
459 */
460Admin.prototype.nodeInfo = function () {
461 return this._sendRequest("get", "/nodeinfo", null);
462};
463
464/**
465 * Method get list of available addresses.
466 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#accounts}
467 *
468 * @return [accountsList]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#accounts}
469 *
470 * @example
471 * var admin = new Neb().admin;
472 * admin.accounts().then(function(accounts) {
473 * //code
474 * });
475 */
476Admin.prototype.accounts = function () {
477 return this._sendRequest("get", "/accounts", null);
478};
479
480/**
481 * Method create a new account in Nebulas network with provided passphrase.
482 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#newaccount}
483 *
484 * @param {Object} options
485 * @param {Password} options.passphrase
486 *
487 * @return [address]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#newaccount}
488 *
489 * @example
490 * var admin = new Neb().admin;
491 * admin.newAccount({passphrase: "passphrase"}).then(function(address) {
492 * //code
493 * });
494 */
495Admin.prototype.newAccount = function (options) {
496 options = utils.argumentsToObject(['passphrase'], arguments);
497 var params = { "passphrase": options.passphrase };
498 return this._sendRequest("post", "/account/new", params);
499};
500
501/**
502 * Method unlock account with provided passphrase.
503 * After the default unlock time, the account will be locked.
504 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#unlockaccount}
505 *
506 * @param {Object} options
507 * @param {HexString} options.address
508 * @param {Password} options.passphrase
509 * @param {Number} options.duration
510 *
511 * @return [isUnLocked]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#unlockaccount}
512 *
513 * @example
514 * var admin = new Neb().admin;
515 * admin.unlockAccount({
516 * address: "n1cYKNHTeVW9v1NQRWuhZZn9ETbqAYozckh",
517 * passphrase: "passphrase",
518 * duration: 1000000000
519 * }).then(function(isUnLocked) {
520 * //code
521 * });
522 */
523Admin.prototype.unlockAccount = function (options) {
524 options = utils.argumentsToObject(['address', 'passphrase', 'duration'], arguments);
525 var params = {
526 "address": options.address,
527 "passphrase": options.passphrase,
528 "duration": options.duration
529 };
530 return this._sendRequest("post", "/account/unlock", params);
531};
532
533/**
534 * Method lock account.
535 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#lockaccount}
536 *
537 * @param {Object} options
538 * @param {HexString} options.address
539 *
540 * @return [isLocked]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#lockaccount}
541 *
542 * @example
543 * var admin = new Neb().admin;
544 * admin.lockAccount({address: "n1cYKNHTeVW9v1NQRWuhZZn9ETbqAYozckh"}).then(function(isLocked) {
545 * //code
546 * });
547 */
548Admin.prototype.lockAccount = function (options) {
549 options = utils.argumentsToObject(['address'], arguments);
550 var params = { "address": options.address };
551 return this._sendRequest("post", "/account/lock", params);
552};
553
554/**
555 * Method wrap transaction sending functionality.
556 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#sendtransaction}
557 *
558 * @param {TransactionOptions} options
559 *
560 * @return [Transcation hash and contract address]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#sendtransaction}
561 *
562 * @example
563 * var admin = new Neb().admin;
564 * admin.sendTransaction({
565 * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
566 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
567 * value: 10,
568 * nonce: 12,
569 * gasPrice: 1000000,
570 * gasLimit: 2000000
571 * }).then(function(tx) {
572 * //code
573 * });
574 */
575Admin.prototype.sendTransaction = function (options) {
576 options = utils.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract', 'binary'], arguments);
577 var params = {
578 "from": options.from,
579 "to": options.to,
580 "value": utils.toString(options.value),
581 "nonce": options.nonce,
582 "gasPrice": utils.toString(options.gasPrice),
583 "gasLimit": utils.toString(options.gasLimit),
584 "contract": options.contract,
585 "binary": options.binary
586 };
587 return this._sendRequest("post", "/transaction", params);
588};
589
590/**
591 * Method sign hash.
592 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#signhash}
593 *
594 * @param {Object} options
595 * @param {HexString} options.address
596 * @param {Base64} options.hash of hash bytes with base64 encode.
597 * @param {UInt32} options.alg
598 *
599 * @return [data]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#signhash}
600 *
601 * @example
602 * var admin = new Neb().admin;
603 * admin.SignHash({
604 * address: "n1cYKNHTeVW9v1NQRWuhZZn9ETbqAYozckh",
605 * hash: "OGQ5NjllZWY2ZWNhZDNjMjlhM2E2MjkyODBlNjg2Y2YwYzNmNWQ1YTg2YWZmM2NhMTIwMjBjOTIzYWRjNmM5Mg==",
606 * alg: 1
607 * }).then(function(data) {
608 * //code
609 * });
610 */
611Admin.prototype.signHash = function (options) {
612 options = utils.argumentsToObject(['address', 'hash', 'alg'], arguments);
613 var params = {
614 "address": options.address,
615 "hash": options.hash,
616 "alg": options.alg
617 };
618 return this._sendRequest("post", "/sign/hash", params);
619};
620
621/**
622 * Method sign transaction with passphrase.
623 * The transaction's from addrees must be unlock before sign call.
624 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#signtransactionwithpassphrase}
625 *
626 * @param {TransactionOptions} options
627 * @param {Password} options.passphrase
628 *
629 * @return [Transcation hash and contract address]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#signtransactionwithpassphrase}
630 *
631 * @example
632 * var admin = new Neb().admin;
633 * admin.signTransactionWithPassphrase({
634 * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
635 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
636 * value: 10,
637 * nonce: 12,
638 * gasPrice: 1000000,
639 * gasLimit: 2000000,
640 * passphrase: "passphrase"
641 * }).then(function(tx) {
642 * //code
643 * });
644 */
645Admin.prototype.signTransactionWithPassphrase = function (options) {
646 options = utils.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract', 'binary', 'passphrase'], arguments);
647 var tx = {
648 "from": options.from,
649 "to": options.to,
650 "value": utils.toString(options.value),
651 "nonce": options.nonce,
652 "gasPrice": utils.toString(options.gasPrice),
653 "gasLimit": utils.toString(options.gasLimit),
654 "contract": options.contract,
655 "binary": options.binary
656 };
657 var params = {
658 "transaction": tx,
659 "passphrase": options.passphrase
660 };
661 return this._sendRequest("post", "/sign", params);
662};
663
664/**
665 * Method send transaction with passphrase.
666 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#sendtransactionwithpassphrase}
667 *
668 * @param {TransactionOptions} options
669 * @param {Password} options.passphrase
670 *
671 * @return [data]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#sendtransactionwithpassphrase}
672 *
673 * @example
674 * var admin = new Neb().admin;
675 * admin.sendTransactionWithPassphrase({
676 * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
677 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
678 * value: 10,
679 * nonce: 12,
680 * gasPrice: 1000000,
681 * gasLimit: 2000000,
682 * passphrase: "passphrase"
683 * }).then(function(tx) {
684 * //code
685 * });
686 */
687Admin.prototype.sendTransactionWithPassphrase = function (options) {
688 options = utils.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract', 'binary', 'passphrase'], arguments);
689 var tx = {
690 "from": options.from,
691 "to": options.to,
692 "value": utils.toString(options.value),
693 "nonce": options.nonce,
694 "gasPrice": utils.toString(options.gasPrice),
695 "gasLimit": utils.toString(options.gasLimit),
696 "contract": options.contract,
697 "binary": options.binary
698 };
699 var params = {
700 "transaction": tx,
701 "passphrase": options.passphrase
702 };
703 return this._sendRequest("post", "/transactionWithPassphrase", params);
704};
705
706/**
707 * Method start listen provided port.
708 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#startpprof}
709 *
710 * @param {Object} options
711 * @param {String} options.listen - Listen port.
712 *
713 * @return [isListenStrted]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#startpprof}
714 *
715 * @example
716 * var admin = new Neb().admin;
717 * admin.startPprof({listen: '8080'}).then(function(isListenStrted) {
718 * //code
719 * });
720 */
721Admin.prototype.startPprof = function (options) {
722 options = utils.argumentsToObject(['listen'], arguments);
723 var params = { "listen": options.listen };
724 return this._sendRequest("post", "/pprof", params);
725};
726
727/**
728 * Method get config of node in Nebulas Network.
729 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#getConfig}
730 *
731 * @return [config]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#getConfig}
732 *
733 * @example
734 * var admin = new Neb().admin;
735 * admin.getConfig().then(function(info) {
736 * //code
737 * });
738 */
739Admin.prototype.getConfig = function () {
740 return this._sendRequest("get", "/getConfig", null);
741};
742
743Admin.prototype._sendRequest = function (method, api, params, callback) {
744 var action = this._path + api;
745 if (typeof callback === "function") {
746 return this._request.asyncRequest(method, action, params, callback);
747 } else {
748 return this._request.request(method, action, params);
749 }
750};
751
752module.exports = Admin;
753
754},{"./utils/utils.js":21}],3:[function(require,module,exports){
755
756"use strict";
757
758var utils = require('./utils/utils.js');
759
760/**
761 * User API constructor.
762 * Class encapsulate methods for building distributed applications and services.
763 *
764 * @see [API documentation]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md}
765 * @constructor
766 *
767 * @param {Neb} neb - Instance of Neb library.
768 *
769 * @example
770 * var api = new API ( new Neb() );
771 * // or just
772 * var api = new Neb().api;
773 */
774var API = function (neb) {
775 this._setRequest(neb._request);
776};
777
778/**
779 * @private
780 * @param {Request} request - transport wrapper.
781 */
782API.prototype._setRequest = function (request) {
783 this._request = request;
784 this._path = '/user';
785};
786
787/**
788 * Method get state of Nebulas Network.
789 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getnebstate}
790 *
791 * @return [NebStateObject]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getnebstate}
792 *
793 * @example
794 * var api = new Neb().api;
795 * api.getNebState().then(function(state) {
796 * //code
797 * });
798 */
799API.prototype.getNebState = function () {
800 return this._sendRequest("get", "/nebstate", null);
801};
802
803/**
804 * Method get latest irreversible block of Nebulas Network.
805 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#latestirreversibleblock}
806 *
807 * @return [dataBlockInfo.]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#latestirreversibleblock}
808 *
809 * @example
810 * var api = new Neb().api;
811 * api.latestIrreversibleBlock().then(function(blockData) {
812 * //code
813 * });
814 */
815API.prototype.latestIrreversibleBlock = function () {
816 return this._sendRequest("get", "/lib", null);
817};
818
819/**
820 * Method return the state of the account. Balance and nonce.
821 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getaccountstate}
822 *
823 * @param {Object} options
824 * @param {HexString} options.address
825 * @param {String} options.height
826 *
827 * @return [accaountStateObject]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getaccountstate}
828 *
829 * @example
830 * var api = new Neb().api;
831 * api.getAccountState({address: "n1QsosVXKxiV3B4iDWNmxfN4VqpHn2TeUcn"}).then(function(state) {
832 * //code
833 * });
834 */
835API.prototype.getAccountState = function (options) {
836 options = utils.argumentsToObject(['address', 'height'], arguments);
837 var params = { "address": options.address, "height": options.height };
838 return this._sendRequest("post", "/accountstate", params);
839};
840
841/**
842 * Method wrap smart contract call functionality.
843 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#call}
844 *
845 * @param {TransactionOptions} options
846 *
847 * @return [Transcation hash]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#call}
848 *
849 * @example
850 * var api = new Neb().api;
851 * api.call({
852 * chainID: 1,
853 * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
854 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
855 * value: 10,
856 * nonce: 12,
857 * gasPrice: 1000000,
858 * gasLimit: 2000000,
859 * contract: {
860 * function: "save",
861 * args: "[0]"
862 * }
863 * }).then(function(tx) {
864 * //code
865 * });
866 */
867API.prototype.call = function (options) {
868 options = utils.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract'], arguments);
869 var params = {
870 "from": options.from,
871 "to": options.to,
872 "value": utils.toString(options.value),
873 "nonce": options.nonce,
874 "gasPrice": utils.toString(options.gasPrice),
875 "gasLimit": utils.toString(options.gasLimit),
876 "contract": options.contract
877 };
878 return this._sendRequest("post", "/call", params);
879};
880
881/**
882 * Method wrap submit the signed transaction.
883 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#sendrawtransaction}
884 *
885 * @param {Object} options
886 * @param {String} options.data
887 *
888 * @return [Transcation hash]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#sendrawtransaction}
889 *
890 * @example
891 * var api = new Neb().api;
892 * var tx = new Transaction({
893 * chainID: 1,
894 * from: acc1,
895 * to: acc2,
896 * value: 10,
897 * nonce: 12,
898 * gasPrice: 1000000,
899 * gasLimit: 2000000
900 * });
901 * tx.signTransaction();
902 * api.sendRawTransaction( {data: tx.toProtoString()} ).then(function(hash) {
903 * //code
904 * });
905 */
906API.prototype.sendRawTransaction = function (options) {
907 options = utils.argumentsToObject(['data'], arguments);
908 var params = { "data": options.data };
909 return this._sendRequest("post", "/rawtransaction", params);
910};
911
912/**
913 * Get block header info by the block hash.
914 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getblockbyhash}
915 *
916 * @param {Object} options
917 * @param {HexString} options.hash
918 * @param {Boolean} options.fullTransaction
919 *
920 * @return [Block]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getblockbyhash}
921 *
922 * @example
923 * var api = new Neb().api;
924 * api.getBlockByHash({
925 * hash: "00000658397a90df6459b8e7e63ad3f4ce8f0a40b8803ff2f29c611b2e0190b8",
926 * fullTransaction: true
927 * }).then(function(block) {
928 * //code
929 * });
930 */
931API.prototype.getBlockByHash = function (options) {
932 options = utils.argumentsToObject(['hash', 'fullTransaction'], arguments);
933 var params = { "hash": options.hash, "full_fill_transaction": options.fullTransaction };
934 return this._sendRequest("post", "/getBlockByHash", params);
935};
936
937/**
938 * Get block header info by the block height.
939 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getblockbyheight}
940 *
941 * @param {Object} options
942 * @param {Number} options.height
943 * @param {Boolean} options.fullTransaction
944 *
945 * @return [Block]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getblockbyheight}
946 *
947 * @example
948 * var api = new Neb().api;
949 * api.getBlockByHeight({height:2, fullTransaction:true}).then(function(block) {
950 * //code
951 * });
952 */
953API.prototype.getBlockByHeight = function (options) {
954 options = utils.argumentsToObject(['height', 'fullTransaction'], arguments);
955 var params = { "height": options.height, "full_fill_transaction": options.fullTransaction };
956 return this._sendRequest("post", "/getBlockByHeight", params);
957};
958
959/**
960 * Get transactionReceipt info by tansaction hash.
961 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#gettransactionreceipt}
962 *
963 * @param {Object} options
964 * @param {HexString} options.hash
965 *
966 * @return [TransactionReceipt]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#gettransactionreceipt}
967 *
968 * @example
969 * var api = new Neb().api;
970 * api.getTransactionReceipt({hash: "cc7133643a9ae90ec9fa222871b85349ccb6f04452b835851280285ed72b008c"}).then(function(receipt) {
971 * //code
972 * });
973 */
974API.prototype.getTransactionReceipt = function (options) {
975 options = utils.argumentsToObject(['hash'], arguments);
976 var params = { "hash": options.hash };
977 return this._sendRequest("post", "/getTransactionReceipt", params);
978};
979
980/**
981 * Get transactionReceipt info by contract address.
982 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#gettransactionbycontract}
983 *
984 * @param {Object} options
985 * @param {HexString} options.address contract address
986 *
987 * @returns the same as [TransactionReceipt]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#gettransactionreceipt}
988 *
989 * @example
990 * var api = new Neb().api;
991 * api.getTransactionByContract({address: "n1sqDHGjYtX6rMqFoq5Tow3s3LqF4ZxBvE3"}).then(function(receipt) {
992 * //code
993 * });
994 */
995API.prototype.getTransactionByContract = function (options) {
996 options = utils.argumentsToObject(['address'], arguments);
997 var params = { "address": options.address };
998 return this._sendRequest("post", "/getTransactionByContract", params);
999};
1000
1001/**
1002 * Return the subscribed events of transaction & block.
1003 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#subscribe}
1004 *
1005 * @param {Object} options
1006 * @param {Array|String} options.topics
1007 * @param {Function} options.onDownloadProgress - On progress callback function. Recive chunk.
1008 *
1009 * @return [eventData]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#subscribe}
1010 *
1011 * @example
1012 * var api = new Neb().api;
1013 * api.subscribe({topics: ["chain.linkBlock", "chain.pendingTransaction"]}).then(function(eventData) {
1014 * //code
1015 * });
1016 */
1017API.prototype.subscribe = function (options) {
1018 options = utils.argumentsToObject(['topics', 'onDownloadProgress'], arguments);
1019 var params = { "topics": options.topics };
1020 var axiosOptions;
1021 if (typeof options.onDownloadProgress === 'function') {
1022 axiosOptions = {
1023 onDownloadProgress: function (e) {
1024 if (typeof e.target._readLength === 'undefined') {
1025 e.target._readLength = 0;
1026 }
1027 var chunk = e.target.responseText.substr(e.target._readLength);
1028 // TODO check and split multi events
1029 if (chunk && chunk.trim().length > 0) {
1030 e.target._readLength += chunk.length;
1031 options.onDownloadProgress(chunk);
1032 }
1033 }
1034 };
1035 }
1036 return this._sendRequest("post", "/subscribe", params, null, axiosOptions);
1037};
1038
1039/**
1040 * Return current gasPrice.
1041 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getgasprice}
1042 *
1043 * @return [Gas Price]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getgasprice}
1044 *
1045 * @example
1046 * var api = new Neb().api;
1047 * api.gasPrice().then(function(gasPrice) {
1048 * //code
1049 * });
1050 */
1051API.prototype.gasPrice = function () {
1052 return this._sendRequest("get", "/getGasPrice", null);
1053};
1054
1055/**
1056 * Return the estimate gas of transaction.
1057 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#estimategas}
1058 *
1059 * @param {TransactionOptions} options
1060 *
1061 * @return [Gas]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#estimategas}
1062 *
1063 * @example
1064 * var api = new Neb().api;
1065 * api.estimateGas({
1066 * chainID: 1,
1067 * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
1068 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
1069 * value: 10,
1070 * nonce: 12,
1071 * gasPrice: 1000000,
1072 * gasLimit: 2000000
1073 * }).then(function(gas) {
1074 * //code
1075 * });
1076 */
1077API.prototype.estimateGas = function (options) {
1078 options = utils.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract', 'binary'], arguments);
1079 var params = {
1080 "from": options.from,
1081 "to": options.to,
1082 "value": utils.toString(options.value),
1083 "nonce": options.nonce,
1084 "gasPrice": utils.toString(options.gasPrice),
1085 "gasLimit": utils.toString(options.gasLimit),
1086 "contract": options.contract,
1087 "binary": options.binary
1088 };
1089 return this._sendRequest("post", "/estimateGas", params);
1090};
1091
1092/**
1093 * Return the events list of transaction.
1094 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#geteventsbyhash}
1095 *
1096 * @param {Object} options
1097 * @param {HexString} options.hash
1098 *
1099 * @return [Events]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#geteventsbyhash}
1100 *
1101 * @example
1102 * var api = new Neb().api;
1103 * api.getEventsByHash({hash: "ec239d532249f84f158ef8ec9262e1d3d439709ebf4dd5f7c1036b26c6fe8073"}).then(function(events) {
1104 * //code
1105 * });
1106 */
1107API.prototype.getEventsByHash = function (options) {
1108 options = utils.argumentsToObject(['hash'], arguments);
1109 var params = { "hash": options.hash };
1110 return this._sendRequest("post", "/getEventsByHash", params);
1111};
1112
1113/**
1114 * Method getter for dpos dynasty.
1115 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getdynasty}
1116 *
1117 * @param {Object} options
1118 * @param {Number} options.height
1119 *
1120 * @return [delegatees]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getdynasty}
1121 *
1122 * @example
1123 * var api = new Neb().api;
1124 * api.getDynasty({height: 1}).then(function(delegatees) {
1125 * //code
1126 * });
1127 */
1128API.prototype.getDynasty = function (options) {
1129 options = utils.argumentsToObject(['height'], arguments);
1130 var params = { "height": options.height };
1131 return this._sendRequest("post", "/dynasty", params);
1132};
1133
1134API.prototype._sendRequest = function (method, api, params, callback, axiosOptions) {
1135 var action = this._path + api;
1136 if (typeof callback === "function") {
1137 return this._request.asyncRequest(method, action, params, callback);
1138 } else {
1139 return this._request.request(method, action, params, axiosOptions);
1140 }
1141};
1142
1143module.exports = API;
1144
1145},{"./utils/utils.js":21}],4:[function(require,module,exports){
1146"use strict";
1147
1148var axios = require("axios");
1149
1150var debugLog = false;
1151
1152var HttpRequest = function (host, timeout, apiVersion) {
1153 this.host = host || "http://localhost:8685";
1154 this.timeout = timeout || 0;
1155 this.apiVersion = apiVersion || "v1";
1156};
1157
1158HttpRequest.prototype.setHost = function (host) {
1159 this.host = host;
1160};
1161
1162HttpRequest.prototype.setAPIVersion = function (apiVersion) {
1163 this.apiVersion = apiVersion;
1164};
1165
1166HttpRequest.prototype.createUrl = function (api) {
1167 return this.host + "/" + this.apiVersion + api;
1168};
1169
1170HttpRequest.prototype.request = function (method, api, payload, axiosOptions) {
1171 if (debugLog) {
1172 console.log("[debug] HttpRequest: " + method + " " + this.createUrl(api) + " " + JSON.stringify(payload));
1173 }
1174
1175 var axiosParams = {
1176 method: method,
1177 url: this.createUrl(api),
1178 data: payload
1179 };
1180 if (axiosOptions && typeof axiosOptions.onDownloadProgress === 'function') {
1181 axiosParams.onDownloadProgress = axiosOptions.onDownloadProgress;
1182 }
1183 return axios(axiosParams).then(function (resp) {
1184 if ("text/html; charset=UTF-8" === resp.headers['content-type']) {
1185 throw new Error(resp.status + ' - ' + resp.statusText);
1186 }
1187 if (typeof resp.data === "string") {
1188 try {
1189 resp.data = JSON.parse(resp.data);
1190 } catch (e) {
1191 throw new Error('Response is invalid json');
1192 }
1193 }
1194 return resp.data.result || resp.data;
1195 }).catch(function (e) {
1196 if (typeof e.response !== "undefined") {
1197 if (typeof e.response.data === 'object') {
1198 //400 error
1199 throw new Error(e.response.data.error);
1200 } else {
1201 //500 error
1202 var err = e.response.status + ' - ' + e.response.statusText;
1203 err += "\n" + api + " " + JSON.stringify(payload);
1204 throw new Error(err);
1205 }
1206 } else {
1207 throw new Error(e.message);
1208 }
1209 });
1210};
1211
1212HttpRequest.prototype.asyncRequest = function (method, api, payload, callback) {
1213 return this.request(method, api, payload).then(function (data) {
1214 callback(data);
1215 }).catch(function (err) {
1216 callback(err);
1217 });
1218};
1219
1220module.exports = HttpRequest;
1221
1222},{"axios":46}],5:[function(require,module,exports){
1223
1224"use strict";
1225
1226var API = require("./api.js");
1227var Admin = require("./admin.js");
1228
1229var Unit = require("./utils/unit.js");
1230
1231/**
1232 * Neb API library constructor.
1233 * @constructor
1234 * @param {Request} request - transport wrapper.
1235 */
1236var Neb = function (request) {
1237 if (request) {
1238 this._request = request;
1239 }
1240
1241 this.api = new API(this);
1242 this.admin = new Admin(this);
1243};
1244
1245Neb.prototype.setRequest = function (request) {
1246 this._request = request;
1247 this.api._setRequest(request);
1248 this.admin._setRequest(request);
1249};
1250
1251Neb.prototype.toBasic = Unit.toBasic;
1252Neb.prototype.fromBasic = Unit.fromBasic;
1253Neb.prototype.nasToBasic = Unit.nasToBasic;
1254
1255module.exports = Neb;
1256
1257},{"./admin.js":2,"./api.js":3,"./utils/unit.js":20}],6:[function(require,module,exports){
1258"use strict";
1259
1260var block = {
1261 timestamp: 0,
1262 height: 1,
1263 seed: "s"
1264};
1265
1266var transaction = {
1267 hash: "",
1268 from: "",
1269 to: "",
1270 value: "0",
1271 nonce: 1,
1272 timestamp: 0,
1273 gasPrice: "0",
1274 gasLimit: "0"
1275};
1276
1277var state = function () {};
1278
1279module.exports = {
1280 block: block,
1281 transaction: transaction,
1282 state: state
1283};
1284
1285},{}],7:[function(require,module,exports){
1286// Copyright (C) 2017 go-nebulas authors
1287//
1288// This file is part of the go-nebulas library.
1289//
1290// the go-nebulas library is free software: you can redistribute it and/or modify
1291// it under the terms of the GNU General Public License as published by
1292// the Free Software Foundation, either version 3 of the License, or
1293// (at your option) any later version.
1294//
1295// the go-nebulas library is distributed in the hope that it will be useful,
1296// but WITHOUT ANY WARRANTY; without even the implied warranty of
1297// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1298// GNU General Public License for more details.
1299//
1300// You should have received a copy of the GNU General Public License
1301// along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>.
1302//
1303
1304'use strict';
1305
1306var Blockchain = function () {
1307 Object.defineProperty(this, "nativeBlockchain", {
1308 configurable: false,
1309 enumerable: false,
1310 get: function () {
1311 return _native_blockchain;
1312 }
1313 });
1314};
1315
1316Blockchain.prototype = {
1317 AccountAddress: 0x57,
1318 ContractAddress: 0x58,
1319
1320 blockParse: function (str) {
1321 this.block = JSON.parse(str);
1322 },
1323 transactionParse: function (str) {
1324 var tx = JSON.parse(str);
1325 if (tx != null) {
1326 var value = tx.value === undefined || tx.value.length === 0 ? "0" : tx.value;
1327 tx.value = new BigNumber(value);
1328 var gasPrice = tx.gasPrice === undefined || tx.gasPrice.length === 0 ? "0" : tx.gasPrice;
1329 tx.gasPrice = new BigNumber(gasPrice);
1330 var gasLimit = tx.gasLimit === undefined || tx.gasLimit.length === 0 ? "0" : tx.gasLimit;
1331 tx.gasLimit = new BigNumber(gasLimit);
1332 this.transaction = tx;
1333 }
1334 },
1335 transfer: function (address, value) {
1336 if (!(value instanceof BigNumber)) {
1337 value = new BigNumber(value);
1338 }
1339 var ret = this.nativeBlockchain.transfer(address, value.toString(10));
1340 return ret == 0;
1341 },
1342 verifyAddress: function (address) {
1343 return this.nativeBlockchain.verifyAddress(address);
1344 }
1345};
1346module.exports = new Blockchain();
1347
1348},{}],8:[function(require,module,exports){
1349// Copyright (C) 2017 go-nebulas authors
1350//
1351// This file is part of the go-nebulas library.
1352//
1353// the go-nebulas library is free software: you can redistribute it and/or modify
1354// it under the terms of the GNU General Public License as published by
1355// the Free Software Foundation, either version 3 of the License, or
1356// (at your option) any later version.
1357//
1358// the go-nebulas library is distributed in the hope that it will be useful,
1359// but WITHOUT ANY WARRANTY; without even the implied warranty of
1360// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1361// GNU General Public License for more details.
1362//
1363// You should have received a copy of the GNU General Public License
1364// along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>.
1365//
1366
1367'use strict';
1368
1369function Console() {}
1370
1371function log(...args) {
1372 var level = args.shift();
1373 if (typeof level != 'number') {
1374 throw 'level must be number.';
1375 }
1376
1377 var msg = '';
1378 for (var i = 0; i < args.length - 1; i++) {
1379 msg += format(args[i]) + ' ';
1380 }
1381 msg += format(args[args.length - 1]);
1382
1383 _native_log(level, msg);
1384}
1385
1386function format(obj) {
1387 if (typeof obj == 'object') {
1388 return JSON.stringify(obj);
1389 }
1390 return obj;
1391}
1392
1393[['debug', 1], ['warn', 2], ['info', 3], ['log', 3], ['error', 4]].forEach(function (val) {
1394 Console.prototype[val[0]] = log.bind(null, val[1]);
1395});
1396
1397module.exports = new Console();
1398module.exports.Console = Console;
1399
1400},{}],9:[function(require,module,exports){
1401// Copyright (C) 2017 go-nebulas authors
1402//
1403// This file is part of the go-nebulas library.
1404//
1405// the go-nebulas library is free software: you can redistribute it and/or modify
1406// it under the terms of the GNU General Public License as published by
1407// the Free Software Foundation, either version 3 of the License, or
1408// (at your option) any later version.
1409//
1410// the go-nebulas library is distributed in the hope that it will be useful,
1411// but WITHOUT ANY WARRANTY; without even the implied warranty of
1412// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1413// GNU General Public License for more details.
1414//
1415// You should have received a copy of the GNU General Public License
1416// along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>.
1417//
1418
1419'use strict';
1420
1421exports["Trigger"] = function (topic, data) {
1422 _native_event_trigger(topic, JSON.stringify(data));
1423};
1424
1425},{}],10:[function(require,module,exports){
1426// Copyright (C) 2017 go-nebulas authors
1427//
1428// This file is part of the go-nebulas library.
1429//
1430// the go-nebulas library is free software: you can redistribute it and/or modify
1431// it under the terms of the GNU General Public License as published by
1432// the Free Software Foundation, either version 3 of the License, or
1433// (at your option) any later version.
1434//
1435// the go-nebulas library is distributed in the hope that it will be useful,
1436// but WITHOUT ANY WARRANTY; without even the implied warranty of
1437// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1438// GNU General Public License for more details.
1439//
1440// You should have received a copy of the GNU General Public License
1441// along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>.
1442//
1443
1444'use strict';
1445
1446var fieldNameRe = /^[a-zA-Z_$][a-zA-Z0-9_]+$/;
1447
1448var combineStorageMapKey = function (fieldName, key) {
1449 return "@" + fieldName + "[" + key + "]";
1450};
1451
1452var applyMapDescriptor = function (obj, descriptor) {
1453 descriptor = Object.assign({
1454 stringify: JSON.stringify,
1455 parse: JSON.parse
1456 }, descriptor || {});
1457
1458 if (typeof descriptor.stringify !== 'function' || typeof descriptor.parse !== 'function') {
1459 throw new Error("descriptor.stringify and descriptor.parse must be function.");
1460 }
1461
1462 Object.defineProperty(obj, "stringify", {
1463 configurable: false,
1464 enumerable: false,
1465 get: function () {
1466 return descriptor.stringify;
1467 }
1468 });
1469
1470 Object.defineProperty(obj, "parse", {
1471 configurable: false,
1472 enumerable: false,
1473 get: function () {
1474 return descriptor.parse;
1475 }
1476 });
1477};
1478
1479var applyFieldDescriptor = function (obj, fieldName, descriptor) {
1480 descriptor = Object.assign({
1481 stringify: JSON.stringify,
1482 parse: JSON.parse
1483 }, descriptor || {});
1484
1485 if (typeof descriptor.stringify !== 'function' || typeof descriptor.parse !== 'function') {
1486 throw new Error("descriptor.stringify and descriptor.parse must be function.");
1487 }
1488
1489 Object.defineProperty(obj, "__stringify__" + fieldName, {
1490 configurable: false,
1491 enumerable: false,
1492 get: function () {
1493 return descriptor.stringify;
1494 }
1495 });
1496
1497 Object.defineProperty(obj, "__parse__" + fieldName, {
1498 configurable: false,
1499 enumerable: false,
1500 get: function () {
1501 return descriptor.parse;
1502 }
1503 });
1504};
1505
1506var ContractStorage = function (handler) {
1507 var ns = new NativeStorage(handler);
1508 Object.defineProperty(this, "nativeStorage", {
1509 configurable: false,
1510 enumerable: false,
1511 get: function () {
1512 return ns;
1513 }
1514 });
1515};
1516
1517var StorageMap = function (contractStorage, fieldName, descriptor) {
1518 if (!contractStorage instanceof ContractStorage) {
1519 throw new Error("StorageMap only accept instance of ContractStorage");
1520 }
1521
1522 if (typeof fieldName !== "string" || fieldNameRe.exec(fieldName) == null) {
1523 throw new Error("StorageMap fieldName must match regex /^[a-zA-Z_$].*$/");
1524 }
1525
1526 Object.defineProperty(this, "contractStorage", {
1527 configurable: false,
1528 enumerable: false,
1529 get: function () {
1530 return contractStorage;
1531 }
1532 });
1533 Object.defineProperty(this, "fieldName", {
1534 configurable: false,
1535 enumerable: false,
1536 get: function () {
1537 return fieldName;
1538 }
1539 });
1540
1541 applyMapDescriptor(this, descriptor);
1542};
1543
1544StorageMap.prototype = {
1545 del: function (key) {
1546 return this.contractStorage.del(combineStorageMapKey(this.fieldName, key));
1547 },
1548 get: function (key) {
1549 var val = this.contractStorage.rawGet(combineStorageMapKey(this.fieldName, key));
1550 if (val != null) {
1551 val = this.parse(val);
1552 }
1553 return val;
1554 },
1555 set: function (key, value) {
1556 var val = this.stringify(value);
1557 return this.contractStorage.rawSet(combineStorageMapKey(this.fieldName, key), val);
1558 }
1559};
1560StorageMap.prototype.put = StorageMap.prototype.set;
1561StorageMap.prototype.delete = StorageMap.prototype.del;
1562
1563ContractStorage.prototype = {
1564 rawGet: function (key) {
1565 return this.nativeStorage.get(key);
1566 },
1567 rawSet: function (key, value) {
1568 var ret = this.nativeStorage.set(key, value);
1569 if (ret != 0) {
1570 throw new Error("set key " + key + " failed.");
1571 }
1572 return ret;
1573 },
1574 del: function (key) {
1575 var ret = this.nativeStorage.del(key);
1576 if (ret != 0) {
1577 throw new Error("del key " + key + " failed.");
1578 }
1579 return ret;
1580 },
1581 get: function (key) {
1582 var val = this.rawGet(key);
1583 if (val != null) {
1584 val = JSON.parse(val);
1585 }
1586 return val;
1587 },
1588 set: function (key, value) {
1589 return this.rawSet(key, JSON.stringify(value));
1590 },
1591 defineProperty: function (obj, fieldName, descriptor) {
1592 if (!obj || !fieldName) {
1593 throw new Error("defineProperty requires at least two parameters.");
1594 }
1595 var $this = this;
1596 Object.defineProperty(obj, fieldName, {
1597 configurable: false,
1598 enumerable: true,
1599 get: function () {
1600 var val = $this.rawGet(fieldName);
1601 if (val != null) {
1602 val = obj["__parse__" + fieldName](val);
1603 }
1604 return val;
1605 },
1606 set: function (val) {
1607 val = obj["__stringify__" + fieldName](val);
1608 return $this.rawSet(fieldName, val);
1609 }
1610 });
1611 applyFieldDescriptor(obj, fieldName, descriptor);
1612 return this;
1613 },
1614 defineProperties: function (obj, props) {
1615 if (!obj || !props) {
1616 throw new Error("defineProperties requires two parameters.");
1617 }
1618
1619 for (const fieldName in props) {
1620 this.defineProperty(obj, fieldName, props[fieldName]);
1621 }
1622 return this;
1623 },
1624 defineMapProperty: function (obj, fieldName, descriptor) {
1625 if (!obj || !fieldName) {
1626 throw new Error("defineMapProperty requires two parameters.");
1627 }
1628
1629 var mapObj = new StorageMap(this, fieldName, descriptor);
1630 Object.defineProperty(obj, fieldName, {
1631 configurable: false,
1632 enumerable: true,
1633 get: function () {
1634 return mapObj;
1635 }
1636 });
1637 return this;
1638 },
1639 defineMapProperties: function (obj, props) {
1640 if (!obj || !props) {
1641 throw new Error("defineMapProperties requires two parameters.");
1642 }
1643
1644 for (const fieldName in props) {
1645 this.defineMapProperty(obj, fieldName, props[fieldName]);
1646 }
1647 return this;
1648 }
1649};
1650
1651ContractStorage.prototype.put = ContractStorage.prototype.set;
1652ContractStorage.prototype.delete = ContractStorage.prototype.del;
1653
1654var lcs = new ContractStorage(_native_storage_handlers.lcs);
1655var gcs = new ContractStorage(_native_storage_handlers.gcs);
1656var obj = { ContractStorage: ContractStorage };
1657Object.defineProperty(obj, "lcs", {
1658 configurable: false,
1659 enumerable: false,
1660 get: function () {
1661 return lcs;
1662 }
1663});
1664
1665Object.defineProperty(obj, "gcs", {
1666 configurable: false,
1667 enumerable: false,
1668 get: function () {
1669 return gcs;
1670 }
1671});
1672
1673module.exports = Object.freeze(obj);
1674
1675},{}],11:[function(require,module,exports){
1676(function (global,__dirname){
1677
1678
1679global;
1680
1681if (typeof window !== "undefined") {
1682 global = window;
1683}
1684
1685if (typeof localStorage === "undefined" || localStorage === null) {
1686 var path = require("path");
1687 var storageFile = path.join(__dirname, "./.storage");
1688 var LocalStorage = require('node-localstorage').LocalStorage;
1689 global.localStorage = new LocalStorage(storageFile);
1690}
1691
1692global.context = require("./context");
1693global._native_blockchain = require("./native/blockchain");
1694global._native_log = require("./native/log");
1695global._native_event_trigger = require("./native/event");
1696global._native_storage_handlers = require("./native/storage").handlers;
1697global.NativeStorage = require("./native/storage").NativeStorage;
1698
1699global.nativeConsole = global.console;
1700global.console = require("./libs/console");
1701global.ContractStorage = require("./libs/storage");
1702global.LocalContractStorage = global.ContractStorage.lcs;
1703// global.GlobalContractStorage = ContractStorage.gcs;
1704global.BigNumber = require("bignumber.js");
1705global.Blockchain = require("./libs/blockchain");
1706global.Event = require("./libs/event");
1707
1708// global.Date = require('./libs/date');
1709// global.Math.random = require('./libs/random');
1710// global.BigNumber.random = global.Math.random;
1711
1712module.exports = {
1713 context: global.context
1714};
1715
1716}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},"/lib/nvm")
1717},{"./context":6,"./libs/blockchain":7,"./libs/console":8,"./libs/event":9,"./libs/storage":10,"./native/blockchain":12,"./native/event":13,"./native/log":14,"./native/storage":15,"bignumber.js":73,"node-localstorage":"node-localstorage.js","path":183}],12:[function(require,module,exports){
1718"use strict";
1719
1720var Account = require("../../account");
1721
1722var transfer = function (to, value) {
1723 // TODO: mock the transfer func in nebulas
1724 return 0;
1725};
1726
1727var verifyAddress = function (address) {
1728 return Account.isValidAddress(address);
1729};
1730
1731module.exports = {
1732 transfer: transfer,
1733 verifyAddress: verifyAddress
1734};
1735
1736},{"../../account":1}],13:[function(require,module,exports){
1737"use strict";
1738
1739var trigger = function (topic, data) {
1740 var event = {
1741 Topic: topic,
1742 Data: data
1743 };
1744 var key = context.transaction.hash;
1745 var events = localStorage.getItem(key);
1746 if (events === null || typeof events === "undefined") {
1747 events = new Array();
1748 } else {
1749 events = Array.from(events);
1750 }
1751 events.push(event);
1752 localStorage.setItem(key, events);
1753};
1754
1755module.exports = trigger;
1756
1757},{}],14:[function(require,module,exports){
1758"use strict";
1759
1760var log = function (level, msg) {
1761 var levelStr;
1762 switch (level) {
1763 case 1:
1764 levelStr = "debug";
1765 case 2:
1766 levelStr = "warn";
1767 case 3:
1768 levelStr = "info";
1769 case 4:
1770 levelStr = "error";
1771 default:
1772 levelStr = "info";
1773 }
1774 var log = levelStr + ":" + msg;
1775 nativeConsole.log(log);
1776};
1777
1778module.exports = log;
1779
1780},{}],15:[function(require,module,exports){
1781"use strict";
1782
1783var handlers = {
1784 lcs: 1,
1785 gcs: 2
1786};
1787
1788var NativeStorage = function (handler) {
1789 this.handler = handler;
1790};
1791
1792NativeStorage.prototype = {
1793 get: function (key) {
1794 return localStorage.getItem(key);
1795 },
1796 set: function (key, value) {
1797 localStorage.setItem(key, value);
1798 return 0;
1799 },
1800 del: function (key) {
1801 localStorage.removeItem(key);
1802 return 0;
1803 }
1804};
1805
1806module.exports = {
1807 handlers: handlers,
1808 NativeStorage: NativeStorage
1809};
1810
1811},{}],16:[function(require,module,exports){
1812"use strict";
1813
1814var extend = require('extend');
1815var native = require("./native");
1816
1817var funcRegex = new RegExp("^[a-zA-Z$][A-Za-z0-9_$]*$");
1818
1819var NVM = function (block, transaction) {
1820 extend(native.context.block, block);
1821 extend(native.context.transaction, transaction);
1822 // console.log("block:", native.context.block);
1823 // console.log("tx:", native.context.transaction);
1824};
1825
1826NVM.prototype = {
1827 deploy: function (source, args) {
1828 return this.run(source, "init", args);
1829 },
1830 call: function (source, func, args) {
1831 if (funcRegex.test(func)) {
1832 return this.run(source, func, args);
1833 } else {
1834 throw new Error("invalid func");
1835 }
1836 },
1837 run: function (source, func, args) {
1838 Blockchain.blockParse(JSON.stringify(native.context.block));
1839 Blockchain.transactionParse(JSON.stringify(native.context.transaction));
1840 var Contract = eval(source);
1841 // console.log("contract:", Contract);
1842 var contract = new Contract();
1843 if (args === undefined || args.length === 0) {
1844 args = "[]";
1845 }
1846 if (contract[func] != undefined) {
1847 return contract[func].apply(contract, JSON.parse(args));
1848 } else {
1849 throw new Error("function not found");
1850 }
1851 }
1852};
1853
1854module.exports = NVM;
1855
1856},{"./native":11,"extend":145}],17:[function(require,module,exports){
1857module.exports={
1858 "nested": {
1859 "corepb": {
1860 "nested": {
1861 "Data": {
1862 "fields": {
1863 "type": {
1864 "type": "string",
1865 "id": 1
1866 },
1867 "payload": {
1868 "type": "bytes",
1869 "id": 2
1870 }
1871 }
1872 },
1873 "Transaction": {
1874 "fields": {
1875 "hash": {
1876 "type": "bytes",
1877 "id": 1
1878 },
1879 "from": {
1880 "type": "bytes",
1881 "id": 2
1882 },
1883 "to": {
1884 "type": "bytes",
1885 "id": 3
1886 },
1887 "value": {
1888 "type": "bytes",
1889 "id": 4
1890 },
1891 "nonce": {
1892 "type": "uint64",
1893 "id": 5
1894 },
1895 "timestamp": {
1896 "type": "int64",
1897 "id": 6
1898 },
1899 "data": {
1900 "type": "Data",
1901 "id": 7
1902 },
1903 "chainId": {
1904 "type": "uint32",
1905 "id": 8
1906 },
1907 "gasPrice": {
1908 "type": "bytes",
1909 "id": 9
1910 },
1911 "gasLimit": {
1912 "type": "bytes",
1913 "id": 10
1914 },
1915 "alg": {
1916 "type": "uint32",
1917 "id": 11
1918 },
1919 "sign": {
1920 "type": "bytes",
1921 "id": 12
1922 }
1923 }
1924 }
1925 }
1926 }
1927 }
1928}
1929},{}],18:[function(require,module,exports){
1930"use strict";
1931
1932var protobuf = require('protobufjs');
1933var utils = require('./utils/utils.js');
1934var cryptoUtils = require('./utils/crypto-utils.js');
1935var account = require("./account.js");
1936var htmlescape = require('htmlescape');
1937var BigNumber = require('bignumber.js');
1938
1939var SECP256K1 = 1;
1940var root = protobuf.Root.fromJSON(require("./transaction.json"));
1941
1942var TxPayloadBinaryType = "binary";
1943var TxPayloadDeployType = "deploy";
1944var TxPayloadCallType = "call";
1945
1946/**
1947 * @typedef TransactionInit
1948 * @example
1949 * var acc = Account.NewAccount();
1950 *
1951 * var tx = new Transaction({
1952 * chainID: 1,
1953 * from: acc,
1954 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
1955 * value: 10,
1956 * nonce: 12,
1957 * gasPrice: 1000000,
1958 * gasLimit: 2000000
1959 * });
1960 */
1961
1962/**
1963 * Represent of smart contract payload data.
1964 *
1965 * @typedef {Object} Contract
1966 * @property {String} source - Contract source code for deploy contract.
1967 * @property {String} sourceType - Contract source type for deploy contract. Currently support js and ts.
1968 * @property {String} args - The params of contract. The args content is JSON string of parameters array.
1969 * @property {String} function - The contract call function.
1970 * @property {Buffer} binary - Binary contract representation.
1971 *
1972 * @see [Create own smart contract in Nebulas.]{@link https://github.com/nebulasio/wiki/blob/master/tutorials/%5BEnglish%5D%20Nebulas%20101%20-%2003%20Smart%20Contracts%20JavaScript.md}
1973 * @see [More about transaction parameters.]{@link https://github.com/nebulasio/wiki/blob/c3f5ce8908c80e9104e3b512a7fdfd75f16ac38c/rpc.md#sendtransaction}
1974 *
1975 * @example
1976 * // It's example of possible fields values.
1977 * // For deploy, and execute smart contracts follow this link - https://github.com/nebulasio/wiki/blob/master/tutorials/%5BEnglish%5D%20Nebulas%20101%20-%2003%20Smart%20Contracts%20JavaScript.md
1978 * {
1979 * 'source': '"use strict";var DepositeContent=function(t){if(t){let n=JSON.parse(t);' +
1980 * 'this.balance=new BigNumber(n.balance),this.expiryHeight=new BigNumber(n.expiryHeight)' +
1981 * '}else this.balance=new BigNumber(0),this.expiryHeight=new BigNumber(0)};' +
1982 * 'DepositeContent.prototype={toString:function(){return JSON.stringify(this)}};' +
1983 * 'var BankVaultContract=function(){LocalContractStorage.defineMapProperty(this,"bankVault",' +
1984 * '{parse:function(t){return new DepositeContent(t)},stringify:function(t){return t.toString()}})};' +
1985 * 'BankVaultContract.prototype={init:function(){},save:function(t){var n=Blockchain.transaction.from,' +
1986 * 'e=Blockchain.transaction.value,a=new BigNumber(Blockchain.block.height),r=this.bankVault.get(n);' +
1987 * 'r&&(e=e.plus(r.balance));var i=new DepositeContent;i.balance=e,i.expiryHeight=a.plus(t),' +
1988 * 'this.bankVault.put(n,i)},takeout:function(t){var n=Blockchain.transaction.from,' +
1989 * 'e=new BigNumber(Blockchain.block.height),a=new BigNumber(t),r=this.bankVault.get(n);' +
1990 * 'if(!r)throw new Error("No deposit before.");if(e.lt(r.expiryHeight))throw new Error("Can't takeout before expiryHeight.");' +
1991 * 'if(a.gt(r.balance))throw new Error("Insufficient balance.");if(0!=Blockchain.transfer(n,a))throw new Error("transfer failed.");' +
1992 * 'Event.Trigger("BankVault",{Transfer:{from:Blockchain.transaction.to,to:n,value:a.toString()}}),' +
1993 * 'r.balance=r.balance.sub(a),this.bankVault.put(n,r)},balanceOf:function(){var t=Blockchain.transaction.from;' +
1994 * 'return this.bankVault.get(t)}},module.exports=BankVaultContract;',
1995 * 'sourceType': 'js',
1996 * 'args': '[0]',
1997 * 'function': 'save'
1998 * }
1999 */
2000
2001/**
2002 * Represent Transaction parameters
2003 *
2004 * @typedef {Object} TransactionOptions
2005 * @property {Number} options.chainID - Transaction chain id.
2006 * @property {HexString} options.from - Hex string of the sender account addresss..
2007 * @property {HexString} options.to - Hex string of the receiver account addresss..
2008 * @property {Number} options.value - Value of transaction.
2009 * @property {Number} options.nonce - Transaction nonce.
2010 * @property {Number} options.gasPrice - Gas price. The unit is 10^-18 NAS.
2011 * @property {Number} options.gasLimit - Transaction gas limit.
2012 * @property {Contract} [options.contract]
2013 *
2014 * @example
2015 * {
2016* chainID: 1,
2017* from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
2018* to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2019* value: 10,
2020* nonce: 12,
2021* gasPrice: 1000000,
2022* gasLimit: 2000000
2023* }
2024 */
2025
2026/**
2027 * Transaction constructor.
2028 * Class encapsulate main operation with transactions.
2029 * @see [For more information about parameters, follow this link]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#sendrawtransaction}
2030 * @constructor
2031 *
2032 * @param {TransactionOptions} options - Transaction options.
2033 *
2034 * @see [Transaction tutorial.]{@link https://github.com/nebulasio/wiki/blob/master/tutorials/%5BEnglish%5D%20Nebulas%20101%20-%2002%20Transaction.md}
2035 * @see [Create own smart contract in Nebulas.]{@link https://github.com/nebulasio/wiki/blob/master/tutorials/%5BEnglish%5D%20Nebulas%20101%20-%2003%20Smart%20Contracts%20JavaScript.md}
2036 * @see [More about transaction parameters.]{@link https://github.com/nebulasio/wiki/blob/c3f5ce8908c80e9104e3b512a7fdfd75f16ac38c/rpc.md#sendtransaction}
2037 *
2038 * @example
2039 * var acc = Account.NewAccount();
2040 *
2041 * var tx = new Transaction({
2042 * chainID: 1,
2043 * from: acc,
2044 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2045 * value: 10,
2046 * nonce: 12,
2047 * gasPrice: 1000000,
2048 * gasLimit: 2000000,
2049 * contract: {
2050 * function: "save",
2051 * args: "[0]"
2052 * }
2053 * });
2054 *
2055 */
2056var Transaction = function (options) {
2057 if (arguments.length > 0) {
2058 options = utils.argumentsToObject(['chainID', 'from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract'], arguments);
2059
2060 this.chainID = options.chainID;
2061 this.from = account.fromAddress(options.from);
2062 this.to = account.fromAddress(options.to);
2063 this.value = utils.toBigNumber(options.value);
2064 if (!this.value.isInteger()) throw new Error("Invalid value! The minimum unit is wei (1^-18nas)");
2065 this.nonce = parseInt(options.nonce); // An error will be thrown is nonce is string. Error: "nonce: integer|Long expected"
2066 this.timestamp = Math.floor(new Date().getTime() / 1000);
2067 this.contract = options.contract;
2068 this.gasPrice = utils.toBigNumber(options.gasPrice);
2069 this.gasLimit = utils.toBigNumber(options.gasLimit);
2070
2071 this.data = parseContract(this.contract);
2072 if (this.gasPrice.lessThanOrEqualTo(0)) {
2073 this.gasPrice = new BigNumber(1000000);
2074 }
2075
2076 if (this.gasLimit.lessThanOrEqualTo(0)) {
2077 this.gasLimit = new BigNumber(20000);
2078 }
2079 }
2080 this.signErrorMessage = "You should sign transaction before this operation.";
2081};
2082
2083var parseContract = function (obj) {
2084 /*jshint maxcomplexity:7 */
2085
2086 var payloadType, payload;
2087 if (obj && utils.isString(obj.source) && obj.source.length > 0) {
2088 payloadType = TxPayloadDeployType;
2089 payload = {
2090 SourceType: obj.sourceType,
2091 Source: obj.source,
2092 Args: obj.args
2093 };
2094 } else if (obj && utils.isString(obj.function) && obj.function.length > 0) {
2095 payloadType = TxPayloadCallType;
2096 payload = {
2097 Function: obj.function,
2098 Args: obj.args
2099 };
2100 } else {
2101 payloadType = TxPayloadBinaryType;
2102 if (obj) {
2103 payload = {
2104 Data: cryptoUtils.toBuffer(obj.binary)
2105 };
2106 }
2107 }
2108 var payloadData = utils.isNull(payload) ? null : cryptoUtils.toBuffer(htmlescape(payload));
2109
2110 return { type: payloadType, payload: payloadData };
2111};
2112
2113/**
2114 * Transaction recover method.
2115 *
2116 * @static
2117 * @param {String/Hash} message - Transaction hash.
2118 * @param {String/Hash} signature - Transaction sign
2119 *
2120 * @return {Hash} Transaction from address public key.
2121 *
2122 * @example
2123 * var pubKey = Transaction.recover("82bc718bfd24392b3872eb5a874927a327ab19b156c5584bd5f93b08fab5b1a2", "003d4064f16cbc72367b0fa3870bdcd1044bdb166019d87cdaac6dcfb8c09ac9471570e5b2e1dc249a8642ba67e585e3f43e6383c3b87532f5eb1fe2e718a5ab00");
2124 */
2125Transaction.recover = function (message, signature) {
2126 message = cryptoUtils.toBuffer(message);
2127 var signBuf = cryptoUtils.toBuffer(signature);
2128 var sign = signBuf.slice(0, 64);
2129 var recovery = signBuf.readUIntBE(64, 1);
2130 if (recovery > 27) {
2131 recovery = recovery - 27;
2132 }
2133 var compressed = false;
2134 var pub = cryptoUtils.recover(message, sign, recovery, compressed);
2135 return pub;
2136};
2137
2138/**
2139 * Transaction fromProto method, parse rawData to transaction object.
2140 *
2141 * @static
2142 * @param {String/Hash} data - Transaction raw data.
2143 *
2144 * @return {Object} Transaction object.
2145 *
2146 * @example
2147 * var tx = Transaction.fromProto("EhjZTY/gKLhWVVMZ+xoY9GiHOHJcxhc4uxkaGNlNj+AouFZVUxn7Ghj0aIc4clzGFzi7GSIQAAAAAAAAAAAN4Lazp2QAACgBMPCz6tUFOggKBmJpbmFyeUDpB0oQAAAAAAAAAAAAAAAAAA9CQFIQAAAAAAAAAAAAAAAAAABOIA==");
2148 */
2149Transaction.fromProto = function (data) {
2150 var tx = new Transaction();
2151 tx.fromProto(data);
2152 return tx;
2153};
2154
2155Transaction.prototype = {
2156 /**
2157 * Convert transaction to hash by SHA3-256 algorithm.
2158 *
2159 * @return {Hash} hash of Transaction.
2160 *
2161 * @example
2162 * var acc = Account.NewAccount();
2163 *
2164 * var tx = new Transaction({
2165 * chainID: 1,
2166 * from: acc,
2167 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2168 * value: 10,
2169 * nonce: 12,
2170 * gasPrice: 1000000,
2171 * gasLimit: 2000000
2172 * });
2173 * var txHash = tx.hashTransaction();
2174 * //Uint8Array(32) [211, 213, 102, 103, 23, 231, 246, 141, 20, 202, 210, 25, 92, 142, 162, 242, 232, 95, 44, 239, 45, 57, 241, 61, 34, 2, 213, 160, 17, 207, 75, 40]
2175 */
2176 hashTransaction: function () {
2177 var Data = root.lookup("corepb.Data");
2178 var err = Data.verify(this.data);
2179 if (err) {
2180 throw new Error(err);
2181 }
2182 var data = Data.create(this.data);
2183 var dataBuffer = Data.encode(data).finish();
2184 var hash = cryptoUtils.sha3(this.from.getAddress(), this.to.getAddress(), cryptoUtils.padToBigEndian(this.value, 128), cryptoUtils.padToBigEndian(this.nonce, 64), cryptoUtils.padToBigEndian(this.timestamp, 64), dataBuffer, cryptoUtils.padToBigEndian(this.chainID, 32), cryptoUtils.padToBigEndian(this.gasPrice, 128), cryptoUtils.padToBigEndian(this.gasLimit, 128));
2185 return hash;
2186 },
2187 /**
2188 * Sign transaction with the specified algorithm.
2189 *
2190 * @example
2191 * var acc = Account.NewAccount();
2192 *
2193 * var tx = new Transaction({
2194 * chainID: 1,
2195 * from: acc,
2196 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2197 * value: 10,
2198 * nonce: 12,
2199 * gasPrice: 1000000,
2200 * gasLimit: 2000000
2201 * });
2202 * tx.signTransaction();
2203 */
2204 signTransaction: function () {
2205 if (this.from.getPrivateKey() !== null) {
2206 this.hash = this.hashTransaction();
2207 this.alg = SECP256K1;
2208 this.sign = cryptoUtils.sign(this.hash, this.from.getPrivateKey());
2209 } else {
2210 throw new Error("transaction from address's private key is invalid");
2211 }
2212 },
2213 /**
2214 * Conver transaction data to plain JavaScript object.
2215 *
2216 * @return {Object} Plain JavaScript object with Transaction fields.
2217 * @example
2218 * var acc = Account.NewAccount();
2219 * var tx = new Transaction({
2220 * chainID: 1,
2221 * from: acc,
2222 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2223 * value: 10,
2224 * nonce: 12,
2225 * gasPrice: 1000000,
2226 * gasLimit: 2000000
2227 * });
2228 * txData = tx.toPlainObject();
2229 * // {chainID: 1001, from: "n1USdDKeZXQYubA44W2ZVUdW1cjiJuqswxp", to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", value: 1000000000000000000, nonce: 1, …}
2230 */
2231 toPlainObject: function () {
2232 return {
2233 chainID: this.chainID,
2234 from: this.from.getAddressString(),
2235 to: this.to.getAddressString(),
2236 value: utils.isBigNumber(this.value) ? this.value.toNumber() : this.value,
2237 nonce: this.nonce,
2238 gasPrice: utils.isBigNumber(this.gasPrice) ? this.gasPrice.toNumber() : this.gasPrice,
2239 gasLimit: utils.isBigNumber(this.gasLimit) ? this.gasLimit.toNumber() : this.gasLimit,
2240 contract: this.contract
2241 };
2242 },
2243 /**
2244 * Convert transaction to JSON string.
2245 * </br><b>Note:</b> Transaction should be [sign]{@link Transaction#signTransaction} before converting.
2246 *
2247 * @return {String} JSON stringify of transaction data.
2248 * @example
2249 * var acc = Account.NewAccount();
2250 *
2251 * var tx = new Transaction({
2252 * chainID: 1,
2253 * from: acc,
2254 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2255 * value: 10,
2256 * nonce: 12,
2257 * gasPrice: 1000000,
2258 * gasLimit: 2000000
2259 * });
2260 * tx.signTransaction();
2261 * var txHash = tx.toString();
2262 * // "{"chainID":1001,"from":"n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5","to":"n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17","value":"1000000000000000000","nonce":1,"timestamp":1521905294,"data":{"payloadType":"binary","payload":null},"gasPrice":"1000000","gasLimit":"20000","hash":"f52668b853dd476fd309f21b22ade6bb468262f55402965c3460175b10cb2f20","alg":1,"sign":"cf30d5f61e67bbeb73bb9724ba5ba3744dcbc995521c62f9b5f43efabd9b82f10aaadf19a9cdb05f039d8bf074849ef4b508905bcdea76ae57e464e79c958fa900"}"
2263 */
2264 toString: function () {
2265 if (!this.sign) {
2266 throw new Error(this.signErrorMessage);
2267 }
2268 var payload = utils.isNull(this.data.payload) ? null : JSON.parse(this.data.payload.toString());
2269 var tx = {
2270 chainID: this.chainID,
2271 from: this.from.getAddressString(),
2272 to: this.to.getAddressString(),
2273 value: this.value.toString(10),
2274 nonce: this.nonce,
2275 timestamp: this.timestamp,
2276 data: { payloadType: this.data.type, payload: payload },
2277 gasPrice: this.gasPrice.toString(10),
2278 gasLimit: this.gasLimit.toString(10),
2279 hash: this.hash.toString("hex"),
2280 alg: this.alg,
2281 sign: this.sign.toString("hex")
2282
2283 };
2284 return JSON.stringify(tx);
2285 },
2286 /**
2287 * Convert transaction to Protobuf format.
2288 * </br><b>Note:</b> Transaction should be [sign]{@link Transaction#signTransaction} before converting.
2289 *
2290 * @return {Buffer} Transaction data in Protobuf format
2291 *
2292 * @example
2293 * var acc = Account.NewAccount();
2294 *
2295 * var tx = new Transaction({
2296 * chainID: 1,
2297 * from: acc,
2298 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2299 * value: 10,
2300 * nonce: 12,
2301 * gasPrice: 1000000,
2302 * gasLimit: 2000000
2303 * });
2304 * tx.signTransaction();
2305 * var txHash = tx.toProto();
2306 * // Uint8Array(127)
2307 */
2308 toProto: function () {
2309 if (!this.sign) {
2310 throw new Error(this.signErrorMessage);
2311 }
2312 var Data = root.lookup("corepb.Data");
2313 var err = Data.verify(this.data);
2314 if (err) {
2315 throw err;
2316 }
2317 var data = Data.create(this.data);
2318
2319 var TransactionProto = root.lookup("corepb.Transaction");
2320
2321 var txData = {
2322 hash: this.hash,
2323 from: this.from.getAddress(),
2324 to: this.to.getAddress(),
2325 value: cryptoUtils.padToBigEndian(this.value, 128),
2326 nonce: this.nonce,
2327 timestamp: this.timestamp,
2328 data: data,
2329 chainId: this.chainID,
2330 gasPrice: cryptoUtils.padToBigEndian(this.gasPrice, 128),
2331 gasLimit: cryptoUtils.padToBigEndian(this.gasLimit, 128),
2332 alg: this.alg,
2333 sign: this.sign
2334 };
2335
2336 err = TransactionProto.verify(txData);
2337 if (err) {
2338 throw err;
2339 }
2340 var tx = TransactionProto.create(txData);
2341
2342 var txBuffer = TransactionProto.encode(tx).finish();
2343 return txBuffer;
2344 },
2345 /**
2346 * Convert transaction to Protobuf hash string.
2347 * </br><b>Note:</b> Transaction should be [sign]{@link Transaction#signTransaction} before converting.
2348 *
2349 * @return {Base64} Transaction string.
2350 *
2351 * @example
2352 * var acc = Account.NewAccount();
2353 *
2354 * var tx = new Transaction({
2355 * chainID: 1,
2356 * from: acc,
2357 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2358 * value: 10,
2359 * nonce: 12,
2360 * gasPrice: 1000000,
2361 * gasLimit: 2000000
2362 * });
2363 * tx.signTransaction();
2364 * var txHash = tx.toProtoString();
2365 * // "EhjZTY/gKLhWVVMZ+xoY9GiHOHJcxhc4uxkaGNlNj+AouFZVUxn7Ghj0aIc4clzGFzi7GSIQAAAAAAAAAAAN4Lazp2QAACgBMPCz6tUFOggKBmJpbmFyeUDpB0oQAAAAAAAAAAAAAAAAAA9CQFIQAAAAAAAAAAAAAAAAAABOIA=="
2366 */
2367 toProtoString: function () {
2368 var txBuffer = this.toProto();
2369 return protobuf.util.base64.encode(txBuffer, 0, txBuffer.length);
2370 },
2371 /**
2372 * Restore Transaction from Protobuf format.
2373 * @property {Buffer|String} data - Buffer or stringify Buffer.
2374 *
2375 * @return {Transaction} Restored transaction.
2376 *
2377 * @example
2378 * var acc = Account.NewAccount();
2379 *
2380 * var tx = new Transaction({
2381 * chainID: 1,
2382 * from: acc,
2383 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2384 * value: 10,
2385 * nonce: 12,
2386 * gasPrice: 1000000,
2387 * gasLimit: 2000000
2388 * });
2389 * var tx = tx.fromProto("EhjZTY/gKLhWVVMZ+xoY9GiHOHJcxhc4uxkaGNlNj+AouFZVUxn7Ghj0aIc4clzGFzi7GSIQAAAAAAAAAAAN4Lazp2QAACgBMPCz6tUFOggKBmJpbmFyeUDpB0oQAAAAAAAAAAAAAAAAAA9CQFIQAAAAAAAAAAAAAAAAAABOIA==");
2390 */
2391 fromProto: function (data) {
2392
2393 var txBuffer;
2394 if (utils.isString(data)) {
2395 txBuffer = new Array(protobuf.util.base64.length(data));
2396 protobuf.util.base64.decode(data, txBuffer, 0);
2397 } else {
2398 txBuffer = data;
2399 }
2400
2401 var TransactionProto = root.lookup("corepb.Transaction");
2402 var txProto = TransactionProto.decode(txBuffer);
2403
2404 this.hash = cryptoUtils.toBuffer(txProto.hash);
2405 this.from = account.fromAddress(txProto.from);
2406 this.to = account.fromAddress(txProto.to);
2407 this.value = utils.toBigNumber("0x" + cryptoUtils.toBuffer(txProto.value).toString("hex"));
2408 // long number is object, should convert to int
2409 this.nonce = parseInt(txProto.nonce.toString());
2410 this.timestamp = parseInt(txProto.timestamp.toString());
2411 this.data = txProto.data;
2412 if (this.data.payload.length === 0) {
2413 this.data.payload = null;
2414 }
2415 this.chainID = txProto.chainId;
2416 this.gasPrice = utils.toBigNumber("0x" + cryptoUtils.toBuffer(txProto.gasPrice).toString("hex"));
2417 this.gasLimit = utils.toBigNumber("0x" + cryptoUtils.toBuffer(txProto.gasLimit).toString("hex"));
2418 this.alg = txProto.alg;
2419 this.sign = cryptoUtils.toBuffer(txProto.sign);
2420
2421 return this;
2422 }
2423};
2424
2425module.exports = Transaction;
2426
2427},{"./account.js":1,"./transaction.json":17,"./utils/crypto-utils.js":19,"./utils/utils.js":21,"bignumber.js":73,"htmlescape":160,"protobufjs":191}],19:[function(require,module,exports){
2428 2
2429"use strict"; 3"use strict";
2430 4
@@ -2640,131 +214,82 @@ module.exports = {
2640 recover: recover 214 recover: recover
2641}; 215};
2642 216
2643},{"./utils.js":21,"crypto":116,"jssha":166,"keccak":167,"ripemd160":246,"safe-buffer":247,"scryptsy":248,"secp256k1":249,"uuid":266}],20:[function(require,module,exports){ 217},{"./utils.js":2,"crypto":62,"jssha":110,"keccak":111,"ripemd160":155,"safe-buffer":156,"scryptsy":157,"secp256k1":158,"uuid":175}],2:[function(require,module,exports){
2644
2645"use strict";
2646
2647var BigNumber = require('bignumber.js');
2648var utils = require('./utils.js');
2649
2650var unitMap = {
2651 'none': '0',
2652 'None': '0',
2653 'wei': '1',
2654 'Wei': '1',
2655 'kwei': '1000',
2656 'Kwei': '1000',
2657 'mwei': '1000000',
2658 'Mwei': '1000000',
2659 'gwei': '1000000000',
2660 'Gwei': '1000000000',
2661 'nas': '1000000000000000000',
2662 'NAS': '1000000000000000000'
2663};
2664
2665var unitValue = function (unit) {
2666 unit = unit ? unit.toLowerCase() : 'nas';
2667 var unitValue = unitMap[unit];
2668 if (unitValue === undefined) {
2669 throw new Error('The unit undefined, please use the following units:' + JSON.stringify(unitMap, null, 2));
2670 }
2671 return new BigNumber(unitValue, 10);
2672};
2673
2674var toBasic = function (number, unit) {
2675 return utils.toBigNumber(number).times(unitValue(unit));
2676};
2677
2678var fromBasic = function (number, unit) {
2679 return utils.toBigNumber(number).dividedBy(unitValue(unit));
2680};
2681
2682var nasToBasic = function (number) {
2683 return utils.toBigNumber(number).times(unitValue("nas"));
2684};
2685
2686module.exports = {
2687 toBasic: toBasic,
2688 fromBasic: fromBasic,
2689 nasToBasic: nasToBasic
2690};
2691
2692},{"./utils.js":21,"bignumber.js":73}],21:[function(require,module,exports){
2693 218
2694"use strict"; 219"use strict";
2695 220
2696var BigNumber = require('bignumber.js'); 221var BigNumber = require('bignumber.js');
2697 222
2698var isNull = function (v) { 223var isNull = function (v) {
2699 return v === null || typeof v === "undefined"; 224 return v === null || typeof v === "undefined";
2700}; 225};
2701 226
2702var isBrowser = function () { 227var isBrowser = function () {
2703 return typeof window !== "undefined"; 228 return typeof window !== "undefined";
2704}; 229};
2705 230
2706var isBigNumber = function (obj) { 231var isBigNumber = function (obj) {
2707 return obj instanceof BigNumber || obj && obj.constructor && obj.constructor.name === 'BigNumber'; 232 return obj instanceof BigNumber || obj && obj.constructor && obj.constructor.name === 'BigNumber';
2708}; 233};
2709 234
2710var isString = function (obj) { 235var isString = function (obj) {
2711 return typeof obj === 'string' && obj.constructor === String; 236 return typeof obj === 'string' && obj.constructor === String;
2712}; 237};
2713 238
2714var isObject = function (obj) { 239var isObject = function (obj) {
2715 return obj !== null && typeof obj === 'object'; 240 return obj !== null && typeof obj === 'object';
2716}; 241};
2717 242
2718var isFunction = function (object) { 243var isFunction = function (object) {
2719 return typeof object === 'function'; 244 return typeof object === 'function';
2720}; 245};
2721 246
2722var isNumber = function (object) { 247var isNumber = function (object) {
2723 return typeof object === 'number'; 248 return typeof object === 'number';
2724}; 249};
2725 250
2726var toBigNumber = function (number) { 251var toBigNumber = function (number) {
2727 number = number || 0; 252 number = number || 0;
2728 if (isBigNumber(number)) { 253 if (isBigNumber(number)) {
2729 return number; 254 return number;
2730 } 255 }
2731 if (isString(number) && number.indexOf('0x') === 0) { 256 if (isString(number) && number.indexOf('0x') === 0) {
2732 return new BigNumber(number.replace('0x', ''), 16); 257 return new BigNumber(number.replace('0x', ''), 16);
2733 } 258 }
2734 return new BigNumber(number.toString(10), 10); 259 return new BigNumber(number.toString(10), 10);
2735}; 260};
2736 261
2737var toString = function (obj) { 262var toString = function (obj) {
2738 if (isString(obj)) { 263 if (isString(obj)) {
2739 return obj; 264 return obj;
2740 } else if (isBigNumber(obj)) { 265 } else if (isBigNumber(obj)) {
2741 return obj.toString(10); 266 return obj.toString(10);
2742 } else if (isObject(obj)) { 267 } else if (isObject(obj)) {
2743 return JSON.stringify(obj); 268 return JSON.stringify(obj);
2744 } else { 269 } else {
2745 return obj + ""; 270 return obj + "";
2746 } 271 }
2747}; 272};
2748 273
2749// Transform Array-like arguments object to common array. 274// Transform Array-like arguments object to common array.
2750var argumentsToArray = function (args) { 275var argumentsToArray = function (args) {
2751 var len = args.length, 276 var len = args.length,
2752 resultArray = new Array(len); 277 resultArray = new Array(len);
2753 278
2754 for (var i = 0; i < len; i += 1) { 279 for (var i = 0; i < len; i += 1) {
2755 resultArray[i] = args[i]; 280 resultArray[i] = args[i];
2756 } 281 }
2757 return resultArray; 282 return resultArray;
2758}; 283};
2759 284
2760// Create object based on provided arrays 285// Create object based on provided arrays
2761var zipArraysToObject = function (keysArr, valuesArr) { 286var zipArraysToObject = function (keysArr, valuesArr) {
2762 var resultObject = {}; 287 var resultObject = {};
2763 288
2764 for (var i = 0; i < keysArr.length; i += 1) { 289 for (var i = 0; i < keysArr.length; i += 1) {
2765 resultObject[keysArr[i]] = valuesArr[i]; 290 resultObject[keysArr[i]] = valuesArr[i];
2766 } 291 }
2767 return resultObject; 292 return resultObject;
2768}; 293};
2769 294
2770// Function what make overall view for arguments. 295// Function what make overall view for arguments.
@@ -2773,1104 +298,33 @@ var zipArraysToObject = function (keysArr, valuesArr) {
2773// in case wheare we provide args in object like "func({arg1: value})" 298// in case wheare we provide args in object like "func({arg1: value})"
2774// we just return that object 299// we just return that object
2775var argumentsToObject = function (keys, args) { 300var argumentsToObject = function (keys, args) {
2776 var ArgumentsObject = {}; 301 var ArgumentsObject = {};
2777 302
2778 args = argumentsToArray(args); 303 args = argumentsToArray(args);
2779 if (isObject(args[0])) { 304 if (isObject(args[0])) {
2780 ArgumentsObject = args[0]; 305 ArgumentsObject = args[0];
2781 } else { 306 } else {
2782 ArgumentsObject = zipArraysToObject(keys, args); 307 ArgumentsObject = zipArraysToObject(keys, args);
2783 } 308 }
2784 309
2785 return ArgumentsObject; 310 return ArgumentsObject;
2786}; 311};
2787 312
2788module.exports = { 313module.exports = {
2789 isNull: isNull, 314 isNull: isNull,
2790 isBrowser: isBrowser, 315 isBrowser: isBrowser,
2791 isBigNumber: isBigNumber, 316 isBigNumber: isBigNumber,
2792 isString: isString, 317 isString: isString,
2793 isObject: isObject, 318 isObject: isObject,
2794 isFunction: isFunction, 319 isFunction: isFunction,
2795 isNumber: isNumber, 320 isNumber: isNumber,
2796 toBigNumber: toBigNumber, 321 toBigNumber: toBigNumber,
2797 toString: toString, 322 toString: toString,
2798 argumentsToObject: argumentsToObject, 323 argumentsToObject: argumentsToObject,
2799 zipArraysToObject: zipArraysToObject 324 zipArraysToObject: zipArraysToObject
2800}; 325};
2801 326
2802},{"bignumber.js":73}],22:[function(require,module,exports){ 327},{"bignumber.js":19}],3:[function(require,module,exports){
2803"use strict";
2804module.exports = asPromise;
2805
2806/**
2807 * Callback as used by {@link util.asPromise}.
2808 * @typedef asPromiseCallback
2809 * @type {function}
2810 * @param {Error|null} error Error, if any
2811 * @param {...*} params Additional arguments
2812 * @returns {undefined}
2813 */
2814
2815/**
2816 * Returns a promise from a node-style callback function.
2817 * @memberof util
2818 * @param {asPromiseCallback} fn Function to call
2819 * @param {*} ctx Function context
2820 * @param {...*} params Function arguments
2821 * @returns {Promise<*>} Promisified function
2822 */
2823function asPromise(fn, ctx/*, varargs */) {
2824 var params = new Array(arguments.length - 1),
2825 offset = 0,
2826 index = 2,
2827 pending = true;
2828 while (index < arguments.length)
2829 params[offset++] = arguments[index++];
2830 return new Promise(function executor(resolve, reject) {
2831 params[offset] = function callback(err/*, varargs */) {
2832 if (pending) {
2833 pending = false;
2834 if (err)
2835 reject(err);
2836 else {
2837 var params = new Array(arguments.length - 1),
2838 offset = 0;
2839 while (offset < params.length)
2840 params[offset++] = arguments[offset];
2841 resolve.apply(null, params);
2842 }
2843 }
2844 };
2845 try {
2846 fn.apply(ctx || null, params);
2847 } catch (err) {
2848 if (pending) {
2849 pending = false;
2850 reject(err);
2851 }
2852 }
2853 });
2854}
2855
2856},{}],23:[function(require,module,exports){
2857"use strict";
2858
2859/**
2860 * A minimal base64 implementation for number arrays.
2861 * @memberof util
2862 * @namespace
2863 */
2864var base64 = exports;
2865
2866/**
2867 * Calculates the byte length of a base64 encoded string.
2868 * @param {string} string Base64 encoded string
2869 * @returns {number} Byte length
2870 */
2871base64.length = function length(string) {
2872 var p = string.length;
2873 if (!p)
2874 return 0;
2875 var n = 0;
2876 while (--p % 4 > 1 && string.charAt(p) === "=")
2877 ++n;
2878 return Math.ceil(string.length * 3) / 4 - n;
2879};
2880
2881// Base64 encoding table
2882var b64 = new Array(64);
2883
2884// Base64 decoding table
2885var s64 = new Array(123);
2886
2887// 65..90, 97..122, 48..57, 43, 47
2888for (var i = 0; i < 64;)
2889 s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
2890
2891/**
2892 * Encodes a buffer to a base64 encoded string.
2893 * @param {Uint8Array} buffer Source buffer
2894 * @param {number} start Source start
2895 * @param {number} end Source end
2896 * @returns {string} Base64 encoded string
2897 */
2898base64.encode = function encode(buffer, start, end) {
2899 var parts = null,
2900 chunk = [];
2901 var i = 0, // output index
2902 j = 0, // goto index
2903 t; // temporary
2904 while (start < end) {
2905 var b = buffer[start++];
2906 switch (j) {
2907 case 0:
2908 chunk[i++] = b64[b >> 2];
2909 t = (b & 3) << 4;
2910 j = 1;
2911 break;
2912 case 1:
2913 chunk[i++] = b64[t | b >> 4];
2914 t = (b & 15) << 2;
2915 j = 2;
2916 break;
2917 case 2:
2918 chunk[i++] = b64[t | b >> 6];
2919 chunk[i++] = b64[b & 63];
2920 j = 0;
2921 break;
2922 }
2923 if (i > 8191) {
2924 (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
2925 i = 0;
2926 }
2927 }
2928 if (j) {
2929 chunk[i++] = b64[t];
2930 chunk[i++] = 61;
2931 if (j === 1)
2932 chunk[i++] = 61;
2933 }
2934 if (parts) {
2935 if (i)
2936 parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
2937 return parts.join("");
2938 }
2939 return String.fromCharCode.apply(String, chunk.slice(0, i));
2940};
2941
2942var invalidEncoding = "invalid encoding";
2943
2944/**
2945 * Decodes a base64 encoded string to a buffer.
2946 * @param {string} string Source string
2947 * @param {Uint8Array} buffer Destination buffer
2948 * @param {number} offset Destination offset
2949 * @returns {number} Number of bytes written
2950 * @throws {Error} If encoding is invalid
2951 */
2952base64.decode = function decode(string, buffer, offset) {
2953 var start = offset;
2954 var j = 0, // goto index
2955 t; // temporary
2956 for (var i = 0; i < string.length;) {
2957 var c = string.charCodeAt(i++);
2958 if (c === 61 && j > 1)
2959 break;
2960 if ((c = s64[c]) === undefined)
2961 throw Error(invalidEncoding);
2962 switch (j) {
2963 case 0:
2964 t = c;
2965 j = 1;
2966 break;
2967 case 1:
2968 buffer[offset++] = t << 2 | (c & 48) >> 4;
2969 t = c;
2970 j = 2;
2971 break;
2972 case 2:
2973 buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;
2974 t = c;
2975 j = 3;
2976 break;
2977 case 3:
2978 buffer[offset++] = (t & 3) << 6 | c;
2979 j = 0;
2980 break;
2981 }
2982 }
2983 if (j === 1)
2984 throw Error(invalidEncoding);
2985 return offset - start;
2986};
2987
2988/**
2989 * Tests if the specified string appears to be base64 encoded.
2990 * @param {string} string String to test
2991 * @returns {boolean} `true` if probably base64 encoded, otherwise false
2992 */
2993base64.test = function test(string) {
2994 return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);
2995};
2996
2997},{}],24:[function(require,module,exports){
2998"use strict";
2999module.exports = codegen;
3000
3001/**
3002 * Begins generating a function.
3003 * @memberof util
3004 * @param {string[]} functionParams Function parameter names
3005 * @param {string} [functionName] Function name if not anonymous
3006 * @returns {Codegen} Appender that appends code to the function's body
3007 */
3008function codegen(functionParams, functionName) {
3009
3010 /* istanbul ignore if */
3011 if (typeof functionParams === "string") {
3012 functionName = functionParams;
3013 functionParams = undefined;
3014 }
3015
3016 var body = [];
3017
3018 /**
3019 * Appends code to the function's body or finishes generation.
3020 * @typedef Codegen
3021 * @type {function}
3022 * @param {string|Object.<string,*>} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any
3023 * @param {...*} [formatParams] Format parameters
3024 * @returns {Codegen|Function} Itself or the generated function if finished
3025 * @throws {Error} If format parameter counts do not match
3026 */
3027
3028 function Codegen(formatStringOrScope) {
3029 // note that explicit array handling below makes this ~50% faster
3030
3031 // finish the function
3032 if (typeof formatStringOrScope !== "string") {
3033 var source = toString();
3034 if (codegen.verbose)
3035 console.log("codegen: " + source); // eslint-disable-line no-console
3036 source = "return " + source;
3037 if (formatStringOrScope) {
3038 var scopeKeys = Object.keys(formatStringOrScope),
3039 scopeParams = new Array(scopeKeys.length + 1),
3040 scopeValues = new Array(scopeKeys.length),
3041 scopeOffset = 0;
3042 while (scopeOffset < scopeKeys.length) {
3043 scopeParams[scopeOffset] = scopeKeys[scopeOffset];
3044 scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];
3045 }
3046 scopeParams[scopeOffset] = source;
3047 return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func
3048 }
3049 return Function(source)(); // eslint-disable-line no-new-func
3050 }
3051
3052 // otherwise append to body
3053 var formatParams = new Array(arguments.length - 1),
3054 formatOffset = 0;
3055 while (formatOffset < formatParams.length)
3056 formatParams[formatOffset] = arguments[++formatOffset];
3057 formatOffset = 0;
3058 formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {
3059 var value = formatParams[formatOffset++];
3060 switch ($1) {
3061 case "d": case "f": return String(Number(value));
3062 case "i": return String(Math.floor(value));
3063 case "j": return JSON.stringify(value);
3064 case "s": return String(value);
3065 }
3066 return "%";
3067 });
3068 if (formatOffset !== formatParams.length)
3069 throw Error("parameter count mismatch");
3070 body.push(formatStringOrScope);
3071 return Codegen;
3072 }
3073
3074 function toString(functionNameOverride) {
3075 return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}";
3076 }
3077
3078 Codegen.toString = toString;
3079 return Codegen;
3080}
3081
3082/**
3083 * Begins generating a function.
3084 * @memberof util
3085 * @function codegen
3086 * @param {string} [functionName] Function name if not anonymous
3087 * @returns {Codegen} Appender that appends code to the function's body
3088 * @variation 2
3089 */
3090
3091/**
3092 * When set to `true`, codegen will log generated code to console. Useful for debugging.
3093 * @name util.codegen.verbose
3094 * @type {boolean}
3095 */
3096codegen.verbose = false;
3097
3098},{}],25:[function(require,module,exports){
3099"use strict";
3100module.exports = EventEmitter;
3101
3102/**
3103 * Constructs a new event emitter instance.
3104 * @classdesc A minimal event emitter.
3105 * @memberof util
3106 * @constructor
3107 */
3108function EventEmitter() {
3109
3110 /**
3111 * Registered listeners.
3112 * @type {Object.<string,*>}
3113 * @private
3114 */
3115 this._listeners = {};
3116}
3117
3118/**
3119 * Registers an event listener.
3120 * @param {string} evt Event name
3121 * @param {function} fn Listener
3122 * @param {*} [ctx] Listener context
3123 * @returns {util.EventEmitter} `this`
3124 */
3125EventEmitter.prototype.on = function on(evt, fn, ctx) {
3126 (this._listeners[evt] || (this._listeners[evt] = [])).push({
3127 fn : fn,
3128 ctx : ctx || this
3129 });
3130 return this;
3131};
3132
3133/**
3134 * Removes an event listener or any matching listeners if arguments are omitted.
3135 * @param {string} [evt] Event name. Removes all listeners if omitted.
3136 * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.
3137 * @returns {util.EventEmitter} `this`
3138 */
3139EventEmitter.prototype.off = function off(evt, fn) {
3140 if (evt === undefined)
3141 this._listeners = {};
3142 else {
3143 if (fn === undefined)
3144 this._listeners[evt] = [];
3145 else {
3146 var listeners = this._listeners[evt];
3147 for (var i = 0; i < listeners.length;)
3148 if (listeners[i].fn === fn)
3149 listeners.splice(i, 1);
3150 else
3151 ++i;
3152 }
3153 }
3154 return this;
3155};
3156
3157/**
3158 * Emits an event by calling its listeners with the specified arguments.
3159 * @param {string} evt Event name
3160 * @param {...*} args Arguments
3161 * @returns {util.EventEmitter} `this`
3162 */
3163EventEmitter.prototype.emit = function emit(evt) {
3164 var listeners = this._listeners[evt];
3165 if (listeners) {
3166 var args = [],
3167 i = 1;
3168 for (; i < arguments.length;)
3169 args.push(arguments[i++]);
3170 for (i = 0; i < listeners.length;)
3171 listeners[i].fn.apply(listeners[i++].ctx, args);
3172 }
3173 return this;
3174};
3175
3176},{}],26:[function(require,module,exports){
3177"use strict";
3178module.exports = fetch;
3179
3180var asPromise = require("@protobufjs/aspromise"),
3181 inquire = require("@protobufjs/inquire");
3182
3183var fs = inquire("fs");
3184
3185/**
3186 * Node-style callback as used by {@link util.fetch}.
3187 * @typedef FetchCallback
3188 * @type {function}
3189 * @param {?Error} error Error, if any, otherwise `null`
3190 * @param {string} [contents] File contents, if there hasn't been an error
3191 * @returns {undefined}
3192 */
3193
3194/**
3195 * Options as used by {@link util.fetch}.
3196 * @typedef FetchOptions
3197 * @type {Object}
3198 * @property {boolean} [binary=false] Whether expecting a binary response
3199 * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest
3200 */
3201
3202/**
3203 * Fetches the contents of a file.
3204 * @memberof util
3205 * @param {string} filename File path or url
3206 * @param {FetchOptions} options Fetch options
3207 * @param {FetchCallback} callback Callback function
3208 * @returns {undefined}
3209 */
3210function fetch(filename, options, callback) {
3211 if (typeof options === "function") {
3212 callback = options;
3213 options = {};
3214 } else if (!options)
3215 options = {};
3216
3217 if (!callback)
3218 return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this
3219
3220 // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.
3221 if (!options.xhr && fs && fs.readFile)
3222 return fs.readFile(filename, function fetchReadFileCallback(err, contents) {
3223 return err && typeof XMLHttpRequest !== "undefined"
3224 ? fetch.xhr(filename, options, callback)
3225 : err
3226 ? callback(err)
3227 : callback(null, options.binary ? contents : contents.toString("utf8"));
3228 });
3229
3230 // use the XHR version otherwise.
3231 return fetch.xhr(filename, options, callback);
3232}
3233
3234/**
3235 * Fetches the contents of a file.
3236 * @name util.fetch
3237 * @function
3238 * @param {string} path File path or url
3239 * @param {FetchCallback} callback Callback function
3240 * @returns {undefined}
3241 * @variation 2
3242 */
3243
3244/**
3245 * Fetches the contents of a file.
3246 * @name util.fetch
3247 * @function
3248 * @param {string} path File path or url
3249 * @param {FetchOptions} [options] Fetch options
3250 * @returns {Promise<string|Uint8Array>} Promise
3251 * @variation 3
3252 */
3253
3254/**/
3255fetch.xhr = function fetch_xhr(filename, options, callback) {
3256 var xhr = new XMLHttpRequest();
3257 xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {
3258
3259 if (xhr.readyState !== 4)
3260 return undefined;
3261
3262 // local cors security errors return status 0 / empty string, too. afaik this cannot be
3263 // reliably distinguished from an actually empty file for security reasons. feel free
3264 // to send a pull request if you are aware of a solution.
3265 if (xhr.status !== 0 && xhr.status !== 200)
3266 return callback(Error("status " + xhr.status));
3267
3268 // if binary data is expected, make sure that some sort of array is returned, even if
3269 // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.
3270 if (options.binary) {
3271 var buffer = xhr.response;
3272 if (!buffer) {
3273 buffer = [];
3274 for (var i = 0; i < xhr.responseText.length; ++i)
3275 buffer.push(xhr.responseText.charCodeAt(i) & 255);
3276 }
3277 return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer);
3278 }
3279 return callback(null, xhr.responseText);
3280 };
3281
3282 if (options.binary) {
3283 // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers
3284 if ("overrideMimeType" in xhr)
3285 xhr.overrideMimeType("text/plain; charset=x-user-defined");
3286 xhr.responseType = "arraybuffer";
3287 }
3288
3289 xhr.open("GET", filename);
3290 xhr.send();
3291};
3292
3293},{"@protobufjs/aspromise":22,"@protobufjs/inquire":28}],27:[function(require,module,exports){
3294"use strict";
3295
3296module.exports = factory(factory);
3297
3298/**
3299 * Reads / writes floats / doubles from / to buffers.
3300 * @name util.float
3301 * @namespace
3302 */
3303
3304/**
3305 * Writes a 32 bit float to a buffer using little endian byte order.
3306 * @name util.float.writeFloatLE
3307 * @function
3308 * @param {number} val Value to write
3309 * @param {Uint8Array} buf Target buffer
3310 * @param {number} pos Target buffer offset
3311 * @returns {undefined}
3312 */
3313
3314/**
3315 * Writes a 32 bit float to a buffer using big endian byte order.
3316 * @name util.float.writeFloatBE
3317 * @function
3318 * @param {number} val Value to write
3319 * @param {Uint8Array} buf Target buffer
3320 * @param {number} pos Target buffer offset
3321 * @returns {undefined}
3322 */
3323
3324/**
3325 * Reads a 32 bit float from a buffer using little endian byte order.
3326 * @name util.float.readFloatLE
3327 * @function
3328 * @param {Uint8Array} buf Source buffer
3329 * @param {number} pos Source buffer offset
3330 * @returns {number} Value read
3331 */
3332
3333/**
3334 * Reads a 32 bit float from a buffer using big endian byte order.
3335 * @name util.float.readFloatBE
3336 * @function
3337 * @param {Uint8Array} buf Source buffer
3338 * @param {number} pos Source buffer offset
3339 * @returns {number} Value read
3340 */
3341
3342/**
3343 * Writes a 64 bit double to a buffer using little endian byte order.
3344 * @name util.float.writeDoubleLE
3345 * @function
3346 * @param {number} val Value to write
3347 * @param {Uint8Array} buf Target buffer
3348 * @param {number} pos Target buffer offset
3349 * @returns {undefined}
3350 */
3351
3352/**
3353 * Writes a 64 bit double to a buffer using big endian byte order.
3354 * @name util.float.writeDoubleBE
3355 * @function
3356 * @param {number} val Value to write
3357 * @param {Uint8Array} buf Target buffer
3358 * @param {number} pos Target buffer offset
3359 * @returns {undefined}
3360 */
3361
3362/**
3363 * Reads a 64 bit double from a buffer using little endian byte order.
3364 * @name util.float.readDoubleLE
3365 * @function
3366 * @param {Uint8Array} buf Source buffer
3367 * @param {number} pos Source buffer offset
3368 * @returns {number} Value read
3369 */
3370
3371/**
3372 * Reads a 64 bit double from a buffer using big endian byte order.
3373 * @name util.float.readDoubleBE
3374 * @function
3375 * @param {Uint8Array} buf Source buffer
3376 * @param {number} pos Source buffer offset
3377 * @returns {number} Value read
3378 */
3379
3380// Factory function for the purpose of node-based testing in modified global environments
3381function factory(exports) {
3382
3383 // float: typed array
3384 if (typeof Float32Array !== "undefined") (function() {
3385
3386 var f32 = new Float32Array([ -0 ]),
3387 f8b = new Uint8Array(f32.buffer),
3388 le = f8b[3] === 128;
3389
3390 function writeFloat_f32_cpy(val, buf, pos) {
3391 f32[0] = val;
3392 buf[pos ] = f8b[0];
3393 buf[pos + 1] = f8b[1];
3394 buf[pos + 2] = f8b[2];
3395 buf[pos + 3] = f8b[3];
3396 }
3397
3398 function writeFloat_f32_rev(val, buf, pos) {
3399 f32[0] = val;
3400 buf[pos ] = f8b[3];
3401 buf[pos + 1] = f8b[2];
3402 buf[pos + 2] = f8b[1];
3403 buf[pos + 3] = f8b[0];
3404 }
3405
3406 /* istanbul ignore next */
3407 exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;
3408 /* istanbul ignore next */
3409 exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;
3410
3411 function readFloat_f32_cpy(buf, pos) {
3412 f8b[0] = buf[pos ];
3413 f8b[1] = buf[pos + 1];
3414 f8b[2] = buf[pos + 2];
3415 f8b[3] = buf[pos + 3];
3416 return f32[0];
3417 }
3418
3419 function readFloat_f32_rev(buf, pos) {
3420 f8b[3] = buf[pos ];
3421 f8b[2] = buf[pos + 1];
3422 f8b[1] = buf[pos + 2];
3423 f8b[0] = buf[pos + 3];
3424 return f32[0];
3425 }
3426
3427 /* istanbul ignore next */
3428 exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;
3429 /* istanbul ignore next */
3430 exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;
3431
3432 // float: ieee754
3433 })(); else (function() {
3434
3435 function writeFloat_ieee754(writeUint, val, buf, pos) {
3436 var sign = val < 0 ? 1 : 0;
3437 if (sign)
3438 val = -val;
3439 if (val === 0)
3440 writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);
3441 else if (isNaN(val))
3442 writeUint(2143289344, buf, pos);
3443 else if (val > 3.4028234663852886e+38) // +-Infinity
3444 writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);
3445 else if (val < 1.1754943508222875e-38) // denormal
3446 writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);
3447 else {
3448 var exponent = Math.floor(Math.log(val) / Math.LN2),
3449 mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;
3450 writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);
3451 }
3452 }
3453
3454 exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);
3455 exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);
3456
3457 function readFloat_ieee754(readUint, buf, pos) {
3458 var uint = readUint(buf, pos),
3459 sign = (uint >> 31) * 2 + 1,
3460 exponent = uint >>> 23 & 255,
3461 mantissa = uint & 8388607;
3462 return exponent === 255
3463 ? mantissa
3464 ? NaN
3465 : sign * Infinity
3466 : exponent === 0 // denormal
3467 ? sign * 1.401298464324817e-45 * mantissa
3468 : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);
3469 }
3470
3471 exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);
3472 exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);
3473
3474 })();
3475
3476 // double: typed array
3477 if (typeof Float64Array !== "undefined") (function() {
3478
3479 var f64 = new Float64Array([-0]),
3480 f8b = new Uint8Array(f64.buffer),
3481 le = f8b[7] === 128;
3482
3483 function writeDouble_f64_cpy(val, buf, pos) {
3484 f64[0] = val;
3485 buf[pos ] = f8b[0];
3486 buf[pos + 1] = f8b[1];
3487 buf[pos + 2] = f8b[2];
3488 buf[pos + 3] = f8b[3];
3489 buf[pos + 4] = f8b[4];
3490 buf[pos + 5] = f8b[5];
3491 buf[pos + 6] = f8b[6];
3492 buf[pos + 7] = f8b[7];
3493 }
3494
3495 function writeDouble_f64_rev(val, buf, pos) {
3496 f64[0] = val;
3497 buf[pos ] = f8b[7];
3498 buf[pos + 1] = f8b[6];
3499 buf[pos + 2] = f8b[5];
3500 buf[pos + 3] = f8b[4];
3501 buf[pos + 4] = f8b[3];
3502 buf[pos + 5] = f8b[2];
3503 buf[pos + 6] = f8b[1];
3504 buf[pos + 7] = f8b[0];
3505 }
3506
3507 /* istanbul ignore next */
3508 exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;
3509 /* istanbul ignore next */
3510 exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;
3511
3512 function readDouble_f64_cpy(buf, pos) {
3513 f8b[0] = buf[pos ];
3514 f8b[1] = buf[pos + 1];
3515 f8b[2] = buf[pos + 2];
3516 f8b[3] = buf[pos + 3];
3517 f8b[4] = buf[pos + 4];
3518 f8b[5] = buf[pos + 5];
3519 f8b[6] = buf[pos + 6];
3520 f8b[7] = buf[pos + 7];
3521 return f64[0];
3522 }
3523
3524 function readDouble_f64_rev(buf, pos) {
3525 f8b[7] = buf[pos ];
3526 f8b[6] = buf[pos + 1];
3527 f8b[5] = buf[pos + 2];
3528 f8b[4] = buf[pos + 3];
3529 f8b[3] = buf[pos + 4];
3530 f8b[2] = buf[pos + 5];
3531 f8b[1] = buf[pos + 6];
3532 f8b[0] = buf[pos + 7];
3533 return f64[0];
3534 }
3535
3536 /* istanbul ignore next */
3537 exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;
3538 /* istanbul ignore next */
3539 exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;
3540
3541 // double: ieee754
3542 })(); else (function() {
3543
3544 function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {
3545 var sign = val < 0 ? 1 : 0;
3546 if (sign)
3547 val = -val;
3548 if (val === 0) {
3549 writeUint(0, buf, pos + off0);
3550 writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);
3551 } else if (isNaN(val)) {
3552 writeUint(0, buf, pos + off0);
3553 writeUint(2146959360, buf, pos + off1);
3554 } else if (val > 1.7976931348623157e+308) { // +-Infinity
3555 writeUint(0, buf, pos + off0);
3556 writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);
3557 } else {
3558 var mantissa;
3559 if (val < 2.2250738585072014e-308) { // denormal
3560 mantissa = val / 5e-324;
3561 writeUint(mantissa >>> 0, buf, pos + off0);
3562 writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);
3563 } else {
3564 var exponent = Math.floor(Math.log(val) / Math.LN2);
3565 if (exponent === 1024)
3566 exponent = 1023;
3567 mantissa = val * Math.pow(2, -exponent);
3568 writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);
3569 writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);
3570 }
3571 }
3572 }
3573
3574 exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);
3575 exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);
3576
3577 function readDouble_ieee754(readUint, off0, off1, buf, pos) {
3578 var lo = readUint(buf, pos + off0),
3579 hi = readUint(buf, pos + off1);
3580 var sign = (hi >> 31) * 2 + 1,
3581 exponent = hi >>> 20 & 2047,
3582 mantissa = 4294967296 * (hi & 1048575) + lo;
3583 return exponent === 2047
3584 ? mantissa
3585 ? NaN
3586 : sign * Infinity
3587 : exponent === 0 // denormal
3588 ? sign * 5e-324 * mantissa
3589 : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);
3590 }
3591
3592 exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);
3593 exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);
3594
3595 })();
3596
3597 return exports;
3598}
3599
3600// uint helpers
3601
3602function writeUintLE(val, buf, pos) {
3603 buf[pos ] = val & 255;
3604 buf[pos + 1] = val >>> 8 & 255;
3605 buf[pos + 2] = val >>> 16 & 255;
3606 buf[pos + 3] = val >>> 24;
3607}
3608
3609function writeUintBE(val, buf, pos) {
3610 buf[pos ] = val >>> 24;
3611 buf[pos + 1] = val >>> 16 & 255;
3612 buf[pos + 2] = val >>> 8 & 255;
3613 buf[pos + 3] = val & 255;
3614}
3615
3616function readUintLE(buf, pos) {
3617 return (buf[pos ]
3618 | buf[pos + 1] << 8
3619 | buf[pos + 2] << 16
3620 | buf[pos + 3] << 24) >>> 0;
3621}
3622
3623function readUintBE(buf, pos) {
3624 return (buf[pos ] << 24
3625 | buf[pos + 1] << 16
3626 | buf[pos + 2] << 8
3627 | buf[pos + 3]) >>> 0;
3628}
3629
3630},{}],28:[function(require,module,exports){
3631"use strict";
3632module.exports = inquire;
3633
3634/**
3635 * Requires a module only if available.
3636 * @memberof util
3637 * @param {string} moduleName Module to require
3638 * @returns {?Object} Required module if available and not empty, otherwise `null`
3639 */
3640function inquire(moduleName) {
3641 try {
3642 var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval
3643 if (mod && (mod.length || Object.keys(mod).length))
3644 return mod;
3645 } catch (e) {} // eslint-disable-line no-empty
3646 return null;
3647}
3648
3649},{}],29:[function(require,module,exports){
3650"use strict";
3651
3652/**
3653 * A minimal path module to resolve Unix, Windows and URL paths alike.
3654 * @memberof util
3655 * @namespace
3656 */
3657var path = exports;
3658
3659var isAbsolute =
3660/**
3661 * Tests if the specified path is absolute.
3662 * @param {string} path Path to test
3663 * @returns {boolean} `true` if path is absolute
3664 */
3665path.isAbsolute = function isAbsolute(path) {
3666 return /^(?:\/|\w+:)/.test(path);
3667};
3668
3669var normalize =
3670/**
3671 * Normalizes the specified path.
3672 * @param {string} path Path to normalize
3673 * @returns {string} Normalized path
3674 */
3675path.normalize = function normalize(path) {
3676 path = path.replace(/\\/g, "/")
3677 .replace(/\/{2,}/g, "/");
3678 var parts = path.split("/"),
3679 absolute = isAbsolute(path),
3680 prefix = "";
3681 if (absolute)
3682 prefix = parts.shift() + "/";
3683 for (var i = 0; i < parts.length;) {
3684 if (parts[i] === "..") {
3685 if (i > 0 && parts[i - 1] !== "..")
3686 parts.splice(--i, 2);
3687 else if (absolute)
3688 parts.splice(i, 1);
3689 else
3690 ++i;
3691 } else if (parts[i] === ".")
3692 parts.splice(i, 1);
3693 else
3694 ++i;
3695 }
3696 return prefix + parts.join("/");
3697};
3698
3699/**
3700 * Resolves the specified include path against the specified origin path.
3701 * @param {string} originPath Path to the origin file
3702 * @param {string} includePath Include path relative to origin path
3703 * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized
3704 * @returns {string} Path to the include file
3705 */
3706path.resolve = function resolve(originPath, includePath, alreadyNormalized) {
3707 if (!alreadyNormalized)
3708 includePath = normalize(includePath);
3709 if (isAbsolute(includePath))
3710 return includePath;
3711 if (!alreadyNormalized)
3712 originPath = normalize(originPath);
3713 return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath;
3714};
3715
3716},{}],30:[function(require,module,exports){
3717"use strict";
3718module.exports = pool;
3719
3720/**
3721 * An allocator as used by {@link util.pool}.
3722 * @typedef PoolAllocator
3723 * @type {function}
3724 * @param {number} size Buffer size
3725 * @returns {Uint8Array} Buffer
3726 */
3727
3728/**
3729 * A slicer as used by {@link util.pool}.
3730 * @typedef PoolSlicer
3731 * @type {function}
3732 * @param {number} start Start offset
3733 * @param {number} end End offset
3734 * @returns {Uint8Array} Buffer slice
3735 * @this {Uint8Array}
3736 */
3737
3738/**
3739 * A general purpose buffer pool.
3740 * @memberof util
3741 * @function
3742 * @param {PoolAllocator} alloc Allocator
3743 * @param {PoolSlicer} slice Slicer
3744 * @param {number} [size=8192] Slab size
3745 * @returns {PoolAllocator} Pooled allocator
3746 */
3747function pool(alloc, slice, size) {
3748 var SIZE = size || 8192;
3749 var MAX = SIZE >>> 1;
3750 var slab = null;
3751 var offset = SIZE;
3752 return function pool_alloc(size) {
3753 if (size < 1 || size > MAX)
3754 return alloc(size);
3755 if (offset + size > SIZE) {
3756 slab = alloc(SIZE);
3757 offset = 0;
3758 }
3759 var buf = slice.call(slab, offset, offset += size);
3760 if (offset & 7) // align to 32 bit
3761 offset = (offset | 7) + 1;
3762 return buf;
3763 };
3764}
3765
3766},{}],31:[function(require,module,exports){
3767"use strict";
3768
3769/**
3770 * A minimal UTF8 implementation for number arrays.
3771 * @memberof util
3772 * @namespace
3773 */
3774var utf8 = exports;
3775
3776/**
3777 * Calculates the UTF8 byte length of a string.
3778 * @param {string} string String
3779 * @returns {number} Byte length
3780 */
3781utf8.length = function utf8_length(string) {
3782 var len = 0,
3783 c = 0;
3784 for (var i = 0; i < string.length; ++i) {
3785 c = string.charCodeAt(i);
3786 if (c < 128)
3787 len += 1;
3788 else if (c < 2048)
3789 len += 2;
3790 else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {
3791 ++i;
3792 len += 4;
3793 } else
3794 len += 3;
3795 }
3796 return len;
3797};
3798
3799/**
3800 * Reads UTF8 bytes as a string.
3801 * @param {Uint8Array} buffer Source buffer
3802 * @param {number} start Source start
3803 * @param {number} end Source end
3804 * @returns {string} String read
3805 */
3806utf8.read = function utf8_read(buffer, start, end) {
3807 var len = end - start;
3808 if (len < 1)
3809 return "";
3810 var parts = null,
3811 chunk = [],
3812 i = 0, // char offset
3813 t; // temporary
3814 while (start < end) {
3815 t = buffer[start++];
3816 if (t < 128)
3817 chunk[i++] = t;
3818 else if (t > 191 && t < 224)
3819 chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;
3820 else if (t > 239 && t < 365) {
3821 t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;
3822 chunk[i++] = 0xD800 + (t >> 10);
3823 chunk[i++] = 0xDC00 + (t & 1023);
3824 } else
3825 chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;
3826 if (i > 8191) {
3827 (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
3828 i = 0;
3829 }
3830 }
3831 if (parts) {
3832 if (i)
3833 parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));
3834 return parts.join("");
3835 }
3836 return String.fromCharCode.apply(String, chunk.slice(0, i));
3837};
3838
3839/**
3840 * Writes a string as UTF8 bytes.
3841 * @param {string} string Source string
3842 * @param {Uint8Array} buffer Destination buffer
3843 * @param {number} offset Destination offset
3844 * @returns {number} Bytes written
3845 */
3846utf8.write = function utf8_write(string, buffer, offset) {
3847 var start = offset,
3848 c1, // character 1
3849 c2; // character 2
3850 for (var i = 0; i < string.length; ++i) {
3851 c1 = string.charCodeAt(i);
3852 if (c1 < 128) {
3853 buffer[offset++] = c1;
3854 } else if (c1 < 2048) {
3855 buffer[offset++] = c1 >> 6 | 192;
3856 buffer[offset++] = c1 & 63 | 128;
3857 } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {
3858 c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);
3859 ++i;
3860 buffer[offset++] = c1 >> 18 | 240;
3861 buffer[offset++] = c1 >> 12 & 63 | 128;
3862 buffer[offset++] = c1 >> 6 & 63 | 128;
3863 buffer[offset++] = c1 & 63 | 128;
3864 } else {
3865 buffer[offset++] = c1 >> 12 | 224;
3866 buffer[offset++] = c1 >> 6 & 63 | 128;
3867 buffer[offset++] = c1 & 63 | 128;
3868 }
3869 }
3870 return offset - start;
3871};
3872
3873},{}],32:[function(require,module,exports){
3874var asn1 = exports; 328var asn1 = exports;
3875 329
3876asn1.bignum = require('bn.js'); 330asn1.bignum = require('bn.js');
@@ -3881,7 +335,7 @@ asn1.constants = require('./asn1/constants');
3881asn1.decoders = require('./asn1/decoders'); 335asn1.decoders = require('./asn1/decoders');
3882asn1.encoders = require('./asn1/encoders'); 336asn1.encoders = require('./asn1/encoders');
3883 337
3884},{"./asn1/api":33,"./asn1/base":35,"./asn1/constants":39,"./asn1/decoders":41,"./asn1/encoders":44,"bn.js":75}],33:[function(require,module,exports){ 338},{"./asn1/api":4,"./asn1/base":6,"./asn1/constants":10,"./asn1/decoders":12,"./asn1/encoders":15,"bn.js":21}],4:[function(require,module,exports){
3885var asn1 = require('../asn1'); 339var asn1 = require('../asn1');
3886var inherits = require('inherits'); 340var inherits = require('inherits');
3887 341
@@ -3944,7 +398,7 @@ Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
3944 return this._getEncoder(enc).encode(data, reporter); 398 return this._getEncoder(enc).encode(data, reporter);
3945}; 399};
3946 400
3947},{"../asn1":32,"inherits":163,"vm":271}],34:[function(require,module,exports){ 401},{"../asn1":3,"inherits":107,"vm":180}],5:[function(require,module,exports){
3948var inherits = require('inherits'); 402var inherits = require('inherits');
3949var Reporter = require('../base').Reporter; 403var Reporter = require('../base').Reporter;
3950var Buffer = require('buffer').Buffer; 404var Buffer = require('buffer').Buffer;
@@ -4062,7 +516,7 @@ EncoderBuffer.prototype.join = function join(out, offset) {
4062 return out; 516 return out;
4063}; 517};
4064 518
4065},{"../base":35,"buffer":107,"inherits":163}],35:[function(require,module,exports){ 519},{"../base":6,"buffer":53,"inherits":107}],6:[function(require,module,exports){
4066var base = exports; 520var base = exports;
4067 521
4068base.Reporter = require('./reporter').Reporter; 522base.Reporter = require('./reporter').Reporter;
@@ -4070,7 +524,7 @@ base.DecoderBuffer = require('./buffer').DecoderBuffer;
4070base.EncoderBuffer = require('./buffer').EncoderBuffer; 524base.EncoderBuffer = require('./buffer').EncoderBuffer;
4071base.Node = require('./node'); 525base.Node = require('./node');
4072 526
4073},{"./buffer":34,"./node":36,"./reporter":37}],36:[function(require,module,exports){ 527},{"./buffer":5,"./node":7,"./reporter":8}],7:[function(require,module,exports){
4074var Reporter = require('../base').Reporter; 528var Reporter = require('../base').Reporter;
4075var EncoderBuffer = require('../base').EncoderBuffer; 529var EncoderBuffer = require('../base').EncoderBuffer;
4076var DecoderBuffer = require('../base').DecoderBuffer; 530var DecoderBuffer = require('../base').DecoderBuffer;
@@ -4706,7 +1160,7 @@ Node.prototype._isPrintstr = function isPrintstr(str) {
4706 return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); 1160 return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str);
4707}; 1161};
4708 1162
4709},{"../base":35,"minimalistic-assert":176}],37:[function(require,module,exports){ 1163},{"../base":6,"minimalistic-assert":120}],8:[function(require,module,exports){
4710var inherits = require('inherits'); 1164var inherits = require('inherits');
4711 1165
4712function Reporter(options) { 1166function Reporter(options) {
@@ -4829,7 +1283,7 @@ ReporterError.prototype.rethrow = function rethrow(msg) {
4829 return this; 1283 return this;
4830}; 1284};
4831 1285
4832},{"inherits":163}],38:[function(require,module,exports){ 1286},{"inherits":107}],9:[function(require,module,exports){
4833var constants = require('../constants'); 1287var constants = require('../constants');
4834 1288
4835exports.tagClass = { 1289exports.tagClass = {
@@ -4873,7 +1327,7 @@ exports.tag = {
4873}; 1327};
4874exports.tagByName = constants._reverse(exports.tag); 1328exports.tagByName = constants._reverse(exports.tag);
4875 1329
4876},{"../constants":39}],39:[function(require,module,exports){ 1330},{"../constants":10}],10:[function(require,module,exports){
4877var constants = exports; 1331var constants = exports;
4878 1332
4879// Helper 1333// Helper
@@ -4894,7 +1348,7 @@ constants._reverse = function reverse(map) {
4894 1348
4895constants.der = require('./der'); 1349constants.der = require('./der');
4896 1350
4897},{"./der":38}],40:[function(require,module,exports){ 1351},{"./der":9}],11:[function(require,module,exports){
4898var inherits = require('inherits'); 1352var inherits = require('inherits');
4899 1353
4900var asn1 = require('../../asn1'); 1354var asn1 = require('../../asn1');
@@ -5220,13 +1674,13 @@ function derDecodeLen(buf, primitive, fail) {
5220 return len; 1674 return len;
5221} 1675}
5222 1676
5223},{"../../asn1":32,"inherits":163}],41:[function(require,module,exports){ 1677},{"../../asn1":3,"inherits":107}],12:[function(require,module,exports){
5224var decoders = exports; 1678var decoders = exports;
5225 1679
5226decoders.der = require('./der'); 1680decoders.der = require('./der');
5227decoders.pem = require('./pem'); 1681decoders.pem = require('./pem');
5228 1682
5229},{"./der":40,"./pem":42}],42:[function(require,module,exports){ 1683},{"./der":11,"./pem":13}],13:[function(require,module,exports){
5230var inherits = require('inherits'); 1684var inherits = require('inherits');
5231var Buffer = require('buffer').Buffer; 1685var Buffer = require('buffer').Buffer;
5232 1686
@@ -5277,7 +1731,7 @@ PEMDecoder.prototype.decode = function decode(data, options) {
5277 return DERDecoder.prototype.decode.call(this, input, options); 1731 return DERDecoder.prototype.decode.call(this, input, options);
5278}; 1732};
5279 1733
5280},{"./der":40,"buffer":107,"inherits":163}],43:[function(require,module,exports){ 1734},{"./der":11,"buffer":53,"inherits":107}],14:[function(require,module,exports){
5281var inherits = require('inherits'); 1735var inherits = require('inherits');
5282var Buffer = require('buffer').Buffer; 1736var Buffer = require('buffer').Buffer;
5283 1737
@@ -5574,13 +2028,13 @@ function encodeTag(tag, primitive, cls, reporter) {
5574 return res; 2028 return res;
5575} 2029}
5576 2030
5577},{"../../asn1":32,"buffer":107,"inherits":163}],44:[function(require,module,exports){ 2031},{"../../asn1":3,"buffer":53,"inherits":107}],15:[function(require,module,exports){
5578var encoders = exports; 2032var encoders = exports;
5579 2033
5580encoders.der = require('./der'); 2034encoders.der = require('./der');
5581encoders.pem = require('./pem'); 2035encoders.pem = require('./pem');
5582 2036
5583},{"./der":43,"./pem":45}],45:[function(require,module,exports){ 2037},{"./der":14,"./pem":16}],16:[function(require,module,exports){
5584var inherits = require('inherits'); 2038var inherits = require('inherits');
5585 2039
5586var DEREncoder = require('./der'); 2040var DEREncoder = require('./der');
@@ -5603,4376 +2057,2954 @@ PEMEncoder.prototype.encode = function encode(data, options) {
5603 return out.join('\n'); 2057 return out.join('\n');
5604}; 2058};
5605 2059
5606},{"./der":43,"inherits":163}],46:[function(require,module,exports){ 2060},{"./der":14,"inherits":107}],17:[function(require,module,exports){
5607module.exports = require('./lib/axios'); 2061// base-x encoding
5608},{"./lib/axios":48}],47:[function(require,module,exports){ 2062// Forked from https://github.com/cryptocoinjs/bs58
5609(function (process){ 2063// Originally written by Mike Hearn for BitcoinJ
5610'use strict'; 2064// Copyright (c) 2011 Google Inc
2065// Ported to JavaScript by Stefan Thomas
2066// Merged Buffer refactorings from base58-native by Stephen Pair
2067// Copyright (c) 2013 BitPay Inc
5611 2068
5612var utils = require('./../utils'); 2069var Buffer = require('safe-buffer').Buffer
5613var settle = require('./../core/settle');
5614var buildURL = require('./../helpers/buildURL');
5615var parseHeaders = require('./../helpers/parseHeaders');
5616var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
5617var createError = require('../core/createError');
5618var btoa = (typeof window !== 'undefined' && window.btoa && window.btoa.bind(window)) || require('./../helpers/btoa');
5619 2070
5620module.exports = function xhrAdapter(config) { 2071module.exports = function base (ALPHABET) {
5621 return new Promise(function dispatchXhrRequest(resolve, reject) { 2072 var ALPHABET_MAP = {}
5622 var requestData = config.data; 2073 var BASE = ALPHABET.length
5623 var requestHeaders = config.headers; 2074 var LEADER = ALPHABET.charAt(0)
5624 2075
5625 if (utils.isFormData(requestData)) { 2076 // pre-compute lookup table
5626 delete requestHeaders['Content-Type']; // Let the browser set it 2077 for (var z = 0; z < ALPHABET.length; z++) {
5627 } 2078 var x = ALPHABET.charAt(z)
5628 2079
5629 var request = new XMLHttpRequest(); 2080 if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous')
5630 var loadEvent = 'onreadystatechange'; 2081 ALPHABET_MAP[x] = z
5631 var xDomain = false; 2082 }
5632 2083
5633 // For IE 8/9 CORS support 2084 function encode (source) {
5634 // Only supports POST and GET calls and doesn't returns the response headers. 2085 if (source.length === 0) return ''
5635 // DON'T do this for testing b/c XMLHttpRequest is mocked, not XDomainRequest.
5636 if (process.env.NODE_ENV !== 'test' &&
5637 typeof window !== 'undefined' &&
5638 window.XDomainRequest && !('withCredentials' in request) &&
5639 !isURLSameOrigin(config.url)) {
5640 request = new window.XDomainRequest();
5641 loadEvent = 'onload';
5642 xDomain = true;
5643 request.onprogress = function handleProgress() {};
5644 request.ontimeout = function handleTimeout() {};
5645 }
5646 2086
5647 // HTTP basic authentication 2087 var digits = [0]
5648 if (config.auth) { 2088 for (var i = 0; i < source.length; ++i) {
5649 var username = config.auth.username || ''; 2089 for (var j = 0, carry = source[i]; j < digits.length; ++j) {
5650 var password = config.auth.password || ''; 2090 carry += digits[j] << 8
5651 requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); 2091 digits[j] = carry % BASE
2092 carry = (carry / BASE) | 0
2093 }
2094
2095 while (carry > 0) {
2096 digits.push(carry % BASE)
2097 carry = (carry / BASE) | 0
2098 }
5652 } 2099 }
5653 2100
5654 request.open(config.method.toUpperCase(), buildURL(config.url, config.params, config.paramsSerializer), true); 2101 var string = ''
5655 2102
5656 // Set the request timeout in MS 2103 // deal with leading zeros
5657 request.timeout = config.timeout; 2104 for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += LEADER
2105 // convert digits to a string
2106 for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]]
5658 2107
5659 // Listen for ready state 2108 return string
5660 request[loadEvent] = function handleLoad() { 2109 }
5661 if (!request || (request.readyState !== 4 && !xDomain)) { 2110
5662 return; 2111 function decodeUnsafe (string) {
2112 if (typeof string !== 'string') throw new TypeError('Expected String')
2113 if (string.length === 0) return Buffer.allocUnsafe(0)
2114
2115 var bytes = [0]
2116 for (var i = 0; i < string.length; i++) {
2117 var value = ALPHABET_MAP[string[i]]
2118 if (value === undefined) return
2119
2120 for (var j = 0, carry = value; j < bytes.length; ++j) {
2121 carry += bytes[j] * BASE
2122 bytes[j] = carry & 0xff
2123 carry >>= 8
5663 } 2124 }
5664 2125
5665 // The request errored out and we didn't get a response, this will be 2126 while (carry > 0) {
5666 // handled by onerror instead 2127 bytes.push(carry & 0xff)
5667 // With one exception: request that using file: protocol, most browsers 2128 carry >>= 8
5668 // will return status as 0 even though it's a successful request
5669 if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
5670 return;
5671 } 2129 }
2130 }
5672 2131
5673 // Prepare the response 2132 // deal with leading zeros
5674 var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; 2133 for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) {
5675 var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; 2134 bytes.push(0)
5676 var response = { 2135 }
5677 data: responseData,
5678 // IE sends 1223 instead of 204 (https://github.com/axios/axios/issues/201)
5679 status: request.status === 1223 ? 204 : request.status,
5680 statusText: request.status === 1223 ? 'No Content' : request.statusText,
5681 headers: responseHeaders,
5682 config: config,
5683 request: request
5684 };
5685 2136
5686 settle(resolve, reject, response); 2137 return Buffer.from(bytes.reverse())
2138 }
5687 2139
5688 // Clean up request 2140 function decode (string) {
5689 request = null; 2141 var buffer = decodeUnsafe(string)
5690 }; 2142 if (buffer) return buffer
5691 2143
5692 // Handle low level network errors 2144 throw new Error('Non-base' + BASE + ' character')
5693 request.onerror = function handleError() { 2145 }
5694 // Real errors are hidden from us by the browser
5695 // onerror should only fire if it's a network error
5696 reject(createError('Network Error', config, null, request));
5697 2146
5698 // Clean up request 2147 return {
5699 request = null; 2148 encode: encode,
5700 }; 2149 decodeUnsafe: decodeUnsafe,
2150 decode: decode
2151 }
2152}
5701 2153
5702 // Handle timeout 2154},{"safe-buffer":156}],18:[function(require,module,exports){
5703 request.ontimeout = function handleTimeout() { 2155'use strict'
5704 reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED',
5705 request));
5706 2156
5707 // Clean up request 2157exports.byteLength = byteLength
5708 request = null; 2158exports.toByteArray = toByteArray
5709 }; 2159exports.fromByteArray = fromByteArray
5710 2160
5711 // Add xsrf header 2161var lookup = []
5712 // This is only done if running in a standard browser environment. 2162var revLookup = []
5713 // Specifically not if we're in a web worker, or react-native. 2163var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
5714 if (utils.isStandardBrowserEnv()) {
5715 var cookies = require('./../helpers/cookies');
5716 2164
5717 // Add xsrf header 2165var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
5718 var xsrfValue = (config.withCredentials || isURLSameOrigin(config.url)) && config.xsrfCookieName ? 2166for (var i = 0, len = code.length; i < len; ++i) {
5719 cookies.read(config.xsrfCookieName) : 2167 lookup[i] = code[i]
5720 undefined; 2168 revLookup[code.charCodeAt(i)] = i
2169}
5721 2170
5722 if (xsrfValue) { 2171revLookup['-'.charCodeAt(0)] = 62
5723 requestHeaders[config.xsrfHeaderName] = xsrfValue; 2172revLookup['_'.charCodeAt(0)] = 63
5724 }
5725 }
5726 2173
5727 // Add headers to the request 2174function placeHoldersCount (b64) {
5728 if ('setRequestHeader' in request) { 2175 var len = b64.length
5729 utils.forEach(requestHeaders, function setRequestHeader(val, key) { 2176 if (len % 4 > 0) {
5730 if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { 2177 throw new Error('Invalid string. Length must be a multiple of 4')
5731 // Remove Content-Type if data is undefined 2178 }
5732 delete requestHeaders[key];
5733 } else {
5734 // Otherwise add header to the request
5735 request.setRequestHeader(key, val);
5736 }
5737 });
5738 }
5739 2179
5740 // Add withCredentials to request if needed 2180 // the number of equal signs (place holders)
5741 if (config.withCredentials) { 2181 // if there are two placeholders, than the two characters before it
5742 request.withCredentials = true; 2182 // represent one byte
5743 } 2183 // if there is only one, then the three characters before it represent 2 bytes
2184 // this is just a cheap hack to not do indexOf twice
2185 return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
2186}
5744 2187
5745 // Add responseType to request if needed 2188function byteLength (b64) {
5746 if (config.responseType) { 2189 // base64 is 4/3 + up to two characters of the original data
5747 try { 2190 return (b64.length * 3 / 4) - placeHoldersCount(b64)
5748 request.responseType = config.responseType; 2191}
5749 } catch (e) {
5750 // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
5751 // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
5752 if (config.responseType !== 'json') {
5753 throw e;
5754 }
5755 }
5756 }
5757 2192
5758 // Handle progress if needed 2193function toByteArray (b64) {
5759 if (typeof config.onDownloadProgress === 'function') { 2194 var i, l, tmp, placeHolders, arr
5760 request.addEventListener('progress', config.onDownloadProgress); 2195 var len = b64.length
5761 } 2196 placeHolders = placeHoldersCount(b64)
5762 2197
5763 // Not all browsers support upload events 2198 arr = new Arr((len * 3 / 4) - placeHolders)
5764 if (typeof config.onUploadProgress === 'function' && request.upload) {
5765 request.upload.addEventListener('progress', config.onUploadProgress);
5766 }
5767 2199
5768 if (config.cancelToken) { 2200 // if there are placeholders, only get up to the last complete 4 chars
5769 // Handle cancellation 2201 l = placeHolders > 0 ? len - 4 : len
5770 config.cancelToken.promise.then(function onCanceled(cancel) {
5771 if (!request) {
5772 return;
5773 }
5774 2202
5775 request.abort(); 2203 var L = 0
5776 reject(cancel);
5777 // Clean up request
5778 request = null;
5779 });
5780 }
5781 2204
5782 if (requestData === undefined) { 2205 for (i = 0; i < l; i += 4) {
5783 requestData = null; 2206 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
5784 } 2207 arr[L++] = (tmp >> 16) & 0xFF
2208 arr[L++] = (tmp >> 8) & 0xFF
2209 arr[L++] = tmp & 0xFF
2210 }
5785 2211
5786 // Send the request 2212 if (placeHolders === 2) {
5787 request.send(requestData); 2213 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
5788 }); 2214 arr[L++] = tmp & 0xFF
5789}; 2215 } else if (placeHolders === 1) {
2216 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
2217 arr[L++] = (tmp >> 8) & 0xFF
2218 arr[L++] = tmp & 0xFF
2219 }
5790 2220
5791}).call(this,require('_process')) 2221 return arr
5792},{"../core/createError":54,"./../core/settle":57,"./../helpers/btoa":61,"./../helpers/buildURL":62,"./../helpers/cookies":64,"./../helpers/isURLSameOrigin":66,"./../helpers/parseHeaders":68,"./../utils":70,"_process":190}],48:[function(require,module,exports){ 2222}
5793'use strict';
5794 2223
5795var utils = require('./utils'); 2224function tripletToBase64 (num) {
5796var bind = require('./helpers/bind'); 2225 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
5797var Axios = require('./core/Axios'); 2226}
5798var defaults = require('./defaults');
5799 2227
5800/** 2228function encodeChunk (uint8, start, end) {
5801 * Create an instance of Axios 2229 var tmp
5802 * 2230 var output = []
5803 * @param {Object} defaultConfig The default config for the instance 2231 for (var i = start; i < end; i += 3) {
5804 * @return {Axios} A new instance of Axios 2232 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
5805 */ 2233 output.push(tripletToBase64(tmp))
5806function createInstance(defaultConfig) { 2234 }
5807 var context = new Axios(defaultConfig); 2235 return output.join('')
5808 var instance = bind(Axios.prototype.request, context); 2236}
5809 2237
5810 // Copy axios.prototype to instance 2238function fromByteArray (uint8) {
5811 utils.extend(instance, Axios.prototype, context); 2239 var tmp
2240 var len = uint8.length
2241 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
2242 var output = ''
2243 var parts = []
2244 var maxChunkLength = 16383 // must be multiple of 3
5812 2245
5813 // Copy context to instance 2246 // go through the array every three bytes, we'll deal with trailing stuff later
5814 utils.extend(instance, context); 2247 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
2248 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
2249 }
5815 2250
5816 return instance; 2251 // pad the end with zeros, but make sure to not forget the extra bytes
2252 if (extraBytes === 1) {
2253 tmp = uint8[len - 1]
2254 output += lookup[tmp >> 2]
2255 output += lookup[(tmp << 4) & 0x3F]
2256 output += '=='
2257 } else if (extraBytes === 2) {
2258 tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
2259 output += lookup[tmp >> 10]
2260 output += lookup[(tmp >> 4) & 0x3F]
2261 output += lookup[(tmp << 2) & 0x3F]
2262 output += '='
2263 }
2264
2265 parts.push(output)
2266
2267 return parts.join('')
5817} 2268}
5818 2269
5819// Create the default instance to be exported 2270},{}],19:[function(require,module,exports){
5820var axios = createInstance(defaults); 2271/*! bignumber.js v5.0.0 https://github.com/MikeMcl/bignumber.js/LICENCE */
5821 2272
5822// Expose Axios class to allow class inheritance 2273;(function (globalObj) {
5823axios.Axios = Axios; 2274 'use strict';
5824 2275
5825// Factory for creating new instances 2276 /*
5826axios.create = function create(instanceConfig) { 2277 bignumber.js v5.0.0
5827 return createInstance(utils.merge(defaults, instanceConfig)); 2278 A JavaScript library for arbitrary-precision arithmetic.
5828}; 2279 https://github.com/MikeMcl/bignumber.js
2280 Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com>
2281 MIT Expat Licence
2282 */
5829 2283
5830// Expose Cancel & CancelToken
5831axios.Cancel = require('./cancel/Cancel');
5832axios.CancelToken = require('./cancel/CancelToken');
5833axios.isCancel = require('./cancel/isCancel');
5834 2284
5835// Expose all/spread 2285 var BigNumber,
5836axios.all = function all(promises) { 2286 isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
5837 return Promise.all(promises); 2287 mathceil = Math.ceil,
5838}; 2288 mathfloor = Math.floor,
5839axios.spread = require('./helpers/spread'); 2289 notBool = ' not a boolean or binary digit',
2290 roundingMode = 'rounding mode',
2291 tooManyDigits = 'number type has more than 15 significant digits',
2292 ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_',
2293 BASE = 1e14,
2294 LOG_BASE = 14,
2295 MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1
2296 // MAX_INT32 = 0x7fffffff, // 2^31 - 1
2297 POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
2298 SQRT_BASE = 1e7,
2299
2300 /*
2301 * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
2302 * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an
2303 * exception is thrown (if ERRORS is true).
2304 */
2305 MAX = 1E9; // 0 to MAX_INT32
2306
2307
2308 /*
2309 * Create and return a BigNumber constructor.
2310 */
2311 function constructorFactory(config) {
2312 var div, parseNumeric,
2313
2314 // id tracks the caller function, so its name can be included in error messages.
2315 id = 0,
2316 P = BigNumber.prototype,
2317 ONE = new BigNumber(1),
2318
2319
2320 /********************************* EDITABLE DEFAULTS **********************************/
2321
2322
2323 /*
2324 * The default values below must be integers within the inclusive ranges stated.
2325 * The values can also be changed at run-time using BigNumber.config.
2326 */
2327
2328 // The maximum number of decimal places for operations involving division.
2329 DECIMAL_PLACES = 20, // 0 to MAX
2330
2331 /*
2332 * The rounding mode used when rounding to the above decimal places, and when using
2333 * toExponential, toFixed, toFormat and toPrecision, and round (default value).
2334 * UP 0 Away from zero.
2335 * DOWN 1 Towards zero.
2336 * CEIL 2 Towards +Infinity.
2337 * FLOOR 3 Towards -Infinity.
2338 * HALF_UP 4 Towards nearest neighbour. If equidistant, up.
2339 * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
2340 * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
2341 * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
2342 * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
2343 */
2344 ROUNDING_MODE = 4, // 0 to 8
2345
2346 // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
2347
2348 // The exponent value at and beneath which toString returns exponential notation.
2349 // Number type: -7
2350 TO_EXP_NEG = -7, // 0 to -MAX
2351
2352 // The exponent value at and above which toString returns exponential notation.
2353 // Number type: 21
2354 TO_EXP_POS = 21, // 0 to MAX
2355
2356 // RANGE : [MIN_EXP, MAX_EXP]
2357
2358 // The minimum exponent value, beneath which underflow to zero occurs.
2359 // Number type: -324 (5e-324)
2360 MIN_EXP = -1e7, // -1 to -MAX
2361
2362 // The maximum exponent value, above which overflow to Infinity occurs.
2363 // Number type: 308 (1.7976931348623157e+308)
2364 // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
2365 MAX_EXP = 1e7, // 1 to MAX
2366
2367 // Whether BigNumber Errors are ever thrown.
2368 ERRORS = true, // true or false
2369
2370 // Change to intValidatorNoErrors if ERRORS is false.
2371 isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors
2372
2373 // Whether to use cryptographically-secure random number generation, if available.
2374 CRYPTO = false, // true or false
2375
2376 /*
2377 * The modulo mode used when calculating the modulus: a mod n.
2378 * The quotient (q = a / n) is calculated according to the corresponding rounding mode.
2379 * The remainder (r) is calculated as: r = a - n * q.
2380 *
2381 * UP 0 The remainder is positive if the dividend is negative, else is negative.
2382 * DOWN 1 The remainder has the same sign as the dividend.
2383 * This modulo mode is commonly known as 'truncated division' and is
2384 * equivalent to (a % n) in JavaScript.
2385 * FLOOR 3 The remainder has the same sign as the divisor (Python %).
2386 * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
2387 * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
2388 * The remainder is always positive.
2389 *
2390 * The truncated division, floored division, Euclidian division and IEEE 754 remainder
2391 * modes are commonly used for the modulus operation.
2392 * Although the other rounding modes can also be used, they may not give useful results.
2393 */
2394 MODULO_MODE = 1, // 0 to 9
2395
2396 // The maximum number of significant digits of the result of the toPower operation.
2397 // If POW_PRECISION is 0, there will be unlimited significant digits.
2398 POW_PRECISION = 0, // 0 to MAX
2399
2400 // The format specification used by the BigNumber.prototype.toFormat method.
2401 FORMAT = {
2402 decimalSeparator: '.',
2403 groupSeparator: ',',
2404 groupSize: 3,
2405 secondaryGroupSize: 0,
2406 fractionGroupSeparator: '\xA0', // non-breaking space
2407 fractionGroupSize: 0
2408 };
5840 2409
5841module.exports = axios;
5842 2410
5843// Allow use of default import syntax in TypeScript 2411 /******************************************************************************************/
5844module.exports.default = axios;
5845 2412
5846},{"./cancel/Cancel":49,"./cancel/CancelToken":50,"./cancel/isCancel":51,"./core/Axios":52,"./defaults":59,"./helpers/bind":60,"./helpers/spread":69,"./utils":70}],49:[function(require,module,exports){
5847'use strict';
5848 2413
5849/** 2414 // CONSTRUCTOR
5850 * A `Cancel` is an object that is thrown when an operation is canceled.
5851 *
5852 * @class
5853 * @param {string=} message The message.
5854 */
5855function Cancel(message) {
5856 this.message = message;
5857}
5858 2415
5859Cancel.prototype.toString = function toString() {
5860 return 'Cancel' + (this.message ? ': ' + this.message : '');
5861};
5862 2416
5863Cancel.prototype.__CANCEL__ = true; 2417 /*
2418 * The BigNumber constructor and exported function.
2419 * Create and return a new instance of a BigNumber object.
2420 *
2421 * n {number|string|BigNumber} A numeric value.
2422 * [b] {number} The base of n. Integer, 2 to 64 inclusive.
2423 */
2424 function BigNumber( n, b ) {
2425 var c, e, i, num, len, str,
2426 x = this;
5864 2427
5865module.exports = Cancel; 2428 // Enable constructor usage without new.
2429 if ( !( x instanceof BigNumber ) ) {
5866 2430
5867},{}],50:[function(require,module,exports){ 2431 // 'BigNumber() constructor call without new: {n}'
5868'use strict'; 2432 // See GitHub issue: #81.
2433 //if (ERRORS) raise( 26, 'constructor call without new', n );
2434 return new BigNumber( n, b );
2435 }
5869 2436
5870var Cancel = require('./Cancel'); 2437 // 'new BigNumber() base not an integer: {b}'
2438 // 'new BigNumber() base out of range: {b}'
2439 if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) {
2440
2441 // Duplicate.
2442 if ( n instanceof BigNumber ) {
2443 x.s = n.s;
2444 x.e = n.e;
2445 x.c = ( n = n.c ) ? n.slice() : n;
2446 id = 0;
2447 return;
2448 }
5871 2449
5872/** 2450 if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) {
5873 * A `CancelToken` is an object that can be used to request cancellation of an operation. 2451 x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1;
5874 * 2452
5875 * @class 2453 // Fast path for integers.
5876 * @param {Function} executor The executor function. 2454 if ( n === ~~n ) {
5877 */ 2455 for ( e = 0, i = n; i >= 10; i /= 10, e++ );
5878function CancelToken(executor) { 2456 x.e = e;
5879 if (typeof executor !== 'function') { 2457 x.c = [n];
5880 throw new TypeError('executor must be a function.'); 2458 id = 0;
5881 } 2459 return;
2460 }
2461
2462 str = n + '';
2463 } else {
2464 if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num );
2465 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
2466 }
2467 } else {
2468 b = b | 0;
2469 str = n + '';
2470
2471 // Ensure return value is rounded to DECIMAL_PLACES as with other bases.
2472 // Allow exponential notation to be used with base 10 argument.
2473 if ( b == 10 ) {
2474 x = new BigNumber( n instanceof BigNumber ? n : str );
2475 return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE );
2476 }
5882 2477
5883 var resolvePromise; 2478 // Avoid potential interpretation of Infinity and NaN as base 44+ values.
5884 this.promise = new Promise(function promiseExecutor(resolve) { 2479 // Any number in exponential form will fail due to the [Ee][+-].
5885 resolvePromise = resolve; 2480 if ( ( num = typeof n == 'number' ) && n * 0 != 0 ||
5886 }); 2481 !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) +
2482 '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) {
2483 return parseNumeric( x, str, num, b );
2484 }
5887 2485
5888 var token = this; 2486 if (num) {
5889 executor(function cancel(message) { 2487 x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1;
5890 if (token.reason) {
5891 // Cancellation has already been requested
5892 return;
5893 }
5894 2488
5895 token.reason = new Cancel(message); 2489 if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) {
5896 resolvePromise(token.reason);
5897 });
5898}
5899 2490
5900/** 2491 // 'new BigNumber() number type has more than 15 significant digits: {n}'
5901 * Throws a `Cancel` if cancellation has been requested. 2492 raise( id, tooManyDigits, n );
5902 */ 2493 }
5903CancelToken.prototype.throwIfRequested = function throwIfRequested() {
5904 if (this.reason) {
5905 throw this.reason;
5906 }
5907};
5908 2494
5909/** 2495 // Prevent later check for length on converted number.
5910 * Returns an object that contains a new `CancelToken` and a function that, when called, 2496 num = false;
5911 * cancels the `CancelToken`. 2497 } else {
5912 */ 2498 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
5913CancelToken.source = function source() { 2499 }
5914 var cancel;
5915 var token = new CancelToken(function executor(c) {
5916 cancel = c;
5917 });
5918 return {
5919 token: token,
5920 cancel: cancel
5921 };
5922};
5923 2500
5924module.exports = CancelToken; 2501 str = convertBase( str, 10, b, x.s );
2502 }
5925 2503
5926},{"./Cancel":49}],51:[function(require,module,exports){ 2504 // Decimal point?
5927'use strict'; 2505 if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' );
5928 2506
5929module.exports = function isCancel(value) { 2507 // Exponential form?
5930 return !!(value && value.__CANCEL__); 2508 if ( ( i = str.search( /e/i ) ) > 0 ) {
5931};
5932 2509
5933},{}],52:[function(require,module,exports){ 2510 // Determine exponent.
5934'use strict'; 2511 if ( e < 0 ) e = i;
2512 e += +str.slice( i + 1 );
2513 str = str.substring( 0, i );
2514 } else if ( e < 0 ) {
5935 2515
5936var defaults = require('./../defaults'); 2516 // Integer.
5937var utils = require('./../utils'); 2517 e = str.length;
5938var InterceptorManager = require('./InterceptorManager'); 2518 }
5939var dispatchRequest = require('./dispatchRequest');
5940 2519
5941/** 2520 // Determine leading zeros.
5942 * Create a new instance of Axios 2521 for ( i = 0; str.charCodeAt(i) === 48; i++ );
5943 *
5944 * @param {Object} instanceConfig The default config for the instance
5945 */
5946function Axios(instanceConfig) {
5947 this.defaults = instanceConfig;
5948 this.interceptors = {
5949 request: new InterceptorManager(),
5950 response: new InterceptorManager()
5951 };
5952}
5953 2522
5954/** 2523 // Determine trailing zeros.
5955 * Dispatch a request 2524 for ( len = str.length; str.charCodeAt(--len) === 48; );
5956 * 2525 str = str.slice( i, len + 1 );
5957 * @param {Object} config The config specific for this request (merged with this.defaults)
5958 */
5959Axios.prototype.request = function request(config) {
5960 /*eslint no-param-reassign:0*/
5961 // Allow for axios('example/url'[, config]) a la fetch API
5962 if (typeof config === 'string') {
5963 config = utils.merge({
5964 url: arguments[0]
5965 }, arguments[1]);
5966 }
5967 2526
5968 config = utils.merge(defaults, {method: 'get'}, this.defaults, config); 2527 if (str) {
5969 config.method = config.method.toLowerCase(); 2528 len = str.length;
5970 2529
5971 // Hook up interceptors middleware 2530 // Disallow numbers with over 15 significant digits if number type.
5972 var chain = [dispatchRequest, undefined]; 2531 // 'new BigNumber() number type has more than 15 significant digits: {n}'
5973 var promise = Promise.resolve(config); 2532 if ( num && ERRORS && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) {
2533 raise( id, tooManyDigits, x.s * n );
2534 }
5974 2535
5975 this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { 2536 e = e - i - 1;
5976 chain.unshift(interceptor.fulfilled, interceptor.rejected);
5977 });
5978 2537
5979 this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { 2538 // Overflow?
5980 chain.push(interceptor.fulfilled, interceptor.rejected); 2539 if ( e > MAX_EXP ) {
5981 });
5982 2540
5983 while (chain.length) { 2541 // Infinity.
5984 promise = promise.then(chain.shift(), chain.shift()); 2542 x.c = x.e = null;
5985 }
5986 2543
5987 return promise; 2544 // Underflow?
5988}; 2545 } else if ( e < MIN_EXP ) {
5989 2546
5990// Provide aliases for supported request methods 2547 // Zero.
5991utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { 2548 x.c = [ x.e = 0 ];
5992 /*eslint func-names:0*/ 2549 } else {
5993 Axios.prototype[method] = function(url, config) { 2550 x.e = e;
5994 return this.request(utils.merge(config || {}, { 2551 x.c = [];
5995 method: method,
5996 url: url
5997 }));
5998 };
5999});
6000 2552
6001utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { 2553 // Transform base
6002 /*eslint func-names:0*/
6003 Axios.prototype[method] = function(url, data, config) {
6004 return this.request(utils.merge(config || {}, {
6005 method: method,
6006 url: url,
6007 data: data
6008 }));
6009 };
6010});
6011 2554
6012module.exports = Axios; 2555 // e is the base 10 exponent.
2556 // i is where to slice str to get the first element of the coefficient array.
2557 i = ( e + 1 ) % LOG_BASE;
2558 if ( e < 0 ) i += LOG_BASE;
6013 2559
6014},{"./../defaults":59,"./../utils":70,"./InterceptorManager":53,"./dispatchRequest":55}],53:[function(require,module,exports){ 2560 if ( i < len ) {
6015'use strict'; 2561 if (i) x.c.push( +str.slice( 0, i ) );
6016 2562
6017var utils = require('./../utils'); 2563 for ( len -= LOG_BASE; i < len; ) {
2564 x.c.push( +str.slice( i, i += LOG_BASE ) );
2565 }
6018 2566
6019function InterceptorManager() { 2567 str = str.slice(i);
6020 this.handlers = []; 2568 i = LOG_BASE - str.length;
6021} 2569 } else {
2570 i -= len;
2571 }
6022 2572
6023/** 2573 for ( ; i--; str += '0' );
6024 * Add a new interceptor to the stack 2574 x.c.push( +str );
6025 * 2575 }
6026 * @param {Function} fulfilled The function to handle `then` for a `Promise` 2576 } else {
6027 * @param {Function} rejected The function to handle `reject` for a `Promise`
6028 *
6029 * @return {Number} An ID used to remove interceptor later
6030 */
6031InterceptorManager.prototype.use = function use(fulfilled, rejected) {
6032 this.handlers.push({
6033 fulfilled: fulfilled,
6034 rejected: rejected
6035 });
6036 return this.handlers.length - 1;
6037};
6038 2577
6039/** 2578 // Zero.
6040 * Remove an interceptor from the stack 2579 x.c = [ x.e = 0 ];
6041 * 2580 }
6042 * @param {Number} id The ID that was returned by `use`
6043 */
6044InterceptorManager.prototype.eject = function eject(id) {
6045 if (this.handlers[id]) {
6046 this.handlers[id] = null;
6047 }
6048};
6049 2581
6050/** 2582 id = 0;
6051 * Iterate over all the registered interceptors 2583 }
6052 *
6053 * This method is particularly useful for skipping over any
6054 * interceptors that may have become `null` calling `eject`.
6055 *
6056 * @param {Function} fn The function to call for each interceptor
6057 */
6058InterceptorManager.prototype.forEach = function forEach(fn) {
6059 utils.forEach(this.handlers, function forEachHandler(h) {
6060 if (h !== null) {
6061 fn(h);
6062 }
6063 });
6064};
6065 2584
6066module.exports = InterceptorManager;
6067 2585
6068},{"./../utils":70}],54:[function(require,module,exports){ 2586 // CONSTRUCTOR PROPERTIES
6069'use strict'; 2587
2588
2589 BigNumber.another = constructorFactory;
2590
2591 BigNumber.ROUND_UP = 0;
2592 BigNumber.ROUND_DOWN = 1;
2593 BigNumber.ROUND_CEIL = 2;
2594 BigNumber.ROUND_FLOOR = 3;
2595 BigNumber.ROUND_HALF_UP = 4;
2596 BigNumber.ROUND_HALF_DOWN = 5;
2597 BigNumber.ROUND_HALF_EVEN = 6;
2598 BigNumber.ROUND_HALF_CEIL = 7;
2599 BigNumber.ROUND_HALF_FLOOR = 8;
2600 BigNumber.EUCLID = 9;
2601
2602
2603 /*
2604 * Configure infrequently-changing library-wide settings.
2605 *
2606 * Accept an object or an argument list, with one or many of the following properties or
2607 * parameters respectively:
2608 *
2609 * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive
2610 * ROUNDING_MODE {number} Integer, 0 to 8 inclusive
2611 * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or
2612 * [integer -MAX to 0 incl., 0 to MAX incl.]
2613 * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
2614 * [integer -MAX to -1 incl., integer 1 to MAX incl.]
2615 * ERRORS {boolean|number} true, false, 1 or 0
2616 * CRYPTO {boolean|number} true, false, 1 or 0
2617 * MODULO_MODE {number} 0 to 9 inclusive
2618 * POW_PRECISION {number} 0 to MAX inclusive
2619 * FORMAT {object} See BigNumber.prototype.toFormat
2620 * decimalSeparator {string}
2621 * groupSeparator {string}
2622 * groupSize {number}
2623 * secondaryGroupSize {number}
2624 * fractionGroupSeparator {string}
2625 * fractionGroupSize {number}
2626 *
2627 * (The values assigned to the above FORMAT object properties are not checked for validity.)
2628 *
2629 * E.g.
2630 * BigNumber.config(20, 4) is equivalent to
2631 * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
2632 *
2633 * Ignore properties/parameters set to null or undefined.
2634 * Return an object with the properties current values.
2635 */
2636 BigNumber.config = BigNumber.set = function () {
2637 var v, p,
2638 i = 0,
2639 r = {},
2640 a = arguments,
2641 o = a[0],
2642 has = o && typeof o == 'object'
2643 ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; }
2644 : function () { if ( a.length > i ) return ( v = a[i++] ) != null; };
2645
2646 // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
2647 // 'config() DECIMAL_PLACES not an integer: {v}'
2648 // 'config() DECIMAL_PLACES out of range: {v}'
2649 if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) {
2650 DECIMAL_PLACES = v | 0;
2651 }
2652 r[p] = DECIMAL_PLACES;
6070 2653
6071var enhanceError = require('./enhanceError'); 2654 // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
2655 // 'config() ROUNDING_MODE not an integer: {v}'
2656 // 'config() ROUNDING_MODE out of range: {v}'
2657 if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) {
2658 ROUNDING_MODE = v | 0;
2659 }
2660 r[p] = ROUNDING_MODE;
2661
2662 // EXPONENTIAL_AT {number|number[]}
2663 // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive].
2664 // 'config() EXPONENTIAL_AT not an integer: {v}'
2665 // 'config() EXPONENTIAL_AT out of range: {v}'
2666 if ( has( p = 'EXPONENTIAL_AT' ) ) {
2667
2668 if ( isArray(v) ) {
2669 if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) {
2670 TO_EXP_NEG = v[0] | 0;
2671 TO_EXP_POS = v[1] | 0;
2672 }
2673 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
2674 TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 );
2675 }
2676 }
2677 r[p] = [ TO_EXP_NEG, TO_EXP_POS ];
2678
2679 // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
2680 // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
2681 // 'config() RANGE not an integer: {v}'
2682 // 'config() RANGE cannot be zero: {v}'
2683 // 'config() RANGE out of range: {v}'
2684 if ( has( p = 'RANGE' ) ) {
2685
2686 if ( isArray(v) ) {
2687 if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) {
2688 MIN_EXP = v[0] | 0;
2689 MAX_EXP = v[1] | 0;
2690 }
2691 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
2692 if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 );
2693 else if (ERRORS) raise( 2, p + ' cannot be zero', v );
2694 }
2695 }
2696 r[p] = [ MIN_EXP, MAX_EXP ];
6072 2697
6073/** 2698 // ERRORS {boolean|number} true, false, 1 or 0.
6074 * Create an Error with the specified message, config, error code, request and response. 2699 // 'config() ERRORS not a boolean or binary digit: {v}'
6075 * 2700 if ( has( p = 'ERRORS' ) ) {
6076 * @param {string} message The error message.
6077 * @param {Object} config The config.
6078 * @param {string} [code] The error code (for example, 'ECONNABORTED').
6079 * @param {Object} [request] The request.
6080 * @param {Object} [response] The response.
6081 * @returns {Error} The created error.
6082 */
6083module.exports = function createError(message, config, code, request, response) {
6084 var error = new Error(message);
6085 return enhanceError(error, config, code, request, response);
6086};
6087 2701
6088},{"./enhanceError":56}],55:[function(require,module,exports){ 2702 if ( v === !!v || v === 1 || v === 0 ) {
6089'use strict'; 2703 id = 0;
2704 isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors;
2705 } else if (ERRORS) {
2706 raise( 2, p + notBool, v );
2707 }
2708 }
2709 r[p] = ERRORS;
2710
2711 // CRYPTO {boolean|number} true, false, 1 or 0.
2712 // 'config() CRYPTO not a boolean or binary digit: {v}'
2713 // 'config() crypto unavailable: {crypto}'
2714 if ( has( p = 'CRYPTO' ) ) {
2715
2716 if ( v === true || v === false || v === 1 || v === 0 ) {
2717 if (v) {
2718 v = typeof crypto == 'undefined';
2719 if ( !v && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
2720 CRYPTO = true;
2721 } else if (ERRORS) {
2722 raise( 2, 'crypto unavailable', v ? void 0 : crypto );
2723 } else {
2724 CRYPTO = false;
2725 }
2726 } else {
2727 CRYPTO = false;
2728 }
2729 } else if (ERRORS) {
2730 raise( 2, p + notBool, v );
2731 }
2732 }
2733 r[p] = CRYPTO;
6090 2734
6091var utils = require('./../utils'); 2735 // MODULO_MODE {number} Integer, 0 to 9 inclusive.
6092var transformData = require('./transformData'); 2736 // 'config() MODULO_MODE not an integer: {v}'
6093var isCancel = require('../cancel/isCancel'); 2737 // 'config() MODULO_MODE out of range: {v}'
6094var defaults = require('../defaults'); 2738 if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) {
6095var isAbsoluteURL = require('./../helpers/isAbsoluteURL'); 2739 MODULO_MODE = v | 0;
6096var combineURLs = require('./../helpers/combineURLs'); 2740 }
2741 r[p] = MODULO_MODE;
6097 2742
6098/** 2743 // POW_PRECISION {number} Integer, 0 to MAX inclusive.
6099 * Throws a `Cancel` if cancellation has been requested. 2744 // 'config() POW_PRECISION not an integer: {v}'
6100 */ 2745 // 'config() POW_PRECISION out of range: {v}'
6101function throwIfCancellationRequested(config) { 2746 if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) {
6102 if (config.cancelToken) { 2747 POW_PRECISION = v | 0;
6103 config.cancelToken.throwIfRequested(); 2748 }
6104 } 2749 r[p] = POW_PRECISION;
6105}
6106 2750
6107/** 2751 // FORMAT {object}
6108 * Dispatch a request to the server using the configured adapter. 2752 // 'config() FORMAT not an object: {v}'
6109 * 2753 if ( has( p = 'FORMAT' ) ) {
6110 * @param {object} config The config that is to be used for the request
6111 * @returns {Promise} The Promise to be fulfilled
6112 */
6113module.exports = function dispatchRequest(config) {
6114 throwIfCancellationRequested(config);
6115 2754
6116 // Support baseURL config 2755 if ( typeof v == 'object' ) {
6117 if (config.baseURL && !isAbsoluteURL(config.url)) { 2756 FORMAT = v;
6118 config.url = combineURLs(config.baseURL, config.url); 2757 } else if (ERRORS) {
6119 } 2758 raise( 2, p + ' not an object', v );
2759 }
2760 }
2761 r[p] = FORMAT;
6120 2762
6121 // Ensure headers exist 2763 return r;
6122 config.headers = config.headers || {}; 2764 };
6123 2765
6124 // Transform request data
6125 config.data = transformData(
6126 config.data,
6127 config.headers,
6128 config.transformRequest
6129 );
6130 2766
6131 // Flatten headers 2767 /*
6132 config.headers = utils.merge( 2768 * Return a new BigNumber whose value is the maximum of the arguments.
6133 config.headers.common || {}, 2769 *
6134 config.headers[config.method] || {}, 2770 * arguments {number|string|BigNumber}
6135 config.headers || {} 2771 */
6136 ); 2772 BigNumber.max = function () { return maxOrMin( arguments, P.lt ); };
2773
2774
2775 /*
2776 * Return a new BigNumber whose value is the minimum of the arguments.
2777 *
2778 * arguments {number|string|BigNumber}
2779 */
2780 BigNumber.min = function () { return maxOrMin( arguments, P.gt ); };
2781
2782
2783 /*
2784 * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
2785 * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
2786 * zeros are produced).
2787 *
2788 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
2789 *
2790 * 'random() decimal places not an integer: {dp}'
2791 * 'random() decimal places out of range: {dp}'
2792 * 'random() crypto unavailable: {crypto}'
2793 */
2794 BigNumber.random = (function () {
2795 var pow2_53 = 0x20000000000000;
2796
2797 // Return a 53 bit integer n, where 0 <= n < 9007199254740992.
2798 // Check if Math.random() produces more than 32 bits of randomness.
2799 // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
2800 // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
2801 var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
2802 ? function () { return mathfloor( Math.random() * pow2_53 ); }
2803 : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
2804 (Math.random() * 0x800000 | 0); };
2805
2806 return function (dp) {
2807 var a, b, e, k, v,
2808 i = 0,
2809 c = [],
2810 rand = new BigNumber(ONE);
2811
2812 dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0;
2813 k = mathceil( dp / LOG_BASE );
2814
2815 if (CRYPTO) {
2816
2817 // Browsers supporting crypto.getRandomValues.
2818 if (crypto.getRandomValues) {
2819
2820 a = crypto.getRandomValues( new Uint32Array( k *= 2 ) );
2821
2822 for ( ; i < k; ) {
2823
2824 // 53 bits:
2825 // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
2826 // 11111 11111111 11111111 11111111 11100000 00000000 00000000
2827 // ((Math.pow(2, 32) - 1) >>> 11).toString(2)
2828 // 11111 11111111 11111111
2829 // 0x20000 is 2^21.
2830 v = a[i] * 0x20000 + (a[i + 1] >>> 11);
2831
2832 // Rejection sampling:
2833 // 0 <= v < 9007199254740992
2834 // Probability that v >= 9e15, is
2835 // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
2836 if ( v >= 9e15 ) {
2837 b = crypto.getRandomValues( new Uint32Array(2) );
2838 a[i] = b[0];
2839 a[i + 1] = b[1];
2840 } else {
2841
2842 // 0 <= v <= 8999999999999999
2843 // 0 <= (v % 1e14) <= 99999999999999
2844 c.push( v % 1e14 );
2845 i += 2;
2846 }
2847 }
2848 i = k / 2;
2849
2850 // Node.js supporting crypto.randomBytes.
2851 } else if (crypto.randomBytes) {
2852
2853 // buffer
2854 a = crypto.randomBytes( k *= 7 );
2855
2856 for ( ; i < k; ) {
2857
2858 // 0x1000000000000 is 2^48, 0x10000000000 is 2^40
2859 // 0x100000000 is 2^32, 0x1000000 is 2^24
2860 // 11111 11111111 11111111 11111111 11111111 11111111 11111111
2861 // 0 <= v < 9007199254740992
2862 v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) +
2863 ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) +
2864 ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6];
2865
2866 if ( v >= 9e15 ) {
2867 crypto.randomBytes(7).copy( a, i );
2868 } else {
2869
2870 // 0 <= (v % 1e14) <= 99999999999999
2871 c.push( v % 1e14 );
2872 i += 7;
2873 }
2874 }
2875 i = k / 7;
2876 } else {
2877 CRYPTO = false;
2878 if (ERRORS) raise( 14, 'crypto unavailable', crypto );
2879 }
2880 }
6137 2881
6138 utils.forEach( 2882 // Use Math.random.
6139 ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], 2883 if (!CRYPTO) {
6140 function cleanHeaderConfig(method) {
6141 delete config.headers[method];
6142 }
6143 );
6144 2884
6145 var adapter = config.adapter || defaults.adapter; 2885 for ( ; i < k; ) {
2886 v = random53bitInt();
2887 if ( v < 9e15 ) c[i++] = v % 1e14;
2888 }
2889 }
6146 2890
6147 return adapter(config).then(function onAdapterResolution(response) { 2891 k = c[--i];
6148 throwIfCancellationRequested(config); 2892 dp %= LOG_BASE;
6149 2893
6150 // Transform response data 2894 // Convert trailing digits to zeros according to dp.
6151 response.data = transformData( 2895 if ( k && dp ) {
6152 response.data, 2896 v = POWS_TEN[LOG_BASE - dp];
6153 response.headers, 2897 c[i] = mathfloor( k / v ) * v;
6154 config.transformResponse 2898 }
6155 );
6156 2899
6157 return response; 2900 // Remove trailing elements which are zero.
6158 }, function onAdapterRejection(reason) { 2901 for ( ; c[i] === 0; c.pop(), i-- );
6159 if (!isCancel(reason)) {
6160 throwIfCancellationRequested(config);
6161
6162 // Transform response data
6163 if (reason && reason.response) {
6164 reason.response.data = transformData(
6165 reason.response.data,
6166 reason.response.headers,
6167 config.transformResponse
6168 );
6169 }
6170 }
6171 2902
6172 return Promise.reject(reason); 2903 // Zero?
6173 }); 2904 if ( i < 0 ) {
6174}; 2905 c = [ e = 0 ];
2906 } else {
6175 2907
6176},{"../cancel/isCancel":51,"../defaults":59,"./../helpers/combineURLs":63,"./../helpers/isAbsoluteURL":65,"./../utils":70,"./transformData":58}],56:[function(require,module,exports){ 2908 // Remove leading elements which are zero and adjust exponent accordingly.
6177'use strict'; 2909 for ( e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);
6178 2910
6179/** 2911 // Count the digits of the first element of c to determine leading zeros, and...
6180 * Update an Error with the specified config, error code, and response. 2912 for ( i = 1, v = c[0]; v >= 10; v /= 10, i++);
6181 *
6182 * @param {Error} error The error to update.
6183 * @param {Object} config The config.
6184 * @param {string} [code] The error code (for example, 'ECONNABORTED').
6185 * @param {Object} [request] The request.
6186 * @param {Object} [response] The response.
6187 * @returns {Error} The error.
6188 */
6189module.exports = function enhanceError(error, config, code, request, response) {
6190 error.config = config;
6191 if (code) {
6192 error.code = code;
6193 }
6194 error.request = request;
6195 error.response = response;
6196 return error;
6197};
6198 2913
6199},{}],57:[function(require,module,exports){ 2914 // adjust the exponent accordingly.
6200'use strict'; 2915 if ( i < LOG_BASE ) e -= LOG_BASE - i;
2916 }
6201 2917
6202var createError = require('./createError'); 2918 rand.e = e;
2919 rand.c = c;
2920 return rand;
2921 };
2922 })();
6203 2923
6204/**
6205 * Resolve or reject a Promise based on response status.
6206 *
6207 * @param {Function} resolve A function that resolves the promise.
6208 * @param {Function} reject A function that rejects the promise.
6209 * @param {object} response The response.
6210 */
6211module.exports = function settle(resolve, reject, response) {
6212 var validateStatus = response.config.validateStatus;
6213 // Note: status is not exposed by XDomainRequest
6214 if (!response.status || !validateStatus || validateStatus(response.status)) {
6215 resolve(response);
6216 } else {
6217 reject(createError(
6218 'Request failed with status code ' + response.status,
6219 response.config,
6220 null,
6221 response.request,
6222 response
6223 ));
6224 }
6225};
6226 2924
6227},{"./createError":54}],58:[function(require,module,exports){ 2925 // PRIVATE FUNCTIONS
6228'use strict';
6229 2926
6230var utils = require('./../utils');
6231 2927
6232/** 2928 // Convert a numeric string of baseIn to a numeric string of baseOut.
6233 * Transform the data for a request or a response 2929 function convertBase( str, baseOut, baseIn, sign ) {
6234 * 2930 var d, e, k, r, x, xc, y,
6235 * @param {Object|String} data The data to be transformed 2931 i = str.indexOf( '.' ),
6236 * @param {Array} headers The headers for the request or response 2932 dp = DECIMAL_PLACES,
6237 * @param {Array|Function} fns A single function or Array of functions 2933 rm = ROUNDING_MODE;
6238 * @returns {*} The resulting transformed data
6239 */
6240module.exports = function transformData(data, headers, fns) {
6241 /*eslint no-param-reassign:0*/
6242 utils.forEach(fns, function transform(fn) {
6243 data = fn(data, headers);
6244 });
6245 2934
6246 return data; 2935 if ( baseIn < 37 ) str = str.toLowerCase();
6247};
6248 2936
6249},{"./../utils":70}],59:[function(require,module,exports){ 2937 // Non-integer.
6250(function (process){ 2938 if ( i >= 0 ) {
6251'use strict'; 2939 k = POW_PRECISION;
6252 2940
6253var utils = require('./utils'); 2941 // Unlimited precision.
6254var normalizeHeaderName = require('./helpers/normalizeHeaderName'); 2942 POW_PRECISION = 0;
2943 str = str.replace( '.', '' );
2944 y = new BigNumber(baseIn);
2945 x = y.pow( str.length - i );
2946 POW_PRECISION = k;
6255 2947
6256var DEFAULT_CONTENT_TYPE = { 2948 // Convert str as if an integer, then restore the fraction part by dividing the
6257 'Content-Type': 'application/x-www-form-urlencoded' 2949 // result by its base raised to a power.
6258}; 2950 y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );
2951 y.e = y.c.length;
2952 }
6259 2953
6260function setContentTypeIfUnset(headers, value) { 2954 // Convert the number as integer.
6261 if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { 2955 xc = toBaseOut( str, baseIn, baseOut );
6262 headers['Content-Type'] = value; 2956 e = k = xc.length;
6263 }
6264}
6265 2957
6266function getDefaultAdapter() { 2958 // Remove trailing zeros.
6267 var adapter; 2959 for ( ; xc[--k] == 0; xc.pop() );
6268 if (typeof XMLHttpRequest !== 'undefined') { 2960 if ( !xc[0] ) return '0';
6269 // For browsers use XHR adapter
6270 adapter = require('./adapters/xhr');
6271 } else if (typeof process !== 'undefined') {
6272 // For node use HTTP adapter
6273 adapter = require('./adapters/http');
6274 }
6275 return adapter;
6276}
6277 2961
6278var defaults = { 2962 if ( i < 0 ) {
6279 adapter: getDefaultAdapter(), 2963 --e;
2964 } else {
2965 x.c = xc;
2966 x.e = e;
2967
2968 // sign is needed for correct rounding.
2969 x.s = sign;
2970 x = div( x, y, dp, rm, baseOut );
2971 xc = x.c;
2972 r = x.r;
2973 e = x.e;
2974 }
6280 2975
6281 transformRequest: [function transformRequest(data, headers) { 2976 d = e + dp + 1;
6282 normalizeHeaderName(headers, 'Content-Type');
6283 if (utils.isFormData(data) ||
6284 utils.isArrayBuffer(data) ||
6285 utils.isBuffer(data) ||
6286 utils.isStream(data) ||
6287 utils.isFile(data) ||
6288 utils.isBlob(data)
6289 ) {
6290 return data;
6291 }
6292 if (utils.isArrayBufferView(data)) {
6293 return data.buffer;
6294 }
6295 if (utils.isURLSearchParams(data)) {
6296 setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
6297 return data.toString();
6298 }
6299 if (utils.isObject(data)) {
6300 setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
6301 return JSON.stringify(data);
6302 }
6303 return data;
6304 }],
6305 2977
6306 transformResponse: [function transformResponse(data) { 2978 // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.
6307 /*eslint no-param-reassign:0*/ 2979 i = xc[d];
6308 if (typeof data === 'string') { 2980 k = baseOut / 2;
6309 try { 2981 r = r || d < 0 || xc[d + 1] != null;
6310 data = JSON.parse(data);
6311 } catch (e) { /* Ignore */ }
6312 }
6313 return data;
6314 }],
6315 2982
6316 /** 2983 r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
6317 * A timeout in milliseconds to abort a request. If set to 0 (default) a 2984 : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
6318 * timeout is not created. 2985 rm == ( x.s < 0 ? 8 : 7 ) );
6319 */
6320 timeout: 0,
6321 2986
6322 xsrfCookieName: 'XSRF-TOKEN', 2987 if ( d < 1 || !xc[0] ) {
6323 xsrfHeaderName: 'X-XSRF-TOKEN',
6324 2988
6325 maxContentLength: -1, 2989 // 1^-dp or 0.
2990 str = r ? toFixedPoint( '1', -dp ) : '0';
2991 } else {
2992 xc.length = d;
6326 2993
6327 validateStatus: function validateStatus(status) { 2994 if (r) {
6328 return status >= 200 && status < 300;
6329 }
6330};
6331 2995
6332defaults.headers = { 2996 // Rounding up may mean the previous digit has to be rounded up and so on.
6333 common: { 2997 for ( --baseOut; ++xc[--d] > baseOut; ) {
6334 'Accept': 'application/json, text/plain, */*' 2998 xc[d] = 0;
6335 }
6336};
6337 2999
6338utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { 3000 if ( !d ) {
6339 defaults.headers[method] = {}; 3001 ++e;
6340}); 3002 xc = [1].concat(xc);
3003 }
3004 }
3005 }
6341 3006
6342utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { 3007 // Determine trailing zeros.
6343 defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); 3008 for ( k = xc.length; !xc[--k]; );
6344});
6345 3009
6346module.exports = defaults; 3010 // E.g. [4, 11, 15] becomes 4bf.
3011 for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );
3012 str = toFixedPoint( str, e );
3013 }
6347 3014
6348}).call(this,require('_process')) 3015 // The caller will add the sign.
6349},{"./adapters/http":47,"./adapters/xhr":47,"./helpers/normalizeHeaderName":67,"./utils":70,"_process":190}],60:[function(require,module,exports){ 3016 return str;
6350'use strict'; 3017 }
6351 3018
6352module.exports = function bind(fn, thisArg) {
6353 return function wrap() {
6354 var args = new Array(arguments.length);
6355 for (var i = 0; i < args.length; i++) {
6356 args[i] = arguments[i];
6357 }
6358 return fn.apply(thisArg, args);
6359 };
6360};
6361 3019
6362},{}],61:[function(require,module,exports){ 3020 // Perform division in the specified base. Called by div and convertBase.
6363'use strict'; 3021 div = (function () {
3022
3023 // Assume non-zero x and k.
3024 function multiply( x, k, base ) {
3025 var m, temp, xlo, xhi,
3026 carry = 0,
3027 i = x.length,
3028 klo = k % SQRT_BASE,
3029 khi = k / SQRT_BASE | 0;
3030
3031 for ( x = x.slice(); i--; ) {
3032 xlo = x[i] % SQRT_BASE;
3033 xhi = x[i] / SQRT_BASE | 0;
3034 m = khi * xlo + xhi * klo;
3035 temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;
3036 carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;
3037 x[i] = temp % base;
3038 }
6364 3039
6365// btoa polyfill for IE<10 courtesy https://github.com/davidchambers/Base64.js 3040 if (carry) x = [carry].concat(x);
6366 3041
6367var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; 3042 return x;
3043 }
6368 3044
6369function E() { 3045 function compare( a, b, aL, bL ) {
6370 this.message = 'String contains an invalid character'; 3046 var i, cmp;
6371}
6372E.prototype = new Error;
6373E.prototype.code = 5;
6374E.prototype.name = 'InvalidCharacterError';
6375 3047
6376function btoa(input) { 3048 if ( aL != bL ) {
6377 var str = String(input); 3049 cmp = aL > bL ? 1 : -1;
6378 var output = ''; 3050 } else {
6379 for (
6380 // initialize result and counter
6381 var block, charCode, idx = 0, map = chars;
6382 // if the next str index does not exist:
6383 // change the mapping table to "="
6384 // check if d has no fractional digits
6385 str.charAt(idx | 0) || (map = '=', idx % 1);
6386 // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
6387 output += map.charAt(63 & block >> 8 - idx % 1 * 8)
6388 ) {
6389 charCode = str.charCodeAt(idx += 3 / 4);
6390 if (charCode > 0xFF) {
6391 throw new E();
6392 }
6393 block = block << 8 | charCode;
6394 }
6395 return output;
6396}
6397 3051
6398module.exports = btoa; 3052 for ( i = cmp = 0; i < aL; i++ ) {
6399 3053
6400},{}],62:[function(require,module,exports){ 3054 if ( a[i] != b[i] ) {
6401'use strict'; 3055 cmp = a[i] > b[i] ? 1 : -1;
3056 break;
3057 }
3058 }
3059 }
3060 return cmp;
3061 }
6402 3062
6403var utils = require('./../utils'); 3063 function subtract( a, b, aL, base ) {
3064 var i = 0;
6404 3065
6405function encode(val) { 3066 // Subtract b from a.
6406 return encodeURIComponent(val). 3067 for ( ; aL--; ) {
6407 replace(/%40/gi, '@'). 3068 a[aL] -= i;
6408 replace(/%3A/gi, ':'). 3069 i = a[aL] < b[aL] ? 1 : 0;
6409 replace(/%24/g, '$'). 3070 a[aL] = i * base + a[aL] - b[aL];
6410 replace(/%2C/gi, ','). 3071 }
6411 replace(/%20/g, '+').
6412 replace(/%5B/gi, '[').
6413 replace(/%5D/gi, ']');
6414}
6415 3072
6416/** 3073 // Remove leading zeros.
6417 * Build a URL by appending params to the end 3074 for ( ; !a[0] && a.length > 1; a.splice(0, 1) );
6418 * 3075 }
6419 * @param {string} url The base of the url (e.g., http://www.google.com)
6420 * @param {object} [params] The params to be appended
6421 * @returns {string} The formatted url
6422 */
6423module.exports = function buildURL(url, params, paramsSerializer) {
6424 /*eslint no-param-reassign:0*/
6425 if (!params) {
6426 return url;
6427 }
6428 3076
6429 var serializedParams; 3077 // x: dividend, y: divisor.
6430 if (paramsSerializer) { 3078 return function ( x, y, dp, rm, base ) {
6431 serializedParams = paramsSerializer(params); 3079 var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
6432 } else if (utils.isURLSearchParams(params)) { 3080 yL, yz,
6433 serializedParams = params.toString(); 3081 s = x.s == y.s ? 1 : -1,
6434 } else { 3082 xc = x.c,
6435 var parts = []; 3083 yc = y.c;
6436 3084
6437 utils.forEach(params, function serialize(val, key) { 3085 // Either NaN, Infinity or 0?
6438 if (val === null || typeof val === 'undefined') { 3086 if ( !xc || !xc[0] || !yc || !yc[0] ) {
6439 return;
6440 }
6441 3087
6442 if (utils.isArray(val)) { 3088 return new BigNumber(
6443 key = key + '[]';
6444 } else {
6445 val = [val];
6446 }
6447 3089
6448 utils.forEach(val, function parseValue(v) { 3090 // Return NaN if either NaN, or both Infinity or 0.
6449 if (utils.isDate(v)) { 3091 !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :
6450 v = v.toISOString();
6451 } else if (utils.isObject(v)) {
6452 v = JSON.stringify(v);
6453 }
6454 parts.push(encode(key) + '=' + encode(v));
6455 });
6456 });
6457 3092
6458 serializedParams = parts.join('&'); 3093 // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
6459 } 3094 xc && xc[0] == 0 || !yc ? s * 0 : s / 0
3095 );
3096 }
6460 3097
6461 if (serializedParams) { 3098 q = new BigNumber(s);
6462 url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; 3099 qc = q.c = [];
6463 } 3100 e = x.e - y.e;
3101 s = dp + e + 1;
6464 3102
6465 return url; 3103 if ( !base ) {
6466}; 3104 base = BASE;
3105 e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE );
3106 s = s / LOG_BASE | 0;
3107 }
6467 3108
6468},{"./../utils":70}],63:[function(require,module,exports){ 3109 // Result exponent may be one less then the current value of e.
6469'use strict'; 3110 // The coefficients of the BigNumbers from convertBase may have trailing zeros.
3111 for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );
3112 if ( yc[i] > ( xc[i] || 0 ) ) e--;
3113
3114 if ( s < 0 ) {
3115 qc.push(1);
3116 more = true;
3117 } else {
3118 xL = xc.length;
3119 yL = yc.length;
3120 i = 0;
3121 s += 2;
3122
3123 // Normalise xc and yc so highest order digit of yc is >= base / 2.
3124
3125 n = mathfloor( base / ( yc[0] + 1 ) );
3126
3127 // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1.
3128 // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) {
3129 if ( n > 1 ) {
3130 yc = multiply( yc, n, base );
3131 xc = multiply( xc, n, base );
3132 yL = yc.length;
3133 xL = xc.length;
3134 }
3135
3136 xi = yL;
3137 rem = xc.slice( 0, yL );
3138 remL = rem.length;
3139
3140 // Add zeros to make remainder as long as divisor.
3141 for ( ; remL < yL; rem[remL++] = 0 );
3142 yz = yc.slice();
3143 yz = [0].concat(yz);
3144 yc0 = yc[0];
3145 if ( yc[1] >= base / 2 ) yc0++;
3146 // Not necessary, but to prevent trial digit n > base, when using base 3.
3147 // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15;
3148
3149 do {
3150 n = 0;
3151
3152 // Compare divisor and remainder.
3153 cmp = compare( yc, rem, yL, remL );
3154
3155 // If divisor < remainder.
3156 if ( cmp < 0 ) {
3157
3158 // Calculate trial digit, n.
3159
3160 rem0 = rem[0];
3161 if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 );
3162
3163 // n is how many times the divisor goes into the current remainder.
3164 n = mathfloor( rem0 / yc0 );
3165
3166 // Algorithm:
3167 // 1. product = divisor * trial digit (n)
3168 // 2. if product > remainder: product -= divisor, n--
3169 // 3. remainder -= product
3170 // 4. if product was < remainder at 2:
3171 // 5. compare new remainder and divisor
3172 // 6. If remainder > divisor: remainder -= divisor, n++
3173
3174 if ( n > 1 ) {
3175
3176 // n may be > base only when base is 3.
3177 if (n >= base) n = base - 1;
3178
3179 // product = divisor * trial digit.
3180 prod = multiply( yc, n, base );
3181 prodL = prod.length;
3182 remL = rem.length;
3183
3184 // Compare product and remainder.
3185 // If product > remainder.
3186 // Trial digit n too high.
3187 // n is 1 too high about 5% of the time, and is not known to have
3188 // ever been more than 1 too high.
3189 while ( compare( prod, rem, prodL, remL ) == 1 ) {
3190 n--;
3191
3192 // Subtract divisor from product.
3193 subtract( prod, yL < prodL ? yz : yc, prodL, base );
3194 prodL = prod.length;
3195 cmp = 1;
3196 }
3197 } else {
3198
3199 // n is 0 or 1, cmp is -1.
3200 // If n is 0, there is no need to compare yc and rem again below,
3201 // so change cmp to 1 to avoid it.
3202 // If n is 1, leave cmp as -1, so yc and rem are compared again.
3203 if ( n == 0 ) {
3204
3205 // divisor < remainder, so n must be at least 1.
3206 cmp = n = 1;
3207 }
3208
3209 // product = divisor
3210 prod = yc.slice();
3211 prodL = prod.length;
3212 }
3213
3214 if ( prodL < remL ) prod = [0].concat(prod);
3215
3216 // Subtract product from remainder.
3217 subtract( rem, prod, remL, base );
3218 remL = rem.length;
3219
3220 // If product was < remainder.
3221 if ( cmp == -1 ) {
3222
3223 // Compare divisor and new remainder.
3224 // If divisor < new remainder, subtract divisor from remainder.
3225 // Trial digit n too low.
3226 // n is 1 too low about 5% of the time, and very rarely 2 too low.
3227 while ( compare( yc, rem, yL, remL ) < 1 ) {
3228 n++;
3229
3230 // Subtract divisor from remainder.
3231 subtract( rem, yL < remL ? yz : yc, remL, base );
3232 remL = rem.length;
3233 }
3234 }
3235 } else if ( cmp === 0 ) {
3236 n++;
3237 rem = [0];
3238 } // else cmp === 1 and n will be 0
3239
3240 // Add the next digit, n, to the result array.
3241 qc[i++] = n;
3242
3243 // Update the remainder.
3244 if ( rem[0] ) {
3245 rem[remL++] = xc[xi] || 0;
3246 } else {
3247 rem = [ xc[xi] ];
3248 remL = 1;
3249 }
3250 } while ( ( xi++ < xL || rem[0] != null ) && s-- );
3251
3252 more = rem[0] != null;
3253
3254 // Leading zero?
3255 if ( !qc[0] ) qc.splice(0, 1);
3256 }
6470 3257
6471/** 3258 if ( base == BASE ) {
6472 * Creates a new URL by combining the specified URLs
6473 *
6474 * @param {string} baseURL The base URL
6475 * @param {string} relativeURL The relative URL
6476 * @returns {string} The combined URL
6477 */
6478module.exports = function combineURLs(baseURL, relativeURL) {
6479 return relativeURL
6480 ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
6481 : baseURL;
6482};
6483 3259
6484},{}],64:[function(require,module,exports){ 3260 // To calculate q.e, first get the number of digits of qc[0].
6485'use strict'; 3261 for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );
3262 round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more );
6486 3263
6487var utils = require('./../utils'); 3264 // Caller is convertBase.
3265 } else {
3266 q.e = e;
3267 q.r = +more;
3268 }
6488 3269
6489module.exports = ( 3270 return q;
6490 utils.isStandardBrowserEnv() ? 3271 };
3272 })();
3273
3274
3275 /*
3276 * Return a string representing the value of BigNumber n in fixed-point or exponential
3277 * notation rounded to the specified decimal places or significant digits.
3278 *
3279 * n is a BigNumber.
3280 * i is the index of the last digit required (i.e. the digit that may be rounded up).
3281 * rm is the rounding mode.
3282 * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24.
3283 */
3284 function format( n, i, rm, caller ) {
3285 var c0, e, ne, len, str;
3286
3287 rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode )
3288 ? rm | 0 : ROUNDING_MODE;
3289
3290 if ( !n.c ) return n.toString();
3291 c0 = n.c[0];
3292 ne = n.e;
3293
3294 if ( i == null ) {
3295 str = coeffToString( n.c );
3296 str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG
3297 ? toExponential( str, ne )
3298 : toFixedPoint( str, ne );
3299 } else {
3300 n = round( new BigNumber(n), i, rm );
3301
3302 // n.e may have changed if the value was rounded up.
3303 e = n.e;
3304
3305 str = coeffToString( n.c );
3306 len = str.length;
3307
3308 // toPrecision returns exponential notation if the number of significant digits
3309 // specified is less than the number of digits necessary to represent the integer
3310 // part of the value in fixed-point notation.
3311
3312 // Exponential notation.
3313 if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) {
3314
3315 // Append zeros?
3316 for ( ; len < i; str += '0', len++ );
3317 str = toExponential( str, e );
3318
3319 // Fixed-point notation.
3320 } else {
3321 i -= ne;
3322 str = toFixedPoint( str, e );
3323
3324 // Append zeros?
3325 if ( e + 1 > len ) {
3326 if ( --i > 0 ) for ( str += '.'; i--; str += '0' );
3327 } else {
3328 i += e - len;
3329 if ( i > 0 ) {
3330 if ( e + 1 == len ) str += '.';
3331 for ( ; i--; str += '0' );
3332 }
3333 }
3334 }
3335 }
6491 3336
6492 // Standard browser envs support document.cookie 3337 return n.s < 0 && c0 ? '-' + str : str;
6493 (function standardBrowserEnv() { 3338 }
6494 return { 3339
6495 write: function write(name, value, expires, path, domain, secure) { 3340
6496 var cookie = []; 3341 // Handle BigNumber.max and BigNumber.min.
6497 cookie.push(name + '=' + encodeURIComponent(value)); 3342 function maxOrMin( args, method ) {
3343 var m, n,
3344 i = 0;
6498 3345
6499 if (utils.isNumber(expires)) { 3346 if ( isArray( args[0] ) ) args = args[0];
6500 cookie.push('expires=' + new Date(expires).toGMTString()); 3347 m = new BigNumber( args[0] );
3348
3349 for ( ; ++i < args.length; ) {
3350 n = new BigNumber( args[i] );
3351
3352 // If any number is NaN, return NaN.
3353 if ( !n.s ) {
3354 m = n;
3355 break;
3356 } else if ( method.call( m, n ) ) {
3357 m = n;
3358 }
3359 }
3360
3361 return m;
6501 } 3362 }
6502 3363
6503 if (utils.isString(path)) { 3364
6504 cookie.push('path=' + path); 3365 /*
3366 * Return true if n is an integer in range, otherwise throw.
3367 * Use for argument validation when ERRORS is true.
3368 */
3369 function intValidatorWithErrors( n, min, max, caller, name ) {
3370 if ( n < min || n > max || n != truncate(n) ) {
3371 raise( caller, ( name || 'decimal places' ) +
3372 ( n < min || n > max ? ' out of range' : ' not an integer' ), n );
3373 }
3374
3375 return true;
6505 } 3376 }
6506 3377
6507 if (utils.isString(domain)) { 3378
6508 cookie.push('domain=' + domain); 3379 /*
3380 * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
3381 * Called by minus, plus and times.
3382 */
3383 function normalise( n, c, e ) {
3384 var i = 1,
3385 j = c.length;
3386
3387 // Remove trailing zeros.
3388 for ( ; !c[--j]; c.pop() );
3389
3390 // Calculate the base 10 exponent. First get the number of digits of c[0].
3391 for ( j = c[0]; j >= 10; j /= 10, i++ );
3392
3393 // Overflow?
3394 if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) {
3395
3396 // Infinity.
3397 n.c = n.e = null;
3398
3399 // Underflow?
3400 } else if ( e < MIN_EXP ) {
3401
3402 // Zero.
3403 n.c = [ n.e = 0 ];
3404 } else {
3405 n.e = e;
3406 n.c = c;
3407 }
3408
3409 return n;
6509 } 3410 }
6510 3411
6511 if (secure === true) { 3412
6512 cookie.push('secure'); 3413 // Handle values that fail the validity test in BigNumber.
3414 parseNumeric = (function () {
3415 var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,
3416 dotAfter = /^([^.]+)\.$/,
3417 dotBefore = /^\.([^.]+)$/,
3418 isInfinityOrNaN = /^-?(Infinity|NaN)$/,
3419 whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
3420
3421 return function ( x, str, num, b ) {
3422 var base,
3423 s = num ? str : str.replace( whitespaceOrPlus, '' );
3424
3425 // No exception on ±Infinity or NaN.
3426 if ( isInfinityOrNaN.test(s) ) {
3427 x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
3428 } else {
3429 if ( !num ) {
3430
3431 // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
3432 s = s.replace( basePrefix, function ( m, p1, p2 ) {
3433 base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
3434 return !b || b == base ? p1 : m;
3435 });
3436
3437 if (b) {
3438 base = b;
3439
3440 // E.g. '1.' to '1', '.1' to '0.1'
3441 s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' );
3442 }
3443
3444 if ( str != s ) return new BigNumber( s, base );
3445 }
3446
3447 // 'new BigNumber() not a number: {n}'
3448 // 'new BigNumber() not a base {b} number: {n}'
3449 if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str );
3450 x.s = null;
3451 }
3452
3453 x.c = x.e = null;
3454 id = 0;
3455 }
3456 })();
3457
3458
3459 // Throw a BigNumber Error.
3460 function raise( caller, msg, val ) {
3461 var error = new Error( [
3462 'new BigNumber', // 0
3463 'cmp', // 1
3464 'config', // 2
3465 'div', // 3
3466 'divToInt', // 4
3467 'eq', // 5
3468 'gt', // 6
3469 'gte', // 7
3470 'lt', // 8
3471 'lte', // 9
3472 'minus', // 10
3473 'mod', // 11
3474 'plus', // 12
3475 'precision', // 13
3476 'random', // 14
3477 'round', // 15
3478 'shift', // 16
3479 'times', // 17
3480 'toDigits', // 18
3481 'toExponential', // 19
3482 'toFixed', // 20
3483 'toFormat', // 21
3484 'toFraction', // 22
3485 'pow', // 23
3486 'toPrecision', // 24
3487 'toString', // 25
3488 'BigNumber' // 26
3489 ][caller] + '() ' + msg + ': ' + val );
3490
3491 error.name = 'BigNumber Error';
3492 id = 0;
3493 throw error;
6513 } 3494 }
6514 3495
6515 document.cookie = cookie.join('; ');
6516 },
6517 3496
6518 read: function read(name) { 3497 /*
6519 var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); 3498 * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
6520 return (match ? decodeURIComponent(match[3]) : null); 3499 * If r is truthy, it is known that there are more digits after the rounding digit.
6521 }, 3500 */
3501 function round( x, sd, rm, r ) {
3502 var d, i, j, k, n, ni, rd,
3503 xc = x.c,
3504 pows10 = POWS_TEN;
3505
3506 // if x is not Infinity or NaN...
3507 if (xc) {
3508
3509 // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
3510 // n is a base 1e14 number, the value of the element of array x.c containing rd.
3511 // ni is the index of n within x.c.
3512 // d is the number of digits of n.
3513 // i is the index of rd within n including leading zeros.
3514 // j is the actual index of rd within n (if < 0, rd is a leading zero).
3515 out: {
3516
3517 // Get the number of digits of the first element of xc.
3518 for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );
3519 i = sd - d;
3520
3521 // If the rounding digit is in the first element of xc...
3522 if ( i < 0 ) {
3523 i += LOG_BASE;
3524 j = sd;
3525 n = xc[ ni = 0 ];
3526
3527 // Get the rounding digit at index j of n.
3528 rd = n / pows10[ d - j - 1 ] % 10 | 0;
3529 } else {
3530 ni = mathceil( ( i + 1 ) / LOG_BASE );
3531
3532 if ( ni >= xc.length ) {
3533
3534 if (r) {
3535
3536 // Needed by sqrt.
3537 for ( ; xc.length <= ni; xc.push(0) );
3538 n = rd = 0;
3539 d = 1;
3540 i %= LOG_BASE;
3541 j = i - LOG_BASE + 1;
3542 } else {
3543 break out;
3544 }
3545 } else {
3546 n = k = xc[ni];
3547
3548 // Get the number of digits of n.
3549 for ( d = 1; k >= 10; k /= 10, d++ );
3550
3551 // Get the index of rd within n.
3552 i %= LOG_BASE;
3553
3554 // Get the index of rd within n, adjusted for leading zeros.
3555 // The number of leading zeros of n is given by LOG_BASE - d.
3556 j = i - LOG_BASE + d;
3557
3558 // Get the rounding digit at index j of n.
3559 rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;
3560 }
3561 }
3562
3563 r = r || sd < 0 ||
3564
3565 // Are there any non-zero digits after the rounding digit?
3566 // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right
3567 // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
3568 xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );
3569
3570 r = rm < 4
3571 ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
3572 : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&
3573
3574 // Check whether the digit to the left of the rounding digit is odd.
3575 ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||
3576 rm == ( x.s < 0 ? 8 : 7 ) );
3577
3578 if ( sd < 1 || !xc[0] ) {
3579 xc.length = 0;
3580
3581 if (r) {
3582
3583 // Convert sd to decimal places.
3584 sd -= x.e + 1;
3585
3586 // 1, 0.1, 0.01, 0.001, 0.0001 etc.
3587 xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ];
3588 x.e = -sd || 0;
3589 } else {
3590
3591 // Zero.
3592 xc[0] = x.e = 0;
3593 }
3594
3595 return x;
3596 }
3597
3598 // Remove excess digits.
3599 if ( i == 0 ) {
3600 xc.length = ni;
3601 k = 1;
3602 ni--;
3603 } else {
3604 xc.length = ni + 1;
3605 k = pows10[ LOG_BASE - i ];
3606
3607 // E.g. 56700 becomes 56000 if 7 is the rounding digit.
3608 // j > 0 means i > number of leading zeros of n.
3609 xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;
3610 }
3611
3612 // Round up?
3613 if (r) {
3614
3615 for ( ; ; ) {
3616
3617 // If the digit to be rounded up is in the first element of xc...
3618 if ( ni == 0 ) {
3619
3620 // i will be the length of xc[0] before k is added.
3621 for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );
3622 j = xc[0] += k;
3623 for ( k = 1; j >= 10; j /= 10, k++ );
3624
3625 // if i != k the length has increased.
3626 if ( i != k ) {
3627 x.e++;
3628 if ( xc[0] == BASE ) xc[0] = 1;
3629 }
3630
3631 break;
3632 } else {
3633 xc[ni] += k;
3634 if ( xc[ni] != BASE ) break;
3635 xc[ni--] = 0;
3636 k = 1;
3637 }
3638 }
3639 }
3640
3641 // Remove trailing zeros.
3642 for ( i = xc.length; xc[--i] === 0; xc.pop() );
3643 }
6522 3644
6523 remove: function remove(name) { 3645 // Overflow? Infinity.
6524 this.write(name, '', Date.now() - 86400000); 3646 if ( x.e > MAX_EXP ) {
6525 } 3647 x.c = x.e = null;
6526 };
6527 })() :
6528 3648
6529 // Non standard browser env (web workers, react-native) lack needed support. 3649 // Underflow? Zero.
6530 (function nonStandardBrowserEnv() { 3650 } else if ( x.e < MIN_EXP ) {
6531 return { 3651 x.c = [ x.e = 0 ];
6532 write: function write() {}, 3652 }
6533 read: function read() { return null; }, 3653 }
6534 remove: function remove() {}
6535 };
6536 })()
6537);
6538 3654
6539},{"./../utils":70}],65:[function(require,module,exports){ 3655 return x;
6540'use strict'; 3656 }
6541 3657
6542/**
6543 * Determines whether the specified URL is absolute
6544 *
6545 * @param {string} url The URL to test
6546 * @returns {boolean} True if the specified URL is absolute, otherwise false
6547 */
6548module.exports = function isAbsoluteURL(url) {
6549 // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
6550 // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
6551 // by any combination of letters, digits, plus, period, or hyphen.
6552 return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
6553};
6554 3658
6555},{}],66:[function(require,module,exports){ 3659 // PROTOTYPE/INSTANCE METHODS
6556'use strict';
6557 3660
6558var utils = require('./../utils');
6559 3661
6560module.exports = ( 3662 /*
6561 utils.isStandardBrowserEnv() ? 3663 * Return a new BigNumber whose value is the absolute value of this BigNumber.
3664 */
3665 P.absoluteValue = P.abs = function () {
3666 var x = new BigNumber(this);
3667 if ( x.s < 0 ) x.s = 1;
3668 return x;
3669 };
6562 3670
6563 // Standard browser envs have full support of the APIs needed to test
6564 // whether the request URL is of the same origin as current location.
6565 (function standardBrowserEnv() {
6566 var msie = /(msie|trident)/i.test(navigator.userAgent);
6567 var urlParsingNode = document.createElement('a');
6568 var originURL;
6569 3671
6570 /** 3672 /*
6571 * Parse a URL to discover it's components 3673 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
6572 * 3674 * number in the direction of Infinity.
6573 * @param {String} url The URL to be parsed 3675 */
6574 * @returns {Object} 3676 P.ceil = function () {
6575 */ 3677 return round( new BigNumber(this), this.e + 1, 2 );
6576 function resolveURL(url) { 3678 };
6577 var href = url;
6578 3679
6579 if (msie) {
6580 // IE needs attribute set twice to normalize properties
6581 urlParsingNode.setAttribute('href', href);
6582 href = urlParsingNode.href;
6583 }
6584 3680
6585 urlParsingNode.setAttribute('href', href); 3681 /*
3682 * Return
3683 * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
3684 * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
3685 * 0 if they have the same value,
3686 * or null if the value of either is NaN.
3687 */
3688 P.comparedTo = P.cmp = function ( y, b ) {
3689 id = 1;
3690 return compare( this, new BigNumber( y, b ) );
3691 };
6586 3692
6587 // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
6588 return {
6589 href: urlParsingNode.href,
6590 protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
6591 host: urlParsingNode.host,
6592 search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
6593 hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
6594 hostname: urlParsingNode.hostname,
6595 port: urlParsingNode.port,
6596 pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
6597 urlParsingNode.pathname :
6598 '/' + urlParsingNode.pathname
6599 };
6600 }
6601 3693
6602 originURL = resolveURL(window.location.href); 3694 /*
3695 * Return the number of decimal places of the value of this BigNumber, or null if the value
3696 * of this BigNumber is ±Infinity or NaN.
3697 */
3698 P.decimalPlaces = P.dp = function () {
3699 var n, v,
3700 c = this.c;
6603 3701
6604 /** 3702 if ( !c ) return null;
6605 * Determine if a URL shares the same origin as the current location 3703 n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE;
6606 *
6607 * @param {String} requestURL The URL to test
6608 * @returns {boolean} True if URL shares the same origin, otherwise false
6609 */
6610 return function isURLSameOrigin(requestURL) {
6611 var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
6612 return (parsed.protocol === originURL.protocol &&
6613 parsed.host === originURL.host);
6614 };
6615 })() :
6616 3704
6617 // Non standard browser envs (web workers, react-native) lack needed support. 3705 // Subtract the number of trailing zeros of the last number.
6618 (function nonStandardBrowserEnv() { 3706 if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- );
6619 return function isURLSameOrigin() { 3707 if ( n < 0 ) n = 0;
6620 return true;
6621 };
6622 })()
6623);
6624 3708
6625},{"./../utils":70}],67:[function(require,module,exports){ 3709 return n;
6626'use strict'; 3710 };
6627 3711
6628var utils = require('../utils');
6629 3712
6630module.exports = function normalizeHeaderName(headers, normalizedName) { 3713 /*
6631 utils.forEach(headers, function processHeader(value, name) { 3714 * n / 0 = I
6632 if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { 3715 * n / N = N
6633 headers[normalizedName] = value; 3716 * n / I = 0
6634 delete headers[name]; 3717 * 0 / n = 0
6635 } 3718 * 0 / 0 = N
6636 }); 3719 * 0 / N = N
6637}; 3720 * 0 / I = 0
3721 * N / n = N
3722 * N / 0 = N
3723 * N / N = N
3724 * N / I = N
3725 * I / n = I
3726 * I / 0 = I
3727 * I / N = N
3728 * I / I = N
3729 *
3730 * Return a new BigNumber whose value is the value of this BigNumber divided by the value of
3731 * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
3732 */
3733 P.dividedBy = P.div = function ( y, b ) {
3734 id = 3;
3735 return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE );
3736 };
6638 3737
6639},{"../utils":70}],68:[function(require,module,exports){
6640'use strict';
6641 3738
6642var utils = require('./../utils'); 3739 /*
3740 * Return a new BigNumber whose value is the integer part of dividing the value of this
3741 * BigNumber by the value of BigNumber(y, b).
3742 */
3743 P.dividedToIntegerBy = P.divToInt = function ( y, b ) {
3744 id = 4;
3745 return div( this, new BigNumber( y, b ), 0, 1 );
3746 };
6643 3747
6644// Headers whose duplicates are ignored by node
6645// c.f. https://nodejs.org/api/http.html#http_message_headers
6646var ignoreDuplicateOf = [
6647 'age', 'authorization', 'content-length', 'content-type', 'etag',
6648 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
6649 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
6650 'referer', 'retry-after', 'user-agent'
6651];
6652 3748
6653/** 3749 /*
6654 * Parse headers into an object 3750 * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
6655 * 3751 * otherwise returns false.
6656 * ``` 3752 */
6657 * Date: Wed, 27 Aug 2014 08:58:49 GMT 3753 P.equals = P.eq = function ( y, b ) {
6658 * Content-Type: application/json 3754 id = 5;
6659 * Connection: keep-alive 3755 return compare( this, new BigNumber( y, b ) ) === 0;
6660 * Transfer-Encoding: chunked 3756 };
6661 * ```
6662 *
6663 * @param {String} headers Headers needing to be parsed
6664 * @returns {Object} Headers parsed into an object
6665 */
6666module.exports = function parseHeaders(headers) {
6667 var parsed = {};
6668 var key;
6669 var val;
6670 var i;
6671 3757
6672 if (!headers) { return parsed; }
6673 3758
6674 utils.forEach(headers.split('\n'), function parser(line) { 3759 /*
6675 i = line.indexOf(':'); 3760 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
6676 key = utils.trim(line.substr(0, i)).toLowerCase(); 3761 * number in the direction of -Infinity.
6677 val = utils.trim(line.substr(i + 1)); 3762 */
3763 P.floor = function () {
3764 return round( new BigNumber(this), this.e + 1, 3 );
3765 };
6678 3766
6679 if (key) {
6680 if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
6681 return;
6682 }
6683 if (key === 'set-cookie') {
6684 parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
6685 } else {
6686 parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
6687 }
6688 }
6689 });
6690 3767
6691 return parsed; 3768 /*
6692}; 3769 * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
3770 * otherwise returns false.
3771 */
3772 P.greaterThan = P.gt = function ( y, b ) {
3773 id = 6;
3774 return compare( this, new BigNumber( y, b ) ) > 0;
3775 };
6693 3776
6694},{"./../utils":70}],69:[function(require,module,exports){
6695'use strict';
6696 3777
6697/** 3778 /*
6698 * Syntactic sugar for invoking a function and expanding an array for arguments. 3779 * Return true if the value of this BigNumber is greater than or equal to the value of
6699 * 3780 * BigNumber(y, b), otherwise returns false.
6700 * Common use case would be to use `Function.prototype.apply`. 3781 */
6701 * 3782 P.greaterThanOrEqualTo = P.gte = function ( y, b ) {
6702 * ```js 3783 id = 7;
6703 * function f(x, y, z) {} 3784 return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0;
6704 * var args = [1, 2, 3];
6705 * f.apply(null, args);
6706 * ```
6707 *
6708 * With `spread` this example can be re-written.
6709 *
6710 * ```js
6711 * spread(function(x, y, z) {})([1, 2, 3]);
6712 * ```
6713 *
6714 * @param {Function} callback
6715 * @returns {Function}
6716 */
6717module.exports = function spread(callback) {
6718 return function wrap(arr) {
6719 return callback.apply(null, arr);
6720 };
6721};
6722 3785
6723},{}],70:[function(require,module,exports){ 3786 };
6724'use strict';
6725 3787
6726var bind = require('./helpers/bind');
6727var isBuffer = require('is-buffer');
6728 3788
6729/*global toString:true*/ 3789 /*
3790 * Return true if the value of this BigNumber is a finite number, otherwise returns false.
3791 */
3792 P.isFinite = function () {
3793 return !!this.c;
3794 };
6730 3795
6731// utils is a library of generic helper functions non-specific to axios
6732 3796
6733var toString = Object.prototype.toString; 3797 /*
3798 * Return true if the value of this BigNumber is an integer, otherwise return false.
3799 */
3800 P.isInteger = P.isInt = function () {
3801 return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2;
3802 };
6734 3803
6735/**
6736 * Determine if a value is an Array
6737 *
6738 * @param {Object} val The value to test
6739 * @returns {boolean} True if value is an Array, otherwise false
6740 */
6741function isArray(val) {
6742 return toString.call(val) === '[object Array]';
6743}
6744 3804
6745/** 3805 /*
6746 * Determine if a value is an ArrayBuffer 3806 * Return true if the value of this BigNumber is NaN, otherwise returns false.
6747 * 3807 */
6748 * @param {Object} val The value to test 3808 P.isNaN = function () {
6749 * @returns {boolean} True if value is an ArrayBuffer, otherwise false 3809 return !this.s;
6750 */ 3810 };
6751function isArrayBuffer(val) {
6752 return toString.call(val) === '[object ArrayBuffer]';
6753}
6754 3811
6755/**
6756 * Determine if a value is a FormData
6757 *
6758 * @param {Object} val The value to test
6759 * @returns {boolean} True if value is an FormData, otherwise false
6760 */
6761function isFormData(val) {
6762 return (typeof FormData !== 'undefined') && (val instanceof FormData);
6763}
6764 3812
6765/** 3813 /*
6766 * Determine if a value is a view on an ArrayBuffer 3814 * Return true if the value of this BigNumber is negative, otherwise returns false.
6767 * 3815 */
6768 * @param {Object} val The value to test 3816 P.isNegative = P.isNeg = function () {
6769 * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false 3817 return this.s < 0;
6770 */ 3818 };
6771function isArrayBufferView(val) {
6772 var result;
6773 if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
6774 result = ArrayBuffer.isView(val);
6775 } else {
6776 result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
6777 }
6778 return result;
6779}
6780 3819
6781/**
6782 * Determine if a value is a String
6783 *
6784 * @param {Object} val The value to test
6785 * @returns {boolean} True if value is a String, otherwise false
6786 */
6787function isString(val) {
6788 return typeof val === 'string';
6789}
6790 3820
6791/** 3821 /*
6792 * Determine if a value is a Number 3822 * Return true if the value of this BigNumber is 0 or -0, otherwise returns false.
6793 * 3823 */
6794 * @param {Object} val The value to test 3824 P.isZero = function () {
6795 * @returns {boolean} True if value is a Number, otherwise false 3825 return !!this.c && this.c[0] == 0;
6796 */ 3826 };
6797function isNumber(val) {
6798 return typeof val === 'number';
6799}
6800 3827
6801/**
6802 * Determine if a value is undefined
6803 *
6804 * @param {Object} val The value to test
6805 * @returns {boolean} True if the value is undefined, otherwise false
6806 */
6807function isUndefined(val) {
6808 return typeof val === 'undefined';
6809}
6810 3828
6811/** 3829 /*
6812 * Determine if a value is an Object 3830 * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
6813 * 3831 * otherwise returns false.
6814 * @param {Object} val The value to test 3832 */
6815 * @returns {boolean} True if value is an Object, otherwise false 3833 P.lessThan = P.lt = function ( y, b ) {
6816 */ 3834 id = 8;
6817function isObject(val) { 3835 return compare( this, new BigNumber( y, b ) ) < 0;
6818 return val !== null && typeof val === 'object'; 3836 };
6819}
6820 3837
6821/**
6822 * Determine if a value is a Date
6823 *
6824 * @param {Object} val The value to test
6825 * @returns {boolean} True if value is a Date, otherwise false
6826 */
6827function isDate(val) {
6828 return toString.call(val) === '[object Date]';
6829}
6830 3838
6831/** 3839 /*
6832 * Determine if a value is a File 3840 * Return true if the value of this BigNumber is less than or equal to the value of
6833 * 3841 * BigNumber(y, b), otherwise returns false.
6834 * @param {Object} val The value to test 3842 */
6835 * @returns {boolean} True if value is a File, otherwise false 3843 P.lessThanOrEqualTo = P.lte = function ( y, b ) {
6836 */ 3844 id = 9;
6837function isFile(val) { 3845 return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0;
6838 return toString.call(val) === '[object File]'; 3846 };
6839}
6840 3847
6841/**
6842 * Determine if a value is a Blob
6843 *
6844 * @param {Object} val The value to test
6845 * @returns {boolean} True if value is a Blob, otherwise false
6846 */
6847function isBlob(val) {
6848 return toString.call(val) === '[object Blob]';
6849}
6850 3848
6851/** 3849 /*
6852 * Determine if a value is a Function 3850 * n - 0 = n
6853 * 3851 * n - N = N
6854 * @param {Object} val The value to test 3852 * n - I = -I
6855 * @returns {boolean} True if value is a Function, otherwise false 3853 * 0 - n = -n
6856 */ 3854 * 0 - 0 = 0
6857function isFunction(val) { 3855 * 0 - N = N
6858 return toString.call(val) === '[object Function]'; 3856 * 0 - I = -I
6859} 3857 * N - n = N
3858 * N - 0 = N
3859 * N - N = N
3860 * N - I = N
3861 * I - n = I
3862 * I - 0 = I
3863 * I - N = N
3864 * I - I = N
3865 *
3866 * Return a new BigNumber whose value is the value of this BigNumber minus the value of
3867 * BigNumber(y, b).
3868 */
3869 P.minus = P.sub = function ( y, b ) {
3870 var i, j, t, xLTy,
3871 x = this,
3872 a = x.s;
3873
3874 id = 10;
3875 y = new BigNumber( y, b );
3876 b = y.s;
3877
3878 // Either NaN?
3879 if ( !a || !b ) return new BigNumber(NaN);
3880
3881 // Signs differ?
3882 if ( a != b ) {
3883 y.s = -b;
3884 return x.plus(y);
3885 }
6860 3886
6861/** 3887 var xe = x.e / LOG_BASE,
6862 * Determine if a value is a Stream 3888 ye = y.e / LOG_BASE,
6863 * 3889 xc = x.c,
6864 * @param {Object} val The value to test 3890 yc = y.c;
6865 * @returns {boolean} True if value is a Stream, otherwise false
6866 */
6867function isStream(val) {
6868 return isObject(val) && isFunction(val.pipe);
6869}
6870 3891
6871/** 3892 if ( !xe || !ye ) {
6872 * Determine if a value is a URLSearchParams object
6873 *
6874 * @param {Object} val The value to test
6875 * @returns {boolean} True if value is a URLSearchParams object, otherwise false
6876 */
6877function isURLSearchParams(val) {
6878 return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
6879}
6880 3893
6881/** 3894 // Either Infinity?
6882 * Trim excess whitespace off the beginning and end of a string 3895 if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN );
6883 *
6884 * @param {String} str The String to trim
6885 * @returns {String} The String freed of excess whitespace
6886 */
6887function trim(str) {
6888 return str.replace(/^\s*/, '').replace(/\s*$/, '');
6889}
6890 3896
6891/** 3897 // Either zero?
6892 * Determine if we're running in a standard browser environment 3898 if ( !xc[0] || !yc[0] ) {
6893 *
6894 * This allows axios to run in a web worker, and react-native.
6895 * Both environments support XMLHttpRequest, but not fully standard globals.
6896 *
6897 * web workers:
6898 * typeof window -> undefined
6899 * typeof document -> undefined
6900 *
6901 * react-native:
6902 * navigator.product -> 'ReactNative'
6903 */
6904function isStandardBrowserEnv() {
6905 if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {
6906 return false;
6907 }
6908 return (
6909 typeof window !== 'undefined' &&
6910 typeof document !== 'undefined'
6911 );
6912}
6913 3899
6914/** 3900 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
6915 * Iterate over an Array or an Object invoking a function for each item. 3901 return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x :
6916 *
6917 * If `obj` is an Array callback will be called passing
6918 * the value, index, and complete array for each item.
6919 *
6920 * If 'obj' is an Object callback will be called passing
6921 * the value, key, and complete object for each property.
6922 *
6923 * @param {Object|Array} obj The object to iterate
6924 * @param {Function} fn The callback to invoke for each item
6925 */
6926function forEach(obj, fn) {
6927 // Don't bother if no value provided
6928 if (obj === null || typeof obj === 'undefined') {
6929 return;
6930 }
6931 3902
6932 // Force an array if not already something iterable 3903 // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
6933 if (typeof obj !== 'object') { 3904 ROUNDING_MODE == 3 ? -0 : 0 );
6934 /*eslint no-param-reassign:0*/ 3905 }
6935 obj = [obj]; 3906 }
6936 }
6937 3907
6938 if (isArray(obj)) { 3908 xe = bitFloor(xe);
6939 // Iterate over array values 3909 ye = bitFloor(ye);
6940 for (var i = 0, l = obj.length; i < l; i++) { 3910 xc = xc.slice();
6941 fn.call(null, obj[i], i, obj);
6942 }
6943 } else {
6944 // Iterate over object keys
6945 for (var key in obj) {
6946 if (Object.prototype.hasOwnProperty.call(obj, key)) {
6947 fn.call(null, obj[key], key, obj);
6948 }
6949 }
6950 }
6951}
6952 3911
6953/** 3912 // Determine which is the bigger number.
6954 * Accepts varargs expecting each argument to be an object, then 3913 if ( a = xe - ye ) {
6955 * immutably merges the properties of each object and returns result.
6956 *
6957 * When multiple objects contain the same key the later object in
6958 * the arguments list will take precedence.
6959 *
6960 * Example:
6961 *
6962 * ```js
6963 * var result = merge({foo: 123}, {foo: 456});
6964 * console.log(result.foo); // outputs 456
6965 * ```
6966 *
6967 * @param {Object} obj1 Object to merge
6968 * @returns {Object} Result of all merge properties
6969 */
6970function merge(/* obj1, obj2, obj3, ... */) {
6971 var result = {};
6972 function assignValue(val, key) {
6973 if (typeof result[key] === 'object' && typeof val === 'object') {
6974 result[key] = merge(result[key], val);
6975 } else {
6976 result[key] = val;
6977 }
6978 }
6979 3914
6980 for (var i = 0, l = arguments.length; i < l; i++) { 3915 if ( xLTy = a < 0 ) {
6981 forEach(arguments[i], assignValue); 3916 a = -a;
6982 } 3917 t = xc;
6983 return result; 3918 } else {
6984} 3919 ye = xe;
3920 t = yc;
3921 }
6985 3922
6986/** 3923 t.reverse();
6987 * Extends object a by mutably adding to it the properties of object b.
6988 *
6989 * @param {Object} a The object to be extended
6990 * @param {Object} b The object to copy properties from
6991 * @param {Object} thisArg The object to bind function to
6992 * @return {Object} The resulting value of object a
6993 */
6994function extend(a, b, thisArg) {
6995 forEach(b, function assignValue(val, key) {
6996 if (thisArg && typeof val === 'function') {
6997 a[key] = bind(val, thisArg);
6998 } else {
6999 a[key] = val;
7000 }
7001 });
7002 return a;
7003}
7004 3924
7005module.exports = { 3925 // Prepend zeros to equalise exponents.
7006 isArray: isArray, 3926 for ( b = a; b--; t.push(0) );
7007 isArrayBuffer: isArrayBuffer, 3927 t.reverse();
7008 isBuffer: isBuffer, 3928 } else {
7009 isFormData: isFormData,
7010 isArrayBufferView: isArrayBufferView,
7011 isString: isString,
7012 isNumber: isNumber,
7013 isObject: isObject,
7014 isUndefined: isUndefined,
7015 isDate: isDate,
7016 isFile: isFile,
7017 isBlob: isBlob,
7018 isFunction: isFunction,
7019 isStream: isStream,
7020 isURLSearchParams: isURLSearchParams,
7021 isStandardBrowserEnv: isStandardBrowserEnv,
7022 forEach: forEach,
7023 merge: merge,
7024 extend: extend,
7025 trim: trim
7026};
7027
7028},{"./helpers/bind":60,"is-buffer":164}],71:[function(require,module,exports){
7029// base-x encoding
7030// Forked from https://github.com/cryptocoinjs/bs58
7031// Originally written by Mike Hearn for BitcoinJ
7032// Copyright (c) 2011 Google Inc
7033// Ported to JavaScript by Stefan Thomas
7034// Merged Buffer refactorings from base58-native by Stephen Pair
7035// Copyright (c) 2013 BitPay Inc
7036 3929
7037var Buffer = require('safe-buffer').Buffer 3930 // Exponents equal. Check digit by digit.
3931 j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b;
7038 3932
7039module.exports = function base (ALPHABET) { 3933 for ( a = b = 0; b < j; b++ ) {
7040 var ALPHABET_MAP = {}
7041 var BASE = ALPHABET.length
7042 var LEADER = ALPHABET.charAt(0)
7043 3934
7044 // pre-compute lookup table 3935 if ( xc[b] != yc[b] ) {
7045 for (var z = 0; z < ALPHABET.length; z++) { 3936 xLTy = xc[b] < yc[b];
7046 var x = ALPHABET.charAt(z) 3937 break;
3938 }
3939 }
3940 }
7047 3941
7048 if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') 3942 // x < y? Point xc to the array of the bigger number.
7049 ALPHABET_MAP[x] = z 3943 if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
7050 }
7051 3944
7052 function encode (source) { 3945 b = ( j = yc.length ) - ( i = xc.length );
7053 if (source.length === 0) return ''
7054 3946
7055 var digits = [0] 3947 // Append zeros to xc if shorter.
7056 for (var i = 0; i < source.length; ++i) { 3948 // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
7057 for (var j = 0, carry = source[i]; j < digits.length; ++j) { 3949 if ( b > 0 ) for ( ; b--; xc[i++] = 0 );
7058 carry += digits[j] << 8 3950 b = BASE - 1;
7059 digits[j] = carry % BASE
7060 carry = (carry / BASE) | 0
7061 }
7062 3951
7063 while (carry > 0) { 3952 // Subtract yc from xc.
7064 digits.push(carry % BASE) 3953 for ( ; j > a; ) {
7065 carry = (carry / BASE) | 0
7066 }
7067 }
7068 3954
7069 var string = '' 3955 if ( xc[--j] < yc[j] ) {
3956 for ( i = j; i && !xc[--i]; xc[i] = b );
3957 --xc[i];
3958 xc[j] += BASE;
3959 }
7070 3960
7071 // deal with leading zeros 3961 xc[j] -= yc[j];
7072 for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += LEADER 3962 }
7073 // convert digits to a string
7074 for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]]
7075 3963
7076 return string 3964 // Remove leading zeros and adjust exponent accordingly.
7077 } 3965 for ( ; xc[0] == 0; xc.splice(0, 1), --ye );
7078 3966
7079 function decodeUnsafe (string) { 3967 // Zero?
7080 if (typeof string !== 'string') throw new TypeError('Expected String') 3968 if ( !xc[0] ) {
7081 if (string.length === 0) return Buffer.allocUnsafe(0)
7082 3969
7083 var bytes = [0] 3970 // Following IEEE 754 (2008) 6.3,
7084 for (var i = 0; i < string.length; i++) { 3971 // n - n = +0 but n - n = -0 when rounding towards -Infinity.
7085 var value = ALPHABET_MAP[string[i]] 3972 y.s = ROUNDING_MODE == 3 ? -1 : 1;
7086 if (value === undefined) return 3973 y.c = [ y.e = 0 ];
3974 return y;
3975 }
7087 3976
7088 for (var j = 0, carry = value; j < bytes.length; ++j) { 3977 // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
7089 carry += bytes[j] * BASE 3978 // for finite x and y.
7090 bytes[j] = carry & 0xff 3979 return normalise( y, xc, ye );
7091 carry >>= 8 3980 };
7092 }
7093 3981
7094 while (carry > 0) { 3982
7095 bytes.push(carry & 0xff) 3983 /*
7096 carry >>= 8 3984 * n % 0 = N
7097 } 3985 * n % N = N
3986 * n % I = n
3987 * 0 % n = 0
3988 * -0 % n = -0
3989 * 0 % 0 = N
3990 * 0 % N = N
3991 * 0 % I = 0
3992 * N % n = N
3993 * N % 0 = N
3994 * N % N = N
3995 * N % I = N
3996 * I % n = N
3997 * I % 0 = N
3998 * I % N = N
3999 * I % I = N
4000 *
4001 * Return a new BigNumber whose value is the value of this BigNumber modulo the value of
4002 * BigNumber(y, b). The result depends on the value of MODULO_MODE.
4003 */
4004 P.modulo = P.mod = function ( y, b ) {
4005 var q, s,
4006 x = this;
4007
4008 id = 11;
4009 y = new BigNumber( y, b );
4010
4011 // Return NaN if x is Infinity or NaN, or y is NaN or zero.
4012 if ( !x.c || !y.s || y.c && !y.c[0] ) {
4013 return new BigNumber(NaN);
4014
4015 // Return x if y is Infinity or x is zero.
4016 } else if ( !y.c || x.c && !x.c[0] ) {
4017 return new BigNumber(x);
4018 }
4019
4020 if ( MODULO_MODE == 9 ) {
4021
4022 // Euclidian division: q = sign(y) * floor(x / abs(y))
4023 // r = x - qy where 0 <= r < abs(y)
4024 s = y.s;
4025 y.s = 1;
4026 q = div( x, y, 0, 3 );
4027 y.s = s;
4028 q.s *= s;
4029 } else {
4030 q = div( x, y, 0, MODULO_MODE );
4031 }
4032
4033 return x.minus( q.times(y) );
4034 };
4035
4036
4037 /*
4038 * Return a new BigNumber whose value is the value of this BigNumber negated,
4039 * i.e. multiplied by -1.
4040 */
4041 P.negated = P.neg = function () {
4042 var x = new BigNumber(this);
4043 x.s = -x.s || null;
4044 return x;
4045 };
4046
4047
4048 /*
4049 * n + 0 = n
4050 * n + N = N
4051 * n + I = I
4052 * 0 + n = n
4053 * 0 + 0 = 0
4054 * 0 + N = N
4055 * 0 + I = I
4056 * N + n = N
4057 * N + 0 = N
4058 * N + N = N
4059 * N + I = N
4060 * I + n = I
4061 * I + 0 = I
4062 * I + N = N
4063 * I + I = I
4064 *
4065 * Return a new BigNumber whose value is the value of this BigNumber plus the value of
4066 * BigNumber(y, b).
4067 */
4068 P.plus = P.add = function ( y, b ) {
4069 var t,
4070 x = this,
4071 a = x.s;
4072
4073 id = 12;
4074 y = new BigNumber( y, b );
4075 b = y.s;
4076
4077 // Either NaN?
4078 if ( !a || !b ) return new BigNumber(NaN);
4079
4080 // Signs differ?
4081 if ( a != b ) {
4082 y.s = -b;
4083 return x.minus(y);
4084 }
4085
4086 var xe = x.e / LOG_BASE,
4087 ye = y.e / LOG_BASE,
4088 xc = x.c,
4089 yc = y.c;
4090
4091 if ( !xe || !ye ) {
4092
4093 // Return ±Infinity if either ±Infinity.
4094 if ( !xc || !yc ) return new BigNumber( a / 0 );
4095
4096 // Either zero?
4097 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
4098 if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 );
4099 }
4100
4101 xe = bitFloor(xe);
4102 ye = bitFloor(ye);
4103 xc = xc.slice();
4104
4105 // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
4106 if ( a = xe - ye ) {
4107 if ( a > 0 ) {
4108 ye = xe;
4109 t = yc;
4110 } else {
4111 a = -a;
4112 t = xc;
4113 }
4114
4115 t.reverse();
4116 for ( ; a--; t.push(0) );
4117 t.reverse();
4118 }
4119
4120 a = xc.length;
4121 b = yc.length;
4122
4123 // Point xc to the longer array, and b to the shorter length.
4124 if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a;
4125
4126 // Only start adding at yc.length - 1 as the further digits of xc can be ignored.
4127 for ( a = 0; b; ) {
4128 a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0;
4129 xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;
4130 }
4131
4132 if (a) {
4133 xc = [a].concat(xc);
4134 ++ye;
4135 }
4136
4137 // No need to check for zero, as +x + +y != 0 && -x + -y != 0
4138 // ye = MAX_EXP + 1 possible
4139 return normalise( y, xc, ye );
4140 };
4141
4142
4143 /*
4144 * Return the number of significant digits of the value of this BigNumber.
4145 *
4146 * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
4147 */
4148 P.precision = P.sd = function (z) {
4149 var n, v,
4150 x = this,
4151 c = x.c;
4152
4153 // 'precision() argument not a boolean or binary digit: {z}'
4154 if ( z != null && z !== !!z && z !== 1 && z !== 0 ) {
4155 if (ERRORS) raise( 13, 'argument' + notBool, z );
4156 if ( z != !!z ) z = null;
4157 }
4158
4159 if ( !c ) return null;
4160 v = c.length - 1;
4161 n = v * LOG_BASE + 1;
4162
4163 if ( v = c[v] ) {
4164
4165 // Subtract the number of trailing zeros of the last element.
4166 for ( ; v % 10 == 0; v /= 10, n-- );
4167
4168 // Add the number of digits of the first element.
4169 for ( v = c[0]; v >= 10; v /= 10, n++ );
4170 }
4171
4172 if ( z && x.e + 1 > n ) n = x.e + 1;
4173
4174 return n;
4175 };
4176
4177
4178 /*
4179 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
4180 * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if
4181 * omitted.
4182 *
4183 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
4184 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4185 *
4186 * 'round() decimal places out of range: {dp}'
4187 * 'round() decimal places not an integer: {dp}'
4188 * 'round() rounding mode not an integer: {rm}'
4189 * 'round() rounding mode out of range: {rm}'
4190 */
4191 P.round = function ( dp, rm ) {
4192 var n = new BigNumber(this);
4193
4194 if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) {
4195 round( n, ~~dp + this.e + 1, rm == null ||
4196 !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 );
4197 }
4198
4199 return n;
4200 };
4201
4202
4203 /*
4204 * Return a new BigNumber whose value is the value of this BigNumber shifted by k places
4205 * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
4206 *
4207 * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
4208 *
4209 * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity
4210 * otherwise.
4211 *
4212 * 'shift() argument not an integer: {k}'
4213 * 'shift() argument out of range: {k}'
4214 */
4215 P.shift = function (k) {
4216 var n = this;
4217 return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' )
4218
4219 // k < 1e+21, or truncate(k) will produce exponential notation.
4220 ? n.times( '1e' + truncate(k) )
4221 : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER )
4222 ? n.s * ( k < 0 ? 0 : 1 / 0 )
4223 : n );
4224 };
4225
4226
4227 /*
4228 * sqrt(-n) = N
4229 * sqrt( N) = N
4230 * sqrt(-I) = N
4231 * sqrt( I) = I
4232 * sqrt( 0) = 0
4233 * sqrt(-0) = -0
4234 *
4235 * Return a new BigNumber whose value is the square root of the value of this BigNumber,
4236 * rounded according to DECIMAL_PLACES and ROUNDING_MODE.
4237 */
4238 P.squareRoot = P.sqrt = function () {
4239 var m, n, r, rep, t,
4240 x = this,
4241 c = x.c,
4242 s = x.s,
4243 e = x.e,
4244 dp = DECIMAL_PLACES + 4,
4245 half = new BigNumber('0.5');
4246
4247 // Negative/NaN/Infinity/zero?
4248 if ( s !== 1 || !c || !c[0] ) {
4249 return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );
4250 }
4251
4252 // Initial estimate.
4253 s = Math.sqrt( +x );
4254
4255 // Math.sqrt underflow/overflow?
4256 // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
4257 if ( s == 0 || s == 1 / 0 ) {
4258 n = coeffToString(c);
4259 if ( ( n.length + e ) % 2 == 0 ) n += '0';
4260 s = Math.sqrt(n);
4261 e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
4262
4263 if ( s == 1 / 0 ) {
4264 n = '1e' + e;
4265 } else {
4266 n = s.toExponential();
4267 n = n.slice( 0, n.indexOf('e') + 1 ) + e;
4268 }
4269
4270 r = new BigNumber(n);
4271 } else {
4272 r = new BigNumber( s + '' );
4273 }
4274
4275 // Check for zero.
4276 // r could be zero if MIN_EXP is changed after the this value was created.
4277 // This would cause a division by zero (x/t) and hence Infinity below, which would cause
4278 // coeffToString to throw.
4279 if ( r.c[0] ) {
4280 e = r.e;
4281 s = e + dp;
4282 if ( s < 3 ) s = 0;
4283
4284 // Newton-Raphson iteration.
4285 for ( ; ; ) {
4286 t = r;
4287 r = half.times( t.plus( div( x, t, dp, 1 ) ) );
4288
4289 if ( coeffToString( t.c ).slice( 0, s ) === ( n =
4290 coeffToString( r.c ) ).slice( 0, s ) ) {
4291
4292 // The exponent of r may here be one less than the final result exponent,
4293 // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
4294 // are indexed correctly.
4295 if ( r.e < e ) --s;
4296 n = n.slice( s - 3, s + 1 );
4297
4298 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits
4299 // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
4300 // iteration.
4301 if ( n == '9999' || !rep && n == '4999' ) {
4302
4303 // On the first iteration only, check to see if rounding up gives the
4304 // exact result as the nines may infinitely repeat.
4305 if ( !rep ) {
4306 round( t, t.e + DECIMAL_PLACES + 2, 0 );
4307
4308 if ( t.times(t).eq(x) ) {
4309 r = t;
4310 break;
4311 }
4312 }
4313
4314 dp += 4;
4315 s += 4;
4316 rep = 1;
4317 } else {
4318
4319 // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
4320 // result. If not, then there are further digits and m will be truthy.
4321 if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {
4322
4323 // Truncate to the first rounding digit.
4324 round( r, r.e + DECIMAL_PLACES + 2, 1 );
4325 m = !r.times(r).eq(x);
4326 }
4327
4328 break;
4329 }
4330 }
4331 }
4332 }
4333
4334 return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m );
4335 };
4336
4337
4338 /*
4339 * n * 0 = 0
4340 * n * N = N
4341 * n * I = I
4342 * 0 * n = 0
4343 * 0 * 0 = 0
4344 * 0 * N = N
4345 * 0 * I = N
4346 * N * n = N
4347 * N * 0 = N
4348 * N * N = N
4349 * N * I = N
4350 * I * n = I
4351 * I * 0 = N
4352 * I * N = N
4353 * I * I = I
4354 *
4355 * Return a new BigNumber whose value is the value of this BigNumber times the value of
4356 * BigNumber(y, b).
4357 */
4358 P.times = P.mul = function ( y, b ) {
4359 var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
4360 base, sqrtBase,
4361 x = this,
4362 xc = x.c,
4363 yc = ( id = 17, y = new BigNumber( y, b ) ).c;
4364
4365 // Either NaN, ±Infinity or ±0?
4366 if ( !xc || !yc || !xc[0] || !yc[0] ) {
4367
4368 // Return NaN if either is NaN, or one is 0 and the other is Infinity.
4369 if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) {
4370 y.c = y.e = y.s = null;
4371 } else {
4372 y.s *= x.s;
4373
4374 // Return ±Infinity if either is ±Infinity.
4375 if ( !xc || !yc ) {
4376 y.c = y.e = null;
4377
4378 // Return ±0 if either is ±0.
4379 } else {
4380 y.c = [0];
4381 y.e = 0;
4382 }
4383 }
4384
4385 return y;
4386 }
4387
4388 e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE );
4389 y.s *= x.s;
4390 xcL = xc.length;
4391 ycL = yc.length;
4392
4393 // Ensure xc points to longer array and xcL to its length.
4394 if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
4395
4396 // Initialise the result array with zeros.
4397 for ( i = xcL + ycL, zc = []; i--; zc.push(0) );
4398
4399 base = BASE;
4400 sqrtBase = SQRT_BASE;
4401
4402 for ( i = ycL; --i >= 0; ) {
4403 c = 0;
4404 ylo = yc[i] % sqrtBase;
4405 yhi = yc[i] / sqrtBase | 0;
4406
4407 for ( k = xcL, j = i + k; j > i; ) {
4408 xlo = xc[--k] % sqrtBase;
4409 xhi = xc[k] / sqrtBase | 0;
4410 m = yhi * xlo + xhi * ylo;
4411 xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c;
4412 c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi;
4413 zc[j--] = xlo % base;
4414 }
4415
4416 zc[j] = c;
4417 }
4418
4419 if (c) {
4420 ++e;
4421 } else {
4422 zc.splice(0, 1);
4423 }
4424
4425 return normalise( y, zc, e );
4426 };
4427
4428
4429 /*
4430 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
4431 * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted.
4432 *
4433 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
4434 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4435 *
4436 * 'toDigits() precision out of range: {sd}'
4437 * 'toDigits() precision not an integer: {sd}'
4438 * 'toDigits() rounding mode not an integer: {rm}'
4439 * 'toDigits() rounding mode out of range: {rm}'
4440 */
4441 P.toDigits = function ( sd, rm ) {
4442 var n = new BigNumber(this);
4443 sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0;
4444 rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0;
4445 return sd ? round( n, sd, rm ) : n;
4446 };
4447
4448
4449 /*
4450 * Return a string representing the value of this BigNumber in exponential notation and
4451 * rounded using ROUNDING_MODE to dp fixed decimal places.
4452 *
4453 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
4454 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4455 *
4456 * 'toExponential() decimal places not an integer: {dp}'
4457 * 'toExponential() decimal places out of range: {dp}'
4458 * 'toExponential() rounding mode not an integer: {rm}'
4459 * 'toExponential() rounding mode out of range: {rm}'
4460 */
4461 P.toExponential = function ( dp, rm ) {
4462 return format( this,
4463 dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 );
4464 };
4465
4466
4467 /*
4468 * Return a string representing the value of this BigNumber in fixed-point notation rounding
4469 * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
4470 *
4471 * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
4472 * but e.g. (-0.00001).toFixed(0) is '-0'.
4473 *
4474 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
4475 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4476 *
4477 * 'toFixed() decimal places not an integer: {dp}'
4478 * 'toFixed() decimal places out of range: {dp}'
4479 * 'toFixed() rounding mode not an integer: {rm}'
4480 * 'toFixed() rounding mode out of range: {rm}'
4481 */
4482 P.toFixed = function ( dp, rm ) {
4483 return format( this, dp != null && isValidInt( dp, 0, MAX, 20 )
4484 ? ~~dp + this.e + 1 : null, rm, 20 );
4485 };
4486
4487
4488 /*
4489 * Return a string representing the value of this BigNumber in fixed-point notation rounded
4490 * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
4491 * of the FORMAT object (see BigNumber.config).
4492 *
4493 * FORMAT = {
4494 * decimalSeparator : '.',
4495 * groupSeparator : ',',
4496 * groupSize : 3,
4497 * secondaryGroupSize : 0,
4498 * fractionGroupSeparator : '\xA0', // non-breaking space
4499 * fractionGroupSize : 0
4500 * };
4501 *
4502 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
4503 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4504 *
4505 * 'toFormat() decimal places not an integer: {dp}'
4506 * 'toFormat() decimal places out of range: {dp}'
4507 * 'toFormat() rounding mode not an integer: {rm}'
4508 * 'toFormat() rounding mode out of range: {rm}'
4509 */
4510 P.toFormat = function ( dp, rm ) {
4511 var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 )
4512 ? ~~dp + this.e + 1 : null, rm, 21 );
4513
4514 if ( this.c ) {
4515 var i,
4516 arr = str.split('.'),
4517 g1 = +FORMAT.groupSize,
4518 g2 = +FORMAT.secondaryGroupSize,
4519 groupSeparator = FORMAT.groupSeparator,
4520 intPart = arr[0],
4521 fractionPart = arr[1],
4522 isNeg = this.s < 0,
4523 intDigits = isNeg ? intPart.slice(1) : intPart,
4524 len = intDigits.length;
4525
4526 if (g2) i = g1, g1 = g2, g2 = i, len -= i;
4527
4528 if ( g1 > 0 && len > 0 ) {
4529 i = len % g1 || g1;
4530 intPart = intDigits.substr( 0, i );
4531
4532 for ( ; i < len; i += g1 ) {
4533 intPart += groupSeparator + intDigits.substr( i, g1 );
4534 }
4535
4536 if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i);
4537 if (isNeg) intPart = '-' + intPart;
4538 }
4539
4540 str = fractionPart
4541 ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize )
4542 ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ),
4543 '$&' + FORMAT.fractionGroupSeparator )
4544 : fractionPart )
4545 : intPart;
4546 }
4547
4548 return str;
4549 };
4550
4551
4552 /*
4553 * Return a string array representing the value of this BigNumber as a simple fraction with
4554 * an integer numerator and an integer denominator. The denominator will be a positive
4555 * non-zero value less than or equal to the specified maximum denominator. If a maximum
4556 * denominator is not specified, the denominator will be the lowest value necessary to
4557 * represent the number exactly.
4558 *
4559 * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.
4560 *
4561 * 'toFraction() max denominator not an integer: {md}'
4562 * 'toFraction() max denominator out of range: {md}'
4563 */
4564 P.toFraction = function (md) {
4565 var arr, d0, d2, e, exp, n, n0, q, s,
4566 k = ERRORS,
4567 x = this,
4568 xc = x.c,
4569 d = new BigNumber(ONE),
4570 n1 = d0 = new BigNumber(ONE),
4571 d1 = n0 = new BigNumber(ONE);
4572
4573 if ( md != null ) {
4574 ERRORS = false;
4575 n = new BigNumber(md);
4576 ERRORS = k;
4577
4578 if ( !( k = n.isInt() ) || n.lt(ONE) ) {
4579
4580 if (ERRORS) {
4581 raise( 22,
4582 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
4583 }
4584
4585 // ERRORS is false:
4586 // If md is a finite non-integer >= 1, round it to an integer and use it.
4587 md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null;
4588 }
4589 }
4590
4591 if ( !xc ) return x.toString();
4592 s = coeffToString(xc);
4593
4594 // Determine initial denominator.
4595 // d is a power of 10 and the minimum max denominator that specifies the value exactly.
4596 e = d.e = s.length - x.e - 1;
4597 d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];
4598 md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n;
4599
4600 exp = MAX_EXP;
4601 MAX_EXP = 1 / 0;
4602 n = new BigNumber(s);
4603
4604 // n0 = d1 = 0
4605 n0.c[0] = 0;
4606
4607 for ( ; ; ) {
4608 q = div( n, d, 0, 1 );
4609 d2 = d0.plus( q.times(d1) );
4610 if ( d2.cmp(md) == 1 ) break;
4611 d0 = d1;
4612 d1 = d2;
4613 n1 = n0.plus( q.times( d2 = n1 ) );
4614 n0 = d2;
4615 d = n.minus( q.times( d2 = d ) );
4616 n = d2;
4617 }
4618
4619 d2 = div( md.minus(d0), d1, 0, 1 );
4620 n0 = n0.plus( d2.times(n1) );
4621 d0 = d0.plus( d2.times(d1) );
4622 n0.s = n1.s = x.s;
4623 e *= 2;
4624
4625 // Determine which fraction is closer to x, n0/d0 or n1/d1
4626 arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp(
4627 div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1
4628 ? [ n1.toString(), d1.toString() ]
4629 : [ n0.toString(), d0.toString() ];
4630
4631 MAX_EXP = exp;
4632 return arr;
4633 };
4634
4635
4636 /*
4637 * Return the value of this BigNumber converted to a number primitive.
4638 */
4639 P.toNumber = function () {
4640 return +this;
4641 };
4642
4643
4644 /*
4645 * Return a BigNumber whose value is the value of this BigNumber raised to the power n.
4646 * If m is present, return the result modulo m.
4647 * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
4648 * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using
4649 * ROUNDING_MODE.
4650 *
4651 * The modular power operation works efficiently when x, n, and m are positive integers,
4652 * otherwise it is equivalent to calculating x.toPower(n).modulo(m) (with POW_PRECISION 0).
4653 *
4654 * n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
4655 * [m] {number|string|BigNumber} The modulus.
4656 *
4657 * 'pow() exponent not an integer: {n}'
4658 * 'pow() exponent out of range: {n}'
4659 *
4660 * Performs 54 loop iterations for n of 9007199254740991.
4661 */
4662 P.toPower = P.pow = function ( n, m ) {
4663 var k, y, z,
4664 i = mathfloor( n < 0 ? -n : +n ),
4665 x = this;
4666
4667 if ( m != null ) {
4668 id = 23;
4669 m = new BigNumber(m);
4670 }
4671
4672 // Pass ±Infinity to Math.pow if exponent is out of range.
4673 if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) &&
4674 ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) ||
4675 parseFloat(n) != n && !( n = NaN ) ) || n == 0 ) {
4676 k = Math.pow( +x, n );
4677 return new BigNumber( m ? k % m : k );
4678 }
4679
4680 if (m) {
4681 if ( n > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt() ) {
4682 x = x.mod(m);
4683 } else {
4684 z = m;
4685
4686 // Nullify m so only a single mod operation is performed at the end.
4687 m = null;
4688 }
4689 } else if (POW_PRECISION) {
4690
4691 // Truncating each coefficient array to a length of k after each multiplication
4692 // equates to truncating significant digits to POW_PRECISION + [28, 41],
4693 // i.e. there will be a minimum of 28 guard digits retained.
4694 // (Using + 1.5 would give [9, 21] guard digits.)
4695 k = mathceil( POW_PRECISION / LOG_BASE + 2 );
4696 }
4697
4698 y = new BigNumber(ONE);
4699
4700 for ( ; ; ) {
4701 if ( i % 2 ) {
4702 y = y.times(x);
4703 if ( !y.c ) break;
4704 if (k) {
4705 if ( y.c.length > k ) y.c.length = k;
4706 } else if (m) {
4707 y = y.mod(m);
4708 }
4709 }
4710
4711 i = mathfloor( i / 2 );
4712 if ( !i ) break;
4713 x = x.times(x);
4714 if (k) {
4715 if ( x.c && x.c.length > k ) x.c.length = k;
4716 } else if (m) {
4717 x = x.mod(m);
4718 }
4719 }
4720
4721 if (m) return y;
4722 if ( n < 0 ) y = ONE.div(y);
4723
4724 return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;
4725 };
4726
4727
4728 /*
4729 * Return a string representing the value of this BigNumber rounded to sd significant digits
4730 * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
4731 * necessary to represent the integer part of the value in fixed-point notation, then use
4732 * exponential notation.
4733 *
4734 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
4735 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
4736 *
4737 * 'toPrecision() precision not an integer: {sd}'
4738 * 'toPrecision() precision out of range: {sd}'
4739 * 'toPrecision() rounding mode not an integer: {rm}'
4740 * 'toPrecision() rounding mode out of range: {rm}'
4741 */
4742 P.toPrecision = function ( sd, rm ) {
4743 return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' )
4744 ? sd | 0 : null, rm, 24 );
4745 };
4746
4747
4748 /*
4749 * Return a string representing the value of this BigNumber in base b, or base 10 if b is
4750 * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
4751 * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
4752 * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
4753 * TO_EXP_NEG, return exponential notation.
4754 *
4755 * [b] {number} Integer, 2 to 64 inclusive.
4756 *
4757 * 'toString() base not an integer: {b}'
4758 * 'toString() base out of range: {b}'
4759 */
4760 P.toString = function (b) {
4761 var str,
4762 n = this,
4763 s = n.s,
4764 e = n.e;
4765
4766 // Infinity or NaN?
4767 if ( e === null ) {
4768
4769 if (s) {
4770 str = 'Infinity';
4771 if ( s < 0 ) str = '-' + str;
4772 } else {
4773 str = 'NaN';
4774 }
4775 } else {
4776 str = coeffToString( n.c );
4777
4778 if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) {
4779 str = e <= TO_EXP_NEG || e >= TO_EXP_POS
4780 ? toExponential( str, e )
4781 : toFixedPoint( str, e );
4782 } else {
4783 str = convertBase( toFixedPoint( str, e ), b | 0, 10, s );
4784 }
4785
4786 if ( s < 0 && n.c[0] ) str = '-' + str;
4787 }
4788
4789 return str;
4790 };
4791
4792
4793 /*
4794 * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole
4795 * number.
4796 */
4797 P.truncated = P.trunc = function () {
4798 return round( new BigNumber(this), this.e + 1, 1 );
4799 };
4800
4801
4802 /*
4803 * Return as toString, but do not accept a base argument, and include the minus sign for
4804 * negative zero.
4805 */
4806 P.valueOf = P.toJSON = function () {
4807 var str,
4808 n = this,
4809 e = n.e;
4810
4811 if ( e === null ) return n.toString();
4812
4813 str = coeffToString( n.c );
4814
4815 str = e <= TO_EXP_NEG || e >= TO_EXP_POS
4816 ? toExponential( str, e )
4817 : toFixedPoint( str, e );
4818
4819 return n.s < 0 ? '-' + str : str;
4820 };
4821
4822
4823 P.isBigNumber = true;
4824
4825 if ( config != null ) BigNumber.config(config);
4826
4827 return BigNumber;
7098 } 4828 }
7099 4829
7100 // deal with leading zeros 4830
7101 for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) { 4831 // PRIVATE HELPER FUNCTIONS
7102 bytes.push(0) 4832
4833
4834 function bitFloor(n) {
4835 var i = n | 0;
4836 return n > 0 || n === i ? i : i - 1;
7103 } 4837 }
7104 4838
7105 return Buffer.from(bytes.reverse())
7106 }
7107 4839
7108 function decode (string) { 4840 // Return a coefficient array as a string of base 10 digits.
7109 var buffer = decodeUnsafe(string) 4841 function coeffToString(a) {
7110 if (buffer) return buffer 4842 var s, z,
4843 i = 1,
4844 j = a.length,
4845 r = a[0] + '';
7111 4846
7112 throw new Error('Non-base' + BASE + ' character') 4847 for ( ; i < j; ) {
7113 } 4848 s = a[i++] + '';
4849 z = LOG_BASE - s.length;
4850 for ( ; z--; s = '0' + s );
4851 r += s;
4852 }
7114 4853
7115 return { 4854 // Determine trailing zeros.
7116 encode: encode, 4855 for ( j = r.length; r.charCodeAt(--j) === 48; );
7117 decodeUnsafe: decodeUnsafe, 4856 return r.slice( 0, j + 1 || 1 );
7118 decode: decode 4857 }
7119 }
7120}
7121 4858
7122},{"safe-buffer":247}],72:[function(require,module,exports){
7123'use strict'
7124 4859
7125exports.byteLength = byteLength 4860 // Compare the value of BigNumbers x and y.
7126exports.toByteArray = toByteArray 4861 function compare( x, y ) {
7127exports.fromByteArray = fromByteArray 4862 var a, b,
4863 xc = x.c,
4864 yc = y.c,
4865 i = x.s,
4866 j = y.s,
4867 k = x.e,
4868 l = y.e;
7128 4869
7129var lookup = [] 4870 // Either NaN?
7130var revLookup = [] 4871 if ( !i || !j ) return null;
7131var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
7132 4872
7133var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' 4873 a = xc && !xc[0];
7134for (var i = 0, len = code.length; i < len; ++i) { 4874 b = yc && !yc[0];
7135 lookup[i] = code[i]
7136 revLookup[code.charCodeAt(i)] = i
7137}
7138 4875
7139revLookup['-'.charCodeAt(0)] = 62 4876 // Either zero?
7140revLookup['_'.charCodeAt(0)] = 63 4877 if ( a || b ) return a ? b ? 0 : -j : i;
7141 4878
7142function placeHoldersCount (b64) { 4879 // Signs differ?
7143 var len = b64.length 4880 if ( i != j ) return i;
7144 if (len % 4 > 0) {
7145 throw new Error('Invalid string. Length must be a multiple of 4')
7146 }
7147 4881
7148 // the number of equal signs (place holders) 4882 a = i < 0;
7149 // if there are two placeholders, than the two characters before it 4883 b = k == l;
7150 // represent one byte
7151 // if there is only one, then the three characters before it represent 2 bytes
7152 // this is just a cheap hack to not do indexOf twice
7153 return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
7154}
7155 4884
7156function byteLength (b64) { 4885 // Either Infinity?
7157 // base64 is 4/3 + up to two characters of the original data 4886 if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1;
7158 return (b64.length * 3 / 4) - placeHoldersCount(b64)
7159}
7160 4887
7161function toByteArray (b64) { 4888 // Compare exponents.
7162 var i, l, tmp, placeHolders, arr 4889 if ( !b ) return k > l ^ a ? 1 : -1;
7163 var len = b64.length
7164 placeHolders = placeHoldersCount(b64)
7165 4890
7166 arr = new Arr((len * 3 / 4) - placeHolders) 4891 j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
7167 4892
7168 // if there are placeholders, only get up to the last complete 4 chars 4893 // Compare digit by digit.
7169 l = placeHolders > 0 ? len - 4 : len 4894 for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1;
7170 4895
7171 var L = 0 4896 // Compare lengths.
4897 return k == l ? 0 : k > l ^ a ? 1 : -1;
4898 }
7172 4899
7173 for (i = 0; i < l; i += 4) {
7174 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
7175 arr[L++] = (tmp >> 16) & 0xFF
7176 arr[L++] = (tmp >> 8) & 0xFF
7177 arr[L++] = tmp & 0xFF
7178 }
7179 4900
7180 if (placeHolders === 2) { 4901 /*
7181 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) 4902 * Return true if n is a valid number in range, otherwise false.
7182 arr[L++] = tmp & 0xFF 4903 * Use for argument validation when ERRORS is false.
7183 } else if (placeHolders === 1) { 4904 * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10.
7184 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) 4905 */
7185 arr[L++] = (tmp >> 8) & 0xFF 4906 function intValidatorNoErrors( n, min, max ) {
7186 arr[L++] = tmp & 0xFF 4907 return ( n = truncate(n) ) >= min && n <= max;
7187 } 4908 }
7188 4909
7189 return arr
7190}
7191 4910
7192function tripletToBase64 (num) { 4911 function isArray(obj) {
7193 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] 4912 return Object.prototype.toString.call(obj) == '[object Array]';
7194} 4913 }
7195 4914
7196function encodeChunk (uint8, start, end) {
7197 var tmp
7198 var output = []
7199 for (var i = start; i < end; i += 3) {
7200 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
7201 output.push(tripletToBase64(tmp))
7202 }
7203 return output.join('')
7204}
7205 4915
7206function fromByteArray (uint8) { 4916 /*
7207 var tmp 4917 * Convert string of baseIn to an array of numbers of baseOut.
7208 var len = uint8.length 4918 * Eg. convertBase('255', 10, 16) returns [15, 15].
7209 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes 4919 * Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
7210 var output = '' 4920 */
7211 var parts = [] 4921 function toBaseOut( str, baseIn, baseOut ) {
7212 var maxChunkLength = 16383 // must be multiple of 3 4922 var j,
4923 arr = [0],
4924 arrL,
4925 i = 0,
4926 len = str.length;
4927
4928 for ( ; i < len; ) {
4929 for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );
4930 arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) );
4931
4932 for ( ; j < arr.length; j++ ) {
4933
4934 if ( arr[j] > baseOut - 1 ) {
4935 if ( arr[j + 1] == null ) arr[j + 1] = 0;
4936 arr[j + 1] += arr[j] / baseOut | 0;
4937 arr[j] %= baseOut;
4938 }
4939 }
4940 }
7213 4941
7214 // go through the array every three bytes, we'll deal with trailing stuff later 4942 return arr.reverse();
7215 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { 4943 }
7216 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
7217 }
7218 4944
7219 // pad the end with zeros, but make sure to not forget the extra bytes
7220 if (extraBytes === 1) {
7221 tmp = uint8[len - 1]
7222 output += lookup[tmp >> 2]
7223 output += lookup[(tmp << 4) & 0x3F]
7224 output += '=='
7225 } else if (extraBytes === 2) {
7226 tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
7227 output += lookup[tmp >> 10]
7228 output += lookup[(tmp >> 4) & 0x3F]
7229 output += lookup[(tmp << 2) & 0x3F]
7230 output += '='
7231 }
7232 4945
7233 parts.push(output) 4946 function toExponential( str, e ) {
4947 return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) +
4948 ( e < 0 ? 'e' : 'e+' ) + e;
4949 }
7234 4950
7235 return parts.join('')
7236}
7237 4951
7238},{}],73:[function(require,module,exports){ 4952 function toFixedPoint( str, e ) {
7239/*! bignumber.js v5.0.0 https://github.com/MikeMcl/bignumber.js/LICENCE */ 4953 var len, z;
7240 4954
7241;(function (globalObj) { 4955 // Negative exponent?
7242 'use strict'; 4956 if ( e < 0 ) {
7243 4957
7244 /* 4958 // Prepend zeros.
7245 bignumber.js v5.0.0 4959 for ( z = '0.'; ++e; z += '0' );
7246 A JavaScript library for arbitrary-precision arithmetic. 4960 str = z + str;
7247 https://github.com/MikeMcl/bignumber.js 4961
7248 Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com> 4962 // Positive exponent
7249 MIT Expat Licence 4963 } else {
7250 */ 4964 len = str.length;
7251 4965
7252 4966 // Append zeros.
7253 var BigNumber, 4967 if ( ++e > len ) {
7254 isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, 4968 for ( z = '0', e -= len; --e; z += '0' );
7255 mathceil = Math.ceil, 4969 str += z;
7256 mathfloor = Math.floor, 4970 } else if ( e < len ) {
7257 notBool = ' not a boolean or binary digit', 4971 str = str.slice( 0, e ) + '.' + str.slice(e);
7258 roundingMode = 'rounding mode', 4972 }
7259 tooManyDigits = 'number type has more than 15 significant digits', 4973 }
7260 ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_', 4974
7261 BASE = 1e14, 4975 return str;
7262 LOG_BASE = 14, 4976 }
7263 MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 4977
7264 // MAX_INT32 = 0x7fffffff, // 2^31 - 1 4978
7265 POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], 4979 function truncate(n) {
7266 SQRT_BASE = 1e7, 4980 n = parseFloat(n);
7267 4981 return n < 0 ? mathceil(n) : mathfloor(n);
7268 /* 4982 }
7269 * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and 4983
7270 * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an 4984
7271 * exception is thrown (if ERRORS is true). 4985 // EXPORT
7272 */ 4986
7273 MAX = 1E9; // 0 to MAX_INT32 4987
7274 4988 BigNumber = constructorFactory();
7275 4989 BigNumber['default'] = BigNumber.BigNumber = BigNumber;
7276 /* 4990
7277 * Create and return a BigNumber constructor. 4991
7278 */ 4992 // AMD.
7279 function constructorFactory(config) { 4993 if ( typeof define == 'function' && define.amd ) {
7280 var div, parseNumeric, 4994 define( function () { return BigNumber; } );
7281 4995
7282 // id tracks the caller function, so its name can be included in error messages. 4996 // Node.js and other environments that support module.exports.
7283 id = 0, 4997 } else if ( typeof module != 'undefined' && module.exports ) {
7284 P = BigNumber.prototype, 4998 module.exports = BigNumber;
7285 ONE = new BigNumber(1), 4999
7286 5000 // Browser.
7287 5001 } else {
7288 /********************************* EDITABLE DEFAULTS **********************************/ 5002 if ( !globalObj ) globalObj = typeof self != 'undefined' ? self : Function('return this')();
7289 5003 globalObj.BigNumber = BigNumber;
7290 5004 }
7291 /* 5005})(this);
7292 * The default values below must be integers within the inclusive ranges stated. 5006
7293 * The values can also be changed at run-time using BigNumber.config. 5007},{}],20:[function(require,module,exports){
7294 */
7295
7296 // The maximum number of decimal places for operations involving division.
7297 DECIMAL_PLACES = 20, // 0 to MAX
7298
7299 /*
7300 * The rounding mode used when rounding to the above decimal places, and when using
7301 * toExponential, toFixed, toFormat and toPrecision, and round (default value).
7302 * UP 0 Away from zero.
7303 * DOWN 1 Towards zero.
7304 * CEIL 2 Towards +Infinity.
7305 * FLOOR 3 Towards -Infinity.
7306 * HALF_UP 4 Towards nearest neighbour. If equidistant, up.
7307 * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
7308 * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
7309 * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
7310 * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
7311 */
7312 ROUNDING_MODE = 4, // 0 to 8
7313
7314 // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
7315
7316 // The exponent value at and beneath which toString returns exponential notation.
7317 // Number type: -7
7318 TO_EXP_NEG = -7, // 0 to -MAX
7319
7320 // The exponent value at and above which toString returns exponential notation.
7321 // Number type: 21
7322 TO_EXP_POS = 21, // 0 to MAX
7323
7324 // RANGE : [MIN_EXP, MAX_EXP]
7325
7326 // The minimum exponent value, beneath which underflow to zero occurs.
7327 // Number type: -324 (5e-324)
7328 MIN_EXP = -1e7, // -1 to -MAX
7329
7330 // The maximum exponent value, above which overflow to Infinity occurs.
7331 // Number type: 308 (1.7976931348623157e+308)
7332 // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
7333 MAX_EXP = 1e7, // 1 to MAX
7334
7335 // Whether BigNumber Errors are ever thrown.
7336 ERRORS = true, // true or false
7337
7338 // Change to intValidatorNoErrors if ERRORS is false.
7339 isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors
7340
7341 // Whether to use cryptographically-secure random number generation, if available.
7342 CRYPTO = false, // true or false
7343
7344 /*
7345 * The modulo mode used when calculating the modulus: a mod n.
7346 * The quotient (q = a / n) is calculated according to the corresponding rounding mode.
7347 * The remainder (r) is calculated as: r = a - n * q.
7348 *
7349 * UP 0 The remainder is positive if the dividend is negative, else is negative.
7350 * DOWN 1 The remainder has the same sign as the dividend.
7351 * This modulo mode is commonly known as 'truncated division' and is
7352 * equivalent to (a % n) in JavaScript.
7353 * FLOOR 3 The remainder has the same sign as the divisor (Python %).
7354 * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
7355 * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
7356 * The remainder is always positive.
7357 *
7358 * The truncated division, floored division, Euclidian division and IEEE 754 remainder
7359 * modes are commonly used for the modulus operation.
7360 * Although the other rounding modes can also be used, they may not give useful results.
7361 */
7362 MODULO_MODE = 1, // 0 to 9
7363
7364 // The maximum number of significant digits of the result of the toPower operation.
7365 // If POW_PRECISION is 0, there will be unlimited significant digits.
7366 POW_PRECISION = 0, // 0 to MAX
7367
7368 // The format specification used by the BigNumber.prototype.toFormat method.
7369 FORMAT = {
7370 decimalSeparator: '.',
7371 groupSeparator: ',',
7372 groupSize: 3,
7373 secondaryGroupSize: 0,
7374 fractionGroupSeparator: '\xA0', // non-breaking space
7375 fractionGroupSize: 0
7376 };
7377
7378
7379 /******************************************************************************************/
7380
7381
7382 // CONSTRUCTOR
7383
7384
7385 /*
7386 * The BigNumber constructor and exported function.
7387 * Create and return a new instance of a BigNumber object.
7388 *
7389 * n {number|string|BigNumber} A numeric value.
7390 * [b] {number} The base of n. Integer, 2 to 64 inclusive.
7391 */
7392 function BigNumber( n, b ) {
7393 var c, e, i, num, len, str,
7394 x = this;
7395
7396 // Enable constructor usage without new.
7397 if ( !( x instanceof BigNumber ) ) {
7398
7399 // 'BigNumber() constructor call without new: {n}'
7400 // See GitHub issue: #81.
7401 //if (ERRORS) raise( 26, 'constructor call without new', n );
7402 return new BigNumber( n, b );
7403 }
7404
7405 // 'new BigNumber() base not an integer: {b}'
7406 // 'new BigNumber() base out of range: {b}'
7407 if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) {
7408
7409 // Duplicate.
7410 if ( n instanceof BigNumber ) {
7411 x.s = n.s;
7412 x.e = n.e;
7413 x.c = ( n = n.c ) ? n.slice() : n;
7414 id = 0;
7415 return;
7416 }
7417
7418 if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) {
7419 x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1;
7420
7421 // Fast path for integers.
7422 if ( n === ~~n ) {
7423 for ( e = 0, i = n; i >= 10; i /= 10, e++ );
7424 x.e = e;
7425 x.c = [n];
7426 id = 0;
7427 return;
7428 }
7429
7430 str = n + '';
7431 } else {
7432 if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num );
7433 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
7434 }
7435 } else {
7436 b = b | 0;
7437 str = n + '';
7438
7439 // Ensure return value is rounded to DECIMAL_PLACES as with other bases.
7440 // Allow exponential notation to be used with base 10 argument.
7441 if ( b == 10 ) {
7442 x = new BigNumber( n instanceof BigNumber ? n : str );
7443 return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE );
7444 }
7445
7446 // Avoid potential interpretation of Infinity and NaN as base 44+ values.
7447 // Any number in exponential form will fail due to the [Ee][+-].
7448 if ( ( num = typeof n == 'number' ) && n * 0 != 0 ||
7449 !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) +
7450 '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) {
7451 return parseNumeric( x, str, num, b );
7452 }
7453
7454 if (num) {
7455 x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1;
7456
7457 if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) {
7458
7459 // 'new BigNumber() number type has more than 15 significant digits: {n}'
7460 raise( id, tooManyDigits, n );
7461 }
7462
7463 // Prevent later check for length on converted number.
7464 num = false;
7465 } else {
7466 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
7467 }
7468
7469 str = convertBase( str, 10, b, x.s );
7470 }
7471
7472 // Decimal point?
7473 if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' );
7474
7475 // Exponential form?
7476 if ( ( i = str.search( /e/i ) ) > 0 ) {
7477
7478 // Determine exponent.
7479 if ( e < 0 ) e = i;
7480 e += +str.slice( i + 1 );
7481 str = str.substring( 0, i );
7482 } else if ( e < 0 ) {
7483
7484 // Integer.
7485 e = str.length;
7486 }
7487
7488 // Determine leading zeros.
7489 for ( i = 0; str.charCodeAt(i) === 48; i++ );
7490
7491 // Determine trailing zeros.
7492 for ( len = str.length; str.charCodeAt(--len) === 48; );
7493 str = str.slice( i, len + 1 );
7494
7495 if (str) {
7496 len = str.length;
7497
7498 // Disallow numbers with over 15 significant digits if number type.
7499 // 'new BigNumber() number type has more than 15 significant digits: {n}'
7500 if ( num && ERRORS && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) {
7501 raise( id, tooManyDigits, x.s * n );
7502 }
7503
7504 e = e - i - 1;
7505
7506 // Overflow?
7507 if ( e > MAX_EXP ) {
7508
7509 // Infinity.
7510 x.c = x.e = null;
7511
7512 // Underflow?
7513 } else if ( e < MIN_EXP ) {
7514
7515 // Zero.
7516 x.c = [ x.e = 0 ];
7517 } else {
7518 x.e = e;
7519 x.c = [];
7520
7521 // Transform base
7522
7523 // e is the base 10 exponent.
7524 // i is where to slice str to get the first element of the coefficient array.
7525 i = ( e + 1 ) % LOG_BASE;
7526 if ( e < 0 ) i += LOG_BASE;
7527
7528 if ( i < len ) {
7529 if (i) x.c.push( +str.slice( 0, i ) );
7530
7531 for ( len -= LOG_BASE; i < len; ) {
7532 x.c.push( +str.slice( i, i += LOG_BASE ) );
7533 }
7534
7535 str = str.slice(i);
7536 i = LOG_BASE - str.length;
7537 } else {
7538 i -= len;
7539 }
7540
7541 for ( ; i--; str += '0' );
7542 x.c.push( +str );
7543 }
7544 } else {
7545
7546 // Zero.
7547 x.c = [ x.e = 0 ];
7548 }
7549
7550 id = 0;
7551 }
7552
7553
7554 // CONSTRUCTOR PROPERTIES
7555
7556
7557 BigNumber.another = constructorFactory;
7558
7559 BigNumber.ROUND_UP = 0;
7560 BigNumber.ROUND_DOWN = 1;
7561 BigNumber.ROUND_CEIL = 2;
7562 BigNumber.ROUND_FLOOR = 3;
7563 BigNumber.ROUND_HALF_UP = 4;
7564 BigNumber.ROUND_HALF_DOWN = 5;
7565 BigNumber.ROUND_HALF_EVEN = 6;
7566 BigNumber.ROUND_HALF_CEIL = 7;
7567 BigNumber.ROUND_HALF_FLOOR = 8;
7568 BigNumber.EUCLID = 9;
7569
7570
7571 /*
7572 * Configure infrequently-changing library-wide settings.
7573 *
7574 * Accept an object or an argument list, with one or many of the following properties or
7575 * parameters respectively:
7576 *
7577 * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive
7578 * ROUNDING_MODE {number} Integer, 0 to 8 inclusive
7579 * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or
7580 * [integer -MAX to 0 incl., 0 to MAX incl.]
7581 * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
7582 * [integer -MAX to -1 incl., integer 1 to MAX incl.]
7583 * ERRORS {boolean|number} true, false, 1 or 0
7584 * CRYPTO {boolean|number} true, false, 1 or 0
7585 * MODULO_MODE {number} 0 to 9 inclusive
7586 * POW_PRECISION {number} 0 to MAX inclusive
7587 * FORMAT {object} See BigNumber.prototype.toFormat
7588 * decimalSeparator {string}
7589 * groupSeparator {string}
7590 * groupSize {number}
7591 * secondaryGroupSize {number}
7592 * fractionGroupSeparator {string}
7593 * fractionGroupSize {number}
7594 *
7595 * (The values assigned to the above FORMAT object properties are not checked for validity.)
7596 *
7597 * E.g.
7598 * BigNumber.config(20, 4) is equivalent to
7599 * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
7600 *
7601 * Ignore properties/parameters set to null or undefined.
7602 * Return an object with the properties current values.
7603 */
7604 BigNumber.config = BigNumber.set = function () {
7605 var v, p,
7606 i = 0,
7607 r = {},
7608 a = arguments,
7609 o = a[0],
7610 has = o && typeof o == 'object'
7611 ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; }
7612 : function () { if ( a.length > i ) return ( v = a[i++] ) != null; };
7613
7614 // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
7615 // 'config() DECIMAL_PLACES not an integer: {v}'
7616 // 'config() DECIMAL_PLACES out of range: {v}'
7617 if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) {
7618 DECIMAL_PLACES = v | 0;
7619 }
7620 r[p] = DECIMAL_PLACES;
7621
7622 // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
7623 // 'config() ROUNDING_MODE not an integer: {v}'
7624 // 'config() ROUNDING_MODE out of range: {v}'
7625 if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) {
7626 ROUNDING_MODE = v | 0;
7627 }
7628 r[p] = ROUNDING_MODE;
7629
7630 // EXPONENTIAL_AT {number|number[]}
7631 // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive].
7632 // 'config() EXPONENTIAL_AT not an integer: {v}'
7633 // 'config() EXPONENTIAL_AT out of range: {v}'
7634 if ( has( p = 'EXPONENTIAL_AT' ) ) {
7635
7636 if ( isArray(v) ) {
7637 if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) {
7638 TO_EXP_NEG = v[0] | 0;
7639 TO_EXP_POS = v[1] | 0;
7640 }
7641 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
7642 TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 );
7643 }
7644 }
7645 r[p] = [ TO_EXP_NEG, TO_EXP_POS ];
7646
7647 // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
7648 // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
7649 // 'config() RANGE not an integer: {v}'
7650 // 'config() RANGE cannot be zero: {v}'
7651 // 'config() RANGE out of range: {v}'
7652 if ( has( p = 'RANGE' ) ) {
7653
7654 if ( isArray(v) ) {
7655 if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) {
7656 MIN_EXP = v[0] | 0;
7657 MAX_EXP = v[1] | 0;
7658 }
7659 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
7660 if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 );
7661 else if (ERRORS) raise( 2, p + ' cannot be zero', v );
7662 }
7663 }
7664 r[p] = [ MIN_EXP, MAX_EXP ];
7665
7666 // ERRORS {boolean|number} true, false, 1 or 0.
7667 // 'config() ERRORS not a boolean or binary digit: {v}'
7668 if ( has( p = 'ERRORS' ) ) {
7669
7670 if ( v === !!v || v === 1 || v === 0 ) {
7671 id = 0;
7672 isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors;
7673 } else if (ERRORS) {
7674 raise( 2, p + notBool, v );
7675 }
7676 }
7677 r[p] = ERRORS;
7678
7679 // CRYPTO {boolean|number} true, false, 1 or 0.
7680 // 'config() CRYPTO not a boolean or binary digit: {v}'
7681 // 'config() crypto unavailable: {crypto}'
7682 if ( has( p = 'CRYPTO' ) ) {
7683
7684 if ( v === true || v === false || v === 1 || v === 0 ) {
7685 if (v) {
7686 v = typeof crypto == 'undefined';
7687 if ( !v && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
7688 CRYPTO = true;
7689 } else if (ERRORS) {
7690 raise( 2, 'crypto unavailable', v ? void 0 : crypto );
7691 } else {
7692 CRYPTO = false;
7693 }
7694 } else {
7695 CRYPTO = false;
7696 }
7697 } else if (ERRORS) {
7698 raise( 2, p + notBool, v );
7699 }
7700 }
7701 r[p] = CRYPTO;
7702
7703 // MODULO_MODE {number} Integer, 0 to 9 inclusive.
7704 // 'config() MODULO_MODE not an integer: {v}'
7705 // 'config() MODULO_MODE out of range: {v}'
7706 if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) {
7707 MODULO_MODE = v | 0;
7708 }
7709 r[p] = MODULO_MODE;
7710
7711 // POW_PRECISION {number} Integer, 0 to MAX inclusive.
7712 // 'config() POW_PRECISION not an integer: {v}'
7713 // 'config() POW_PRECISION out of range: {v}'
7714 if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) {
7715 POW_PRECISION = v | 0;
7716 }
7717 r[p] = POW_PRECISION;
7718
7719 // FORMAT {object}
7720 // 'config() FORMAT not an object: {v}'
7721 if ( has( p = 'FORMAT' ) ) {
7722
7723 if ( typeof v == 'object' ) {
7724 FORMAT = v;
7725 } else if (ERRORS) {
7726 raise( 2, p + ' not an object', v );
7727 }
7728 }
7729 r[p] = FORMAT;
7730
7731 return r;
7732 };
7733
7734
7735 /*
7736 * Return a new BigNumber whose value is the maximum of the arguments.
7737 *
7738 * arguments {number|string|BigNumber}
7739 */
7740 BigNumber.max = function () { return maxOrMin( arguments, P.lt ); };
7741
7742
7743 /*
7744 * Return a new BigNumber whose value is the minimum of the arguments.
7745 *
7746 * arguments {number|string|BigNumber}
7747 */
7748 BigNumber.min = function () { return maxOrMin( arguments, P.gt ); };
7749
7750
7751 /*
7752 * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
7753 * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
7754 * zeros are produced).
7755 *
7756 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
7757 *
7758 * 'random() decimal places not an integer: {dp}'
7759 * 'random() decimal places out of range: {dp}'
7760 * 'random() crypto unavailable: {crypto}'
7761 */
7762 BigNumber.random = (function () {
7763 var pow2_53 = 0x20000000000000;
7764
7765 // Return a 53 bit integer n, where 0 <= n < 9007199254740992.
7766 // Check if Math.random() produces more than 32 bits of randomness.
7767 // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
7768 // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
7769 var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
7770 ? function () { return mathfloor( Math.random() * pow2_53 ); }
7771 : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
7772 (Math.random() * 0x800000 | 0); };
7773
7774 return function (dp) {
7775 var a, b, e, k, v,
7776 i = 0,
7777 c = [],
7778 rand = new BigNumber(ONE);
7779
7780 dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0;
7781 k = mathceil( dp / LOG_BASE );
7782
7783 if (CRYPTO) {
7784
7785 // Browsers supporting crypto.getRandomValues.
7786 if (crypto.getRandomValues) {
7787
7788 a = crypto.getRandomValues( new Uint32Array( k *= 2 ) );
7789
7790 for ( ; i < k; ) {
7791
7792 // 53 bits:
7793 // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
7794 // 11111 11111111 11111111 11111111 11100000 00000000 00000000
7795 // ((Math.pow(2, 32) - 1) >>> 11).toString(2)
7796 // 11111 11111111 11111111
7797 // 0x20000 is 2^21.
7798 v = a[i] * 0x20000 + (a[i + 1] >>> 11);
7799
7800 // Rejection sampling:
7801 // 0 <= v < 9007199254740992
7802 // Probability that v >= 9e15, is
7803 // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
7804 if ( v >= 9e15 ) {
7805 b = crypto.getRandomValues( new Uint32Array(2) );
7806 a[i] = b[0];
7807 a[i + 1] = b[1];
7808 } else {
7809
7810 // 0 <= v <= 8999999999999999
7811 // 0 <= (v % 1e14) <= 99999999999999
7812 c.push( v % 1e14 );
7813 i += 2;
7814 }
7815 }
7816 i = k / 2;
7817
7818 // Node.js supporting crypto.randomBytes.
7819 } else if (crypto.randomBytes) {
7820
7821 // buffer
7822 a = crypto.randomBytes( k *= 7 );
7823
7824 for ( ; i < k; ) {
7825
7826 // 0x1000000000000 is 2^48, 0x10000000000 is 2^40
7827 // 0x100000000 is 2^32, 0x1000000 is 2^24
7828 // 11111 11111111 11111111 11111111 11111111 11111111 11111111
7829 // 0 <= v < 9007199254740992
7830 v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) +
7831 ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) +
7832 ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6];
7833
7834 if ( v >= 9e15 ) {
7835 crypto.randomBytes(7).copy( a, i );
7836 } else {
7837
7838 // 0 <= (v % 1e14) <= 99999999999999
7839 c.push( v % 1e14 );
7840 i += 7;
7841 }
7842 }
7843 i = k / 7;
7844 } else {
7845 CRYPTO = false;
7846 if (ERRORS) raise( 14, 'crypto unavailable', crypto );
7847 }
7848 }
7849
7850 // Use Math.random.
7851 if (!CRYPTO) {
7852
7853 for ( ; i < k; ) {
7854 v = random53bitInt();
7855 if ( v < 9e15 ) c[i++] = v % 1e14;
7856 }
7857 }
7858
7859 k = c[--i];
7860 dp %= LOG_BASE;
7861
7862 // Convert trailing digits to zeros according to dp.
7863 if ( k && dp ) {
7864 v = POWS_TEN[LOG_BASE - dp];
7865 c[i] = mathfloor( k / v ) * v;
7866 }
7867
7868 // Remove trailing elements which are zero.
7869 for ( ; c[i] === 0; c.pop(), i-- );
7870
7871 // Zero?
7872 if ( i < 0 ) {
7873 c = [ e = 0 ];
7874 } else {
7875
7876 // Remove leading elements which are zero and adjust exponent accordingly.
7877 for ( e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);
7878
7879 // Count the digits of the first element of c to determine leading zeros, and...
7880 for ( i = 1, v = c[0]; v >= 10; v /= 10, i++);
7881
7882 // adjust the exponent accordingly.
7883 if ( i < LOG_BASE ) e -= LOG_BASE - i;
7884 }
7885
7886 rand.e = e;
7887 rand.c = c;
7888 return rand;
7889 };
7890 })();
7891
7892
7893 // PRIVATE FUNCTIONS
7894
7895
7896 // Convert a numeric string of baseIn to a numeric string of baseOut.
7897 function convertBase( str, baseOut, baseIn, sign ) {
7898 var d, e, k, r, x, xc, y,
7899 i = str.indexOf( '.' ),
7900 dp = DECIMAL_PLACES,
7901 rm = ROUNDING_MODE;
7902
7903 if ( baseIn < 37 ) str = str.toLowerCase();
7904
7905 // Non-integer.
7906 if ( i >= 0 ) {
7907 k = POW_PRECISION;
7908
7909 // Unlimited precision.
7910 POW_PRECISION = 0;
7911 str = str.replace( '.', '' );
7912 y = new BigNumber(baseIn);
7913 x = y.pow( str.length - i );
7914 POW_PRECISION = k;
7915
7916 // Convert str as if an integer, then restore the fraction part by dividing the
7917 // result by its base raised to a power.
7918 y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );
7919 y.e = y.c.length;
7920 }
7921
7922 // Convert the number as integer.
7923 xc = toBaseOut( str, baseIn, baseOut );
7924 e = k = xc.length;
7925
7926 // Remove trailing zeros.
7927 for ( ; xc[--k] == 0; xc.pop() );
7928 if ( !xc[0] ) return '0';
7929
7930 if ( i < 0 ) {
7931 --e;
7932 } else {
7933 x.c = xc;
7934 x.e = e;
7935
7936 // sign is needed for correct rounding.
7937 x.s = sign;
7938 x = div( x, y, dp, rm, baseOut );
7939 xc = x.c;
7940 r = x.r;
7941 e = x.e;
7942 }
7943
7944 d = e + dp + 1;
7945
7946 // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.
7947 i = xc[d];
7948 k = baseOut / 2;
7949 r = r || d < 0 || xc[d + 1] != null;
7950
7951 r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
7952 : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
7953 rm == ( x.s < 0 ? 8 : 7 ) );
7954
7955 if ( d < 1 || !xc[0] ) {
7956
7957 // 1^-dp or 0.
7958 str = r ? toFixedPoint( '1', -dp ) : '0';
7959 } else {
7960 xc.length = d;
7961
7962 if (r) {
7963
7964 // Rounding up may mean the previous digit has to be rounded up and so on.
7965 for ( --baseOut; ++xc[--d] > baseOut; ) {
7966 xc[d] = 0;
7967
7968 if ( !d ) {
7969 ++e;
7970 xc = [1].concat(xc);
7971 }
7972 }
7973 }
7974
7975 // Determine trailing zeros.
7976 for ( k = xc.length; !xc[--k]; );
7977
7978 // E.g. [4, 11, 15] becomes 4bf.
7979 for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );
7980 str = toFixedPoint( str, e );
7981 }
7982
7983 // The caller will add the sign.
7984 return str;
7985 }
7986
7987
7988 // Perform division in the specified base. Called by div and convertBase.
7989 div = (function () {
7990
7991 // Assume non-zero x and k.
7992 function multiply( x, k, base ) {
7993 var m, temp, xlo, xhi,
7994 carry = 0,
7995 i = x.length,
7996 klo = k % SQRT_BASE,
7997 khi = k / SQRT_BASE | 0;
7998
7999 for ( x = x.slice(); i--; ) {
8000 xlo = x[i] % SQRT_BASE;
8001 xhi = x[i] / SQRT_BASE | 0;
8002 m = khi * xlo + xhi * klo;
8003 temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;
8004 carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;
8005 x[i] = temp % base;
8006 }
8007
8008 if (carry) x = [carry].concat(x);
8009
8010 return x;
8011 }
8012
8013 function compare( a, b, aL, bL ) {
8014 var i, cmp;
8015
8016 if ( aL != bL ) {
8017 cmp = aL > bL ? 1 : -1;
8018 } else {
8019
8020 for ( i = cmp = 0; i < aL; i++ ) {
8021
8022 if ( a[i] != b[i] ) {
8023 cmp = a[i] > b[i] ? 1 : -1;
8024 break;
8025 }
8026 }
8027 }
8028 return cmp;
8029 }
8030
8031 function subtract( a, b, aL, base ) {
8032 var i = 0;
8033
8034 // Subtract b from a.
8035 for ( ; aL--; ) {
8036 a[aL] -= i;
8037 i = a[aL] < b[aL] ? 1 : 0;
8038 a[aL] = i * base + a[aL] - b[aL];
8039 }
8040
8041 // Remove leading zeros.
8042 for ( ; !a[0] && a.length > 1; a.splice(0, 1) );
8043 }
8044
8045 // x: dividend, y: divisor.
8046 return function ( x, y, dp, rm, base ) {
8047 var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
8048 yL, yz,
8049 s = x.s == y.s ? 1 : -1,
8050 xc = x.c,
8051 yc = y.c;
8052
8053 // Either NaN, Infinity or 0?
8054 if ( !xc || !xc[0] || !yc || !yc[0] ) {
8055
8056 return new BigNumber(
8057
8058 // Return NaN if either NaN, or both Infinity or 0.
8059 !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :
8060
8061 // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
8062 xc && xc[0] == 0 || !yc ? s * 0 : s / 0
8063 );
8064 }
8065
8066 q = new BigNumber(s);
8067 qc = q.c = [];
8068 e = x.e - y.e;
8069 s = dp + e + 1;
8070
8071 if ( !base ) {
8072 base = BASE;
8073 e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE );
8074 s = s / LOG_BASE | 0;
8075 }
8076
8077 // Result exponent may be one less then the current value of e.
8078 // The coefficients of the BigNumbers from convertBase may have trailing zeros.
8079 for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );
8080 if ( yc[i] > ( xc[i] || 0 ) ) e--;
8081
8082 if ( s < 0 ) {
8083 qc.push(1);
8084 more = true;
8085 } else {
8086 xL = xc.length;
8087 yL = yc.length;
8088 i = 0;
8089 s += 2;
8090
8091 // Normalise xc and yc so highest order digit of yc is >= base / 2.
8092
8093 n = mathfloor( base / ( yc[0] + 1 ) );
8094
8095 // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1.
8096 // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) {
8097 if ( n > 1 ) {
8098 yc = multiply( yc, n, base );
8099 xc = multiply( xc, n, base );
8100 yL = yc.length;
8101 xL = xc.length;
8102 }
8103
8104 xi = yL;
8105 rem = xc.slice( 0, yL );
8106 remL = rem.length;
8107
8108 // Add zeros to make remainder as long as divisor.
8109 for ( ; remL < yL; rem[remL++] = 0 );
8110 yz = yc.slice();
8111 yz = [0].concat(yz);
8112 yc0 = yc[0];
8113 if ( yc[1] >= base / 2 ) yc0++;
8114 // Not necessary, but to prevent trial digit n > base, when using base 3.
8115 // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15;
8116
8117 do {
8118 n = 0;
8119
8120 // Compare divisor and remainder.
8121 cmp = compare( yc, rem, yL, remL );
8122
8123 // If divisor < remainder.
8124 if ( cmp < 0 ) {
8125
8126 // Calculate trial digit, n.
8127
8128 rem0 = rem[0];
8129 if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 );
8130
8131 // n is how many times the divisor goes into the current remainder.
8132 n = mathfloor( rem0 / yc0 );
8133
8134 // Algorithm:
8135 // 1. product = divisor * trial digit (n)
8136 // 2. if product > remainder: product -= divisor, n--
8137 // 3. remainder -= product
8138 // 4. if product was < remainder at 2:
8139 // 5. compare new remainder and divisor
8140 // 6. If remainder > divisor: remainder -= divisor, n++
8141
8142 if ( n > 1 ) {
8143
8144 // n may be > base only when base is 3.
8145 if (n >= base) n = base - 1;
8146
8147 // product = divisor * trial digit.
8148 prod = multiply( yc, n, base );
8149 prodL = prod.length;
8150 remL = rem.length;
8151
8152 // Compare product and remainder.
8153 // If product > remainder.
8154 // Trial digit n too high.
8155 // n is 1 too high about 5% of the time, and is not known to have
8156 // ever been more than 1 too high.
8157 while ( compare( prod, rem, prodL, remL ) == 1 ) {
8158 n--;
8159
8160 // Subtract divisor from product.
8161 subtract( prod, yL < prodL ? yz : yc, prodL, base );
8162 prodL = prod.length;
8163 cmp = 1;
8164 }
8165 } else {
8166
8167 // n is 0 or 1, cmp is -1.
8168 // If n is 0, there is no need to compare yc and rem again below,
8169 // so change cmp to 1 to avoid it.
8170 // If n is 1, leave cmp as -1, so yc and rem are compared again.
8171 if ( n == 0 ) {
8172
8173 // divisor < remainder, so n must be at least 1.
8174 cmp = n = 1;
8175 }
8176
8177 // product = divisor
8178 prod = yc.slice();
8179 prodL = prod.length;
8180 }
8181
8182 if ( prodL < remL ) prod = [0].concat(prod);
8183
8184 // Subtract product from remainder.
8185 subtract( rem, prod, remL, base );
8186 remL = rem.length;
8187
8188 // If product was < remainder.
8189 if ( cmp == -1 ) {
8190
8191 // Compare divisor and new remainder.
8192 // If divisor < new remainder, subtract divisor from remainder.
8193 // Trial digit n too low.
8194 // n is 1 too low about 5% of the time, and very rarely 2 too low.
8195 while ( compare( yc, rem, yL, remL ) < 1 ) {
8196 n++;
8197
8198 // Subtract divisor from remainder.
8199 subtract( rem, yL < remL ? yz : yc, remL, base );
8200 remL = rem.length;
8201 }
8202 }
8203 } else if ( cmp === 0 ) {
8204 n++;
8205 rem = [0];
8206 } // else cmp === 1 and n will be 0
8207
8208 // Add the next digit, n, to the result array.
8209 qc[i++] = n;
8210
8211 // Update the remainder.
8212 if ( rem[0] ) {
8213 rem[remL++] = xc[xi] || 0;
8214 } else {
8215 rem = [ xc[xi] ];
8216 remL = 1;
8217 }
8218 } while ( ( xi++ < xL || rem[0] != null ) && s-- );
8219
8220 more = rem[0] != null;
8221
8222 // Leading zero?
8223 if ( !qc[0] ) qc.splice(0, 1);
8224 }
8225
8226 if ( base == BASE ) {
8227
8228 // To calculate q.e, first get the number of digits of qc[0].
8229 for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );
8230 round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more );
8231
8232 // Caller is convertBase.
8233 } else {
8234 q.e = e;
8235 q.r = +more;
8236 }
8237
8238 return q;
8239 };
8240 })();
8241
8242
8243 /*
8244 * Return a string representing the value of BigNumber n in fixed-point or exponential
8245 * notation rounded to the specified decimal places or significant digits.
8246 *
8247 * n is a BigNumber.
8248 * i is the index of the last digit required (i.e. the digit that may be rounded up).
8249 * rm is the rounding mode.
8250 * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24.
8251 */
8252 function format( n, i, rm, caller ) {
8253 var c0, e, ne, len, str;
8254
8255 rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode )
8256 ? rm | 0 : ROUNDING_MODE;
8257
8258 if ( !n.c ) return n.toString();
8259 c0 = n.c[0];
8260 ne = n.e;
8261
8262 if ( i == null ) {
8263 str = coeffToString( n.c );
8264 str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG
8265 ? toExponential( str, ne )
8266 : toFixedPoint( str, ne );
8267 } else {
8268 n = round( new BigNumber(n), i, rm );
8269
8270 // n.e may have changed if the value was rounded up.
8271 e = n.e;
8272
8273 str = coeffToString( n.c );
8274 len = str.length;
8275
8276 // toPrecision returns exponential notation if the number of significant digits
8277 // specified is less than the number of digits necessary to represent the integer
8278 // part of the value in fixed-point notation.
8279
8280 // Exponential notation.
8281 if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) {
8282
8283 // Append zeros?
8284 for ( ; len < i; str += '0', len++ );
8285 str = toExponential( str, e );
8286
8287 // Fixed-point notation.
8288 } else {
8289 i -= ne;
8290 str = toFixedPoint( str, e );
8291
8292 // Append zeros?
8293 if ( e + 1 > len ) {
8294 if ( --i > 0 ) for ( str += '.'; i--; str += '0' );
8295 } else {
8296 i += e - len;
8297 if ( i > 0 ) {
8298 if ( e + 1 == len ) str += '.';
8299 for ( ; i--; str += '0' );
8300 }
8301 }
8302 }
8303 }
8304
8305 return n.s < 0 && c0 ? '-' + str : str;
8306 }
8307
8308
8309 // Handle BigNumber.max and BigNumber.min.
8310 function maxOrMin( args, method ) {
8311 var m, n,
8312 i = 0;
8313
8314 if ( isArray( args[0] ) ) args = args[0];
8315 m = new BigNumber( args[0] );
8316
8317 for ( ; ++i < args.length; ) {
8318 n = new BigNumber( args[i] );
8319
8320 // If any number is NaN, return NaN.
8321 if ( !n.s ) {
8322 m = n;
8323 break;
8324 } else if ( method.call( m, n ) ) {
8325 m = n;
8326 }
8327 }
8328
8329 return m;
8330 }
8331
8332
8333 /*
8334 * Return true if n is an integer in range, otherwise throw.
8335 * Use for argument validation when ERRORS is true.
8336 */
8337 function intValidatorWithErrors( n, min, max, caller, name ) {
8338 if ( n < min || n > max || n != truncate(n) ) {
8339 raise( caller, ( name || 'decimal places' ) +
8340 ( n < min || n > max ? ' out of range' : ' not an integer' ), n );
8341 }
8342
8343 return true;
8344 }
8345
8346
8347 /*
8348 * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
8349 * Called by minus, plus and times.
8350 */
8351 function normalise( n, c, e ) {
8352 var i = 1,
8353 j = c.length;
8354
8355 // Remove trailing zeros.
8356 for ( ; !c[--j]; c.pop() );
8357
8358 // Calculate the base 10 exponent. First get the number of digits of c[0].
8359 for ( j = c[0]; j >= 10; j /= 10, i++ );
8360
8361 // Overflow?
8362 if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) {
8363
8364 // Infinity.
8365 n.c = n.e = null;
8366
8367 // Underflow?
8368 } else if ( e < MIN_EXP ) {
8369
8370 // Zero.
8371 n.c = [ n.e = 0 ];
8372 } else {
8373 n.e = e;
8374 n.c = c;
8375 }
8376
8377 return n;
8378 }
8379
8380
8381 // Handle values that fail the validity test in BigNumber.
8382 parseNumeric = (function () {
8383 var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,
8384 dotAfter = /^([^.]+)\.$/,
8385 dotBefore = /^\.([^.]+)$/,
8386 isInfinityOrNaN = /^-?(Infinity|NaN)$/,
8387 whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
8388
8389 return function ( x, str, num, b ) {
8390 var base,
8391 s = num ? str : str.replace( whitespaceOrPlus, '' );
8392
8393 // No exception on ±Infinity or NaN.
8394 if ( isInfinityOrNaN.test(s) ) {
8395 x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
8396 } else {
8397 if ( !num ) {
8398
8399 // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
8400 s = s.replace( basePrefix, function ( m, p1, p2 ) {
8401 base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
8402 return !b || b == base ? p1 : m;
8403 });
8404
8405 if (b) {
8406 base = b;
8407
8408 // E.g. '1.' to '1', '.1' to '0.1'
8409 s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' );
8410 }
8411
8412 if ( str != s ) return new BigNumber( s, base );
8413 }
8414
8415 // 'new BigNumber() not a number: {n}'
8416 // 'new BigNumber() not a base {b} number: {n}'
8417 if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str );
8418 x.s = null;
8419 }
8420
8421 x.c = x.e = null;
8422 id = 0;
8423 }
8424 })();
8425
8426
8427 // Throw a BigNumber Error.
8428 function raise( caller, msg, val ) {
8429 var error = new Error( [
8430 'new BigNumber', // 0
8431 'cmp', // 1
8432 'config', // 2
8433 'div', // 3
8434 'divToInt', // 4
8435 'eq', // 5
8436 'gt', // 6
8437 'gte', // 7
8438 'lt', // 8
8439 'lte', // 9
8440 'minus', // 10
8441 'mod', // 11
8442 'plus', // 12
8443 'precision', // 13
8444 'random', // 14
8445 'round', // 15
8446 'shift', // 16
8447 'times', // 17
8448 'toDigits', // 18
8449 'toExponential', // 19
8450 'toFixed', // 20
8451 'toFormat', // 21
8452 'toFraction', // 22
8453 'pow', // 23
8454 'toPrecision', // 24
8455 'toString', // 25
8456 'BigNumber' // 26
8457 ][caller] + '() ' + msg + ': ' + val );
8458
8459 error.name = 'BigNumber Error';
8460 id = 0;
8461 throw error;
8462 }
8463
8464
8465 /*
8466 * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
8467 * If r is truthy, it is known that there are more digits after the rounding digit.
8468 */
8469 function round( x, sd, rm, r ) {
8470 var d, i, j, k, n, ni, rd,
8471 xc = x.c,
8472 pows10 = POWS_TEN;
8473
8474 // if x is not Infinity or NaN...
8475 if (xc) {
8476
8477 // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
8478 // n is a base 1e14 number, the value of the element of array x.c containing rd.
8479 // ni is the index of n within x.c.
8480 // d is the number of digits of n.
8481 // i is the index of rd within n including leading zeros.
8482 // j is the actual index of rd within n (if < 0, rd is a leading zero).
8483 out: {
8484
8485 // Get the number of digits of the first element of xc.
8486 for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );
8487 i = sd - d;
8488
8489 // If the rounding digit is in the first element of xc...
8490 if ( i < 0 ) {
8491 i += LOG_BASE;
8492 j = sd;
8493 n = xc[ ni = 0 ];
8494
8495 // Get the rounding digit at index j of n.
8496 rd = n / pows10[ d - j - 1 ] % 10 | 0;
8497 } else {
8498 ni = mathceil( ( i + 1 ) / LOG_BASE );
8499
8500 if ( ni >= xc.length ) {
8501
8502 if (r) {
8503
8504 // Needed by sqrt.
8505 for ( ; xc.length <= ni; xc.push(0) );
8506 n = rd = 0;
8507 d = 1;
8508 i %= LOG_BASE;
8509 j = i - LOG_BASE + 1;
8510 } else {
8511 break out;
8512 }
8513 } else {
8514 n = k = xc[ni];
8515
8516 // Get the number of digits of n.
8517 for ( d = 1; k >= 10; k /= 10, d++ );
8518
8519 // Get the index of rd within n.
8520 i %= LOG_BASE;
8521
8522 // Get the index of rd within n, adjusted for leading zeros.
8523 // The number of leading zeros of n is given by LOG_BASE - d.
8524 j = i - LOG_BASE + d;
8525
8526 // Get the rounding digit at index j of n.
8527 rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;
8528 }
8529 }
8530
8531 r = r || sd < 0 ||
8532
8533 // Are there any non-zero digits after the rounding digit?
8534 // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right
8535 // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
8536 xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );
8537
8538 r = rm < 4
8539 ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
8540 : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&
8541
8542 // Check whether the digit to the left of the rounding digit is odd.
8543 ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||
8544 rm == ( x.s < 0 ? 8 : 7 ) );
8545
8546 if ( sd < 1 || !xc[0] ) {
8547 xc.length = 0;
8548
8549 if (r) {
8550
8551 // Convert sd to decimal places.
8552 sd -= x.e + 1;
8553
8554 // 1, 0.1, 0.01, 0.001, 0.0001 etc.
8555 xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ];
8556 x.e = -sd || 0;
8557 } else {
8558
8559 // Zero.
8560 xc[0] = x.e = 0;
8561 }
8562
8563 return x;
8564 }
8565
8566 // Remove excess digits.
8567 if ( i == 0 ) {
8568 xc.length = ni;
8569 k = 1;
8570 ni--;
8571 } else {
8572 xc.length = ni + 1;
8573 k = pows10[ LOG_BASE - i ];
8574
8575 // E.g. 56700 becomes 56000 if 7 is the rounding digit.
8576 // j > 0 means i > number of leading zeros of n.
8577 xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;
8578 }
8579
8580 // Round up?
8581 if (r) {
8582
8583 for ( ; ; ) {
8584
8585 // If the digit to be rounded up is in the first element of xc...
8586 if ( ni == 0 ) {
8587
8588 // i will be the length of xc[0] before k is added.
8589 for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );
8590 j = xc[0] += k;
8591 for ( k = 1; j >= 10; j /= 10, k++ );
8592
8593 // if i != k the length has increased.
8594 if ( i != k ) {
8595 x.e++;
8596 if ( xc[0] == BASE ) xc[0] = 1;
8597 }
8598
8599 break;
8600 } else {
8601 xc[ni] += k;
8602 if ( xc[ni] != BASE ) break;
8603 xc[ni--] = 0;
8604 k = 1;
8605 }
8606 }
8607 }
8608
8609 // Remove trailing zeros.
8610 for ( i = xc.length; xc[--i] === 0; xc.pop() );
8611 }
8612
8613 // Overflow? Infinity.
8614 if ( x.e > MAX_EXP ) {
8615 x.c = x.e = null;
8616
8617 // Underflow? Zero.
8618 } else if ( x.e < MIN_EXP ) {
8619 x.c = [ x.e = 0 ];
8620 }
8621 }
8622
8623 return x;
8624 }
8625
8626
8627 // PROTOTYPE/INSTANCE METHODS
8628
8629
8630 /*
8631 * Return a new BigNumber whose value is the absolute value of this BigNumber.
8632 */
8633 P.absoluteValue = P.abs = function () {
8634 var x = new BigNumber(this);
8635 if ( x.s < 0 ) x.s = 1;
8636 return x;
8637 };
8638
8639
8640 /*
8641 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
8642 * number in the direction of Infinity.
8643 */
8644 P.ceil = function () {
8645 return round( new BigNumber(this), this.e + 1, 2 );
8646 };
8647
8648
8649 /*
8650 * Return
8651 * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
8652 * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
8653 * 0 if they have the same value,
8654 * or null if the value of either is NaN.
8655 */
8656 P.comparedTo = P.cmp = function ( y, b ) {
8657 id = 1;
8658 return compare( this, new BigNumber( y, b ) );
8659 };
8660
8661
8662 /*
8663 * Return the number of decimal places of the value of this BigNumber, or null if the value
8664 * of this BigNumber is ±Infinity or NaN.
8665 */
8666 P.decimalPlaces = P.dp = function () {
8667 var n, v,
8668 c = this.c;
8669
8670 if ( !c ) return null;
8671 n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE;
8672
8673 // Subtract the number of trailing zeros of the last number.
8674 if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- );
8675 if ( n < 0 ) n = 0;
8676
8677 return n;
8678 };
8679
8680
8681 /*
8682 * n / 0 = I
8683 * n / N = N
8684 * n / I = 0
8685 * 0 / n = 0
8686 * 0 / 0 = N
8687 * 0 / N = N
8688 * 0 / I = 0
8689 * N / n = N
8690 * N / 0 = N
8691 * N / N = N
8692 * N / I = N
8693 * I / n = I
8694 * I / 0 = I
8695 * I / N = N
8696 * I / I = N
8697 *
8698 * Return a new BigNumber whose value is the value of this BigNumber divided by the value of
8699 * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
8700 */
8701 P.dividedBy = P.div = function ( y, b ) {
8702 id = 3;
8703 return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE );
8704 };
8705
8706
8707 /*
8708 * Return a new BigNumber whose value is the integer part of dividing the value of this
8709 * BigNumber by the value of BigNumber(y, b).
8710 */
8711 P.dividedToIntegerBy = P.divToInt = function ( y, b ) {
8712 id = 4;
8713 return div( this, new BigNumber( y, b ), 0, 1 );
8714 };
8715
8716
8717 /*
8718 * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
8719 * otherwise returns false.
8720 */
8721 P.equals = P.eq = function ( y, b ) {
8722 id = 5;
8723 return compare( this, new BigNumber( y, b ) ) === 0;
8724 };
8725
8726
8727 /*
8728 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
8729 * number in the direction of -Infinity.
8730 */
8731 P.floor = function () {
8732 return round( new BigNumber(this), this.e + 1, 3 );
8733 };
8734
8735
8736 /*
8737 * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
8738 * otherwise returns false.
8739 */
8740 P.greaterThan = P.gt = function ( y, b ) {
8741 id = 6;
8742 return compare( this, new BigNumber( y, b ) ) > 0;
8743 };
8744
8745
8746 /*
8747 * Return true if the value of this BigNumber is greater than or equal to the value of
8748 * BigNumber(y, b), otherwise returns false.
8749 */
8750 P.greaterThanOrEqualTo = P.gte = function ( y, b ) {
8751 id = 7;
8752 return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0;
8753
8754 };
8755
8756
8757 /*
8758 * Return true if the value of this BigNumber is a finite number, otherwise returns false.
8759 */
8760 P.isFinite = function () {
8761 return !!this.c;
8762 };
8763
8764
8765 /*
8766 * Return true if the value of this BigNumber is an integer, otherwise return false.
8767 */
8768 P.isInteger = P.isInt = function () {
8769 return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2;
8770 };
8771
8772
8773 /*
8774 * Return true if the value of this BigNumber is NaN, otherwise returns false.
8775 */
8776 P.isNaN = function () {
8777 return !this.s;
8778 };
8779
8780
8781 /*
8782 * Return true if the value of this BigNumber is negative, otherwise returns false.
8783 */
8784 P.isNegative = P.isNeg = function () {
8785 return this.s < 0;
8786 };
8787
8788
8789 /*
8790 * Return true if the value of this BigNumber is 0 or -0, otherwise returns false.
8791 */
8792 P.isZero = function () {
8793 return !!this.c && this.c[0] == 0;
8794 };
8795
8796
8797 /*
8798 * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
8799 * otherwise returns false.
8800 */
8801 P.lessThan = P.lt = function ( y, b ) {
8802 id = 8;
8803 return compare( this, new BigNumber( y, b ) ) < 0;
8804 };
8805
8806
8807 /*
8808 * Return true if the value of this BigNumber is less than or equal to the value of
8809 * BigNumber(y, b), otherwise returns false.
8810 */
8811 P.lessThanOrEqualTo = P.lte = function ( y, b ) {
8812 id = 9;
8813 return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0;
8814 };
8815
8816
8817 /*
8818 * n - 0 = n
8819 * n - N = N
8820 * n - I = -I
8821 * 0 - n = -n
8822 * 0 - 0 = 0
8823 * 0 - N = N
8824 * 0 - I = -I
8825 * N - n = N
8826 * N - 0 = N
8827 * N - N = N
8828 * N - I = N
8829 * I - n = I
8830 * I - 0 = I
8831 * I - N = N
8832 * I - I = N
8833 *
8834 * Return a new BigNumber whose value is the value of this BigNumber minus the value of
8835 * BigNumber(y, b).
8836 */
8837 P.minus = P.sub = function ( y, b ) {
8838 var i, j, t, xLTy,
8839 x = this,
8840 a = x.s;
8841
8842 id = 10;
8843 y = new BigNumber( y, b );
8844 b = y.s;
8845
8846 // Either NaN?
8847 if ( !a || !b ) return new BigNumber(NaN);
8848
8849 // Signs differ?
8850 if ( a != b ) {
8851 y.s = -b;
8852 return x.plus(y);
8853 }
8854
8855 var xe = x.e / LOG_BASE,
8856 ye = y.e / LOG_BASE,
8857 xc = x.c,
8858 yc = y.c;
8859
8860 if ( !xe || !ye ) {
8861
8862 // Either Infinity?
8863 if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN );
8864
8865 // Either zero?
8866 if ( !xc[0] || !yc[0] ) {
8867
8868 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
8869 return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x :
8870
8871 // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
8872 ROUNDING_MODE == 3 ? -0 : 0 );
8873 }
8874 }
8875
8876 xe = bitFloor(xe);
8877 ye = bitFloor(ye);
8878 xc = xc.slice();
8879
8880 // Determine which is the bigger number.
8881 if ( a = xe - ye ) {
8882
8883 if ( xLTy = a < 0 ) {
8884 a = -a;
8885 t = xc;
8886 } else {
8887 ye = xe;
8888 t = yc;
8889 }
8890
8891 t.reverse();
8892
8893 // Prepend zeros to equalise exponents.
8894 for ( b = a; b--; t.push(0) );
8895 t.reverse();
8896 } else {
8897
8898 // Exponents equal. Check digit by digit.
8899 j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b;
8900
8901 for ( a = b = 0; b < j; b++ ) {
8902
8903 if ( xc[b] != yc[b] ) {
8904 xLTy = xc[b] < yc[b];
8905 break;
8906 }
8907 }
8908 }
8909
8910 // x < y? Point xc to the array of the bigger number.
8911 if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
8912
8913 b = ( j = yc.length ) - ( i = xc.length );
8914
8915 // Append zeros to xc if shorter.
8916 // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
8917 if ( b > 0 ) for ( ; b--; xc[i++] = 0 );
8918 b = BASE - 1;
8919
8920 // Subtract yc from xc.
8921 for ( ; j > a; ) {
8922
8923 if ( xc[--j] < yc[j] ) {
8924 for ( i = j; i && !xc[--i]; xc[i] = b );
8925 --xc[i];
8926 xc[j] += BASE;
8927 }
8928
8929 xc[j] -= yc[j];
8930 }
8931
8932 // Remove leading zeros and adjust exponent accordingly.
8933 for ( ; xc[0] == 0; xc.splice(0, 1), --ye );
8934
8935 // Zero?
8936 if ( !xc[0] ) {
8937
8938 // Following IEEE 754 (2008) 6.3,
8939 // n - n = +0 but n - n = -0 when rounding towards -Infinity.
8940 y.s = ROUNDING_MODE == 3 ? -1 : 1;
8941 y.c = [ y.e = 0 ];
8942 return y;
8943 }
8944
8945 // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
8946 // for finite x and y.
8947 return normalise( y, xc, ye );
8948 };
8949
8950
8951 /*
8952 * n % 0 = N
8953 * n % N = N
8954 * n % I = n
8955 * 0 % n = 0
8956 * -0 % n = -0
8957 * 0 % 0 = N
8958 * 0 % N = N
8959 * 0 % I = 0
8960 * N % n = N
8961 * N % 0 = N
8962 * N % N = N
8963 * N % I = N
8964 * I % n = N
8965 * I % 0 = N
8966 * I % N = N
8967 * I % I = N
8968 *
8969 * Return a new BigNumber whose value is the value of this BigNumber modulo the value of
8970 * BigNumber(y, b). The result depends on the value of MODULO_MODE.
8971 */
8972 P.modulo = P.mod = function ( y, b ) {
8973 var q, s,
8974 x = this;
8975
8976 id = 11;
8977 y = new BigNumber( y, b );
8978
8979 // Return NaN if x is Infinity or NaN, or y is NaN or zero.
8980 if ( !x.c || !y.s || y.c && !y.c[0] ) {
8981 return new BigNumber(NaN);
8982
8983 // Return x if y is Infinity or x is zero.
8984 } else if ( !y.c || x.c && !x.c[0] ) {
8985 return new BigNumber(x);
8986 }
8987
8988 if ( MODULO_MODE == 9 ) {
8989
8990 // Euclidian division: q = sign(y) * floor(x / abs(y))
8991 // r = x - qy where 0 <= r < abs(y)
8992 s = y.s;
8993 y.s = 1;
8994 q = div( x, y, 0, 3 );
8995 y.s = s;
8996 q.s *= s;
8997 } else {
8998 q = div( x, y, 0, MODULO_MODE );
8999 }
9000
9001 return x.minus( q.times(y) );
9002 };
9003
9004
9005 /*
9006 * Return a new BigNumber whose value is the value of this BigNumber negated,
9007 * i.e. multiplied by -1.
9008 */
9009 P.negated = P.neg = function () {
9010 var x = new BigNumber(this);
9011 x.s = -x.s || null;
9012 return x;
9013 };
9014
9015
9016 /*
9017 * n + 0 = n
9018 * n + N = N
9019 * n + I = I
9020 * 0 + n = n
9021 * 0 + 0 = 0
9022 * 0 + N = N
9023 * 0 + I = I
9024 * N + n = N
9025 * N + 0 = N
9026 * N + N = N
9027 * N + I = N
9028 * I + n = I
9029 * I + 0 = I
9030 * I + N = N
9031 * I + I = I
9032 *
9033 * Return a new BigNumber whose value is the value of this BigNumber plus the value of
9034 * BigNumber(y, b).
9035 */
9036 P.plus = P.add = function ( y, b ) {
9037 var t,
9038 x = this,
9039 a = x.s;
9040
9041 id = 12;
9042 y = new BigNumber( y, b );
9043 b = y.s;
9044
9045 // Either NaN?
9046 if ( !a || !b ) return new BigNumber(NaN);
9047
9048 // Signs differ?
9049 if ( a != b ) {
9050 y.s = -b;
9051 return x.minus(y);
9052 }
9053
9054 var xe = x.e / LOG_BASE,
9055 ye = y.e / LOG_BASE,
9056 xc = x.c,
9057 yc = y.c;
9058
9059 if ( !xe || !ye ) {
9060
9061 // Return ±Infinity if either ±Infinity.
9062 if ( !xc || !yc ) return new BigNumber( a / 0 );
9063
9064 // Either zero?
9065 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
9066 if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 );
9067 }
9068
9069 xe = bitFloor(xe);
9070 ye = bitFloor(ye);
9071 xc = xc.slice();
9072
9073 // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
9074 if ( a = xe - ye ) {
9075 if ( a > 0 ) {
9076 ye = xe;
9077 t = yc;
9078 } else {
9079 a = -a;
9080 t = xc;
9081 }
9082
9083 t.reverse();
9084 for ( ; a--; t.push(0) );
9085 t.reverse();
9086 }
9087
9088 a = xc.length;
9089 b = yc.length;
9090
9091 // Point xc to the longer array, and b to the shorter length.
9092 if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a;
9093
9094 // Only start adding at yc.length - 1 as the further digits of xc can be ignored.
9095 for ( a = 0; b; ) {
9096 a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0;
9097 xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;
9098 }
9099
9100 if (a) {
9101 xc = [a].concat(xc);
9102 ++ye;
9103 }
9104
9105 // No need to check for zero, as +x + +y != 0 && -x + -y != 0
9106 // ye = MAX_EXP + 1 possible
9107 return normalise( y, xc, ye );
9108 };
9109
9110
9111 /*
9112 * Return the number of significant digits of the value of this BigNumber.
9113 *
9114 * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
9115 */
9116 P.precision = P.sd = function (z) {
9117 var n, v,
9118 x = this,
9119 c = x.c;
9120
9121 // 'precision() argument not a boolean or binary digit: {z}'
9122 if ( z != null && z !== !!z && z !== 1 && z !== 0 ) {
9123 if (ERRORS) raise( 13, 'argument' + notBool, z );
9124 if ( z != !!z ) z = null;
9125 }
9126
9127 if ( !c ) return null;
9128 v = c.length - 1;
9129 n = v * LOG_BASE + 1;
9130
9131 if ( v = c[v] ) {
9132
9133 // Subtract the number of trailing zeros of the last element.
9134 for ( ; v % 10 == 0; v /= 10, n-- );
9135
9136 // Add the number of digits of the first element.
9137 for ( v = c[0]; v >= 10; v /= 10, n++ );
9138 }
9139
9140 if ( z && x.e + 1 > n ) n = x.e + 1;
9141
9142 return n;
9143 };
9144
9145
9146 /*
9147 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
9148 * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if
9149 * omitted.
9150 *
9151 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
9152 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
9153 *
9154 * 'round() decimal places out of range: {dp}'
9155 * 'round() decimal places not an integer: {dp}'
9156 * 'round() rounding mode not an integer: {rm}'
9157 * 'round() rounding mode out of range: {rm}'
9158 */
9159 P.round = function ( dp, rm ) {
9160 var n = new BigNumber(this);
9161
9162 if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) {
9163 round( n, ~~dp + this.e + 1, rm == null ||
9164 !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 );
9165 }
9166
9167 return n;
9168 };
9169
9170
9171 /*
9172 * Return a new BigNumber whose value is the value of this BigNumber shifted by k places
9173 * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
9174 *
9175 * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
9176 *
9177 * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity
9178 * otherwise.
9179 *
9180 * 'shift() argument not an integer: {k}'
9181 * 'shift() argument out of range: {k}'
9182 */
9183 P.shift = function (k) {
9184 var n = this;
9185 return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' )
9186
9187 // k < 1e+21, or truncate(k) will produce exponential notation.
9188 ? n.times( '1e' + truncate(k) )
9189 : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER )
9190 ? n.s * ( k < 0 ? 0 : 1 / 0 )
9191 : n );
9192 };
9193
9194
9195 /*
9196 * sqrt(-n) = N
9197 * sqrt( N) = N
9198 * sqrt(-I) = N
9199 * sqrt( I) = I
9200 * sqrt( 0) = 0
9201 * sqrt(-0) = -0
9202 *
9203 * Return a new BigNumber whose value is the square root of the value of this BigNumber,
9204 * rounded according to DECIMAL_PLACES and ROUNDING_MODE.
9205 */
9206 P.squareRoot = P.sqrt = function () {
9207 var m, n, r, rep, t,
9208 x = this,
9209 c = x.c,
9210 s = x.s,
9211 e = x.e,
9212 dp = DECIMAL_PLACES + 4,
9213 half = new BigNumber('0.5');
9214
9215 // Negative/NaN/Infinity/zero?
9216 if ( s !== 1 || !c || !c[0] ) {
9217 return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );
9218 }
9219
9220 // Initial estimate.
9221 s = Math.sqrt( +x );
9222
9223 // Math.sqrt underflow/overflow?
9224 // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
9225 if ( s == 0 || s == 1 / 0 ) {
9226 n = coeffToString(c);
9227 if ( ( n.length + e ) % 2 == 0 ) n += '0';
9228 s = Math.sqrt(n);
9229 e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
9230
9231 if ( s == 1 / 0 ) {
9232 n = '1e' + e;
9233 } else {
9234 n = s.toExponential();
9235 n = n.slice( 0, n.indexOf('e') + 1 ) + e;
9236 }
9237
9238 r = new BigNumber(n);
9239 } else {
9240 r = new BigNumber( s + '' );
9241 }
9242
9243 // Check for zero.
9244 // r could be zero if MIN_EXP is changed after the this value was created.
9245 // This would cause a division by zero (x/t) and hence Infinity below, which would cause
9246 // coeffToString to throw.
9247 if ( r.c[0] ) {
9248 e = r.e;
9249 s = e + dp;
9250 if ( s < 3 ) s = 0;
9251
9252 // Newton-Raphson iteration.
9253 for ( ; ; ) {
9254 t = r;
9255 r = half.times( t.plus( div( x, t, dp, 1 ) ) );
9256
9257 if ( coeffToString( t.c ).slice( 0, s ) === ( n =
9258 coeffToString( r.c ) ).slice( 0, s ) ) {
9259
9260 // The exponent of r may here be one less than the final result exponent,
9261 // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
9262 // are indexed correctly.
9263 if ( r.e < e ) --s;
9264 n = n.slice( s - 3, s + 1 );
9265
9266 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits
9267 // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
9268 // iteration.
9269 if ( n == '9999' || !rep && n == '4999' ) {
9270
9271 // On the first iteration only, check to see if rounding up gives the
9272 // exact result as the nines may infinitely repeat.
9273 if ( !rep ) {
9274 round( t, t.e + DECIMAL_PLACES + 2, 0 );
9275
9276 if ( t.times(t).eq(x) ) {
9277 r = t;
9278 break;
9279 }
9280 }
9281
9282 dp += 4;
9283 s += 4;
9284 rep = 1;
9285 } else {
9286
9287 // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
9288 // result. If not, then there are further digits and m will be truthy.
9289 if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {
9290
9291 // Truncate to the first rounding digit.
9292 round( r, r.e + DECIMAL_PLACES + 2, 1 );
9293 m = !r.times(r).eq(x);
9294 }
9295
9296 break;
9297 }
9298 }
9299 }
9300 }
9301
9302 return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m );
9303 };
9304
9305
9306 /*
9307 * n * 0 = 0
9308 * n * N = N
9309 * n * I = I
9310 * 0 * n = 0
9311 * 0 * 0 = 0
9312 * 0 * N = N
9313 * 0 * I = N
9314 * N * n = N
9315 * N * 0 = N
9316 * N * N = N
9317 * N * I = N
9318 * I * n = I
9319 * I * 0 = N
9320 * I * N = N
9321 * I * I = I
9322 *
9323 * Return a new BigNumber whose value is the value of this BigNumber times the value of
9324 * BigNumber(y, b).
9325 */
9326 P.times = P.mul = function ( y, b ) {
9327 var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
9328 base, sqrtBase,
9329 x = this,
9330 xc = x.c,
9331 yc = ( id = 17, y = new BigNumber( y, b ) ).c;
9332
9333 // Either NaN, ±Infinity or ±0?
9334 if ( !xc || !yc || !xc[0] || !yc[0] ) {
9335
9336 // Return NaN if either is NaN, or one is 0 and the other is Infinity.
9337 if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) {
9338 y.c = y.e = y.s = null;
9339 } else {
9340 y.s *= x.s;
9341
9342 // Return ±Infinity if either is ±Infinity.
9343 if ( !xc || !yc ) {
9344 y.c = y.e = null;
9345
9346 // Return ±0 if either is ±0.
9347 } else {
9348 y.c = [0];
9349 y.e = 0;
9350 }
9351 }
9352
9353 return y;
9354 }
9355
9356 e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE );
9357 y.s *= x.s;
9358 xcL = xc.length;
9359 ycL = yc.length;
9360
9361 // Ensure xc points to longer array and xcL to its length.
9362 if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
9363
9364 // Initialise the result array with zeros.
9365 for ( i = xcL + ycL, zc = []; i--; zc.push(0) );
9366
9367 base = BASE;
9368 sqrtBase = SQRT_BASE;
9369
9370 for ( i = ycL; --i >= 0; ) {
9371 c = 0;
9372 ylo = yc[i] % sqrtBase;
9373 yhi = yc[i] / sqrtBase | 0;
9374
9375 for ( k = xcL, j = i + k; j > i; ) {
9376 xlo = xc[--k] % sqrtBase;
9377 xhi = xc[k] / sqrtBase | 0;
9378 m = yhi * xlo + xhi * ylo;
9379 xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c;
9380 c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi;
9381 zc[j--] = xlo % base;
9382 }
9383
9384 zc[j] = c;
9385 }
9386
9387 if (c) {
9388 ++e;
9389 } else {
9390 zc.splice(0, 1);
9391 }
9392
9393 return normalise( y, zc, e );
9394 };
9395
9396
9397 /*
9398 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
9399 * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted.
9400 *
9401 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
9402 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
9403 *
9404 * 'toDigits() precision out of range: {sd}'
9405 * 'toDigits() precision not an integer: {sd}'
9406 * 'toDigits() rounding mode not an integer: {rm}'
9407 * 'toDigits() rounding mode out of range: {rm}'
9408 */
9409 P.toDigits = function ( sd, rm ) {
9410 var n = new BigNumber(this);
9411 sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0;
9412 rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0;
9413 return sd ? round( n, sd, rm ) : n;
9414 };
9415
9416
9417 /*
9418 * Return a string representing the value of this BigNumber in exponential notation and
9419 * rounded using ROUNDING_MODE to dp fixed decimal places.
9420 *
9421 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
9422 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
9423 *
9424 * 'toExponential() decimal places not an integer: {dp}'
9425 * 'toExponential() decimal places out of range: {dp}'
9426 * 'toExponential() rounding mode not an integer: {rm}'
9427 * 'toExponential() rounding mode out of range: {rm}'
9428 */
9429 P.toExponential = function ( dp, rm ) {
9430 return format( this,
9431 dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 );
9432 };
9433
9434
9435 /*
9436 * Return a string representing the value of this BigNumber in fixed-point notation rounding
9437 * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
9438 *
9439 * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
9440 * but e.g. (-0.00001).toFixed(0) is '-0'.
9441 *
9442 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
9443 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
9444 *
9445 * 'toFixed() decimal places not an integer: {dp}'
9446 * 'toFixed() decimal places out of range: {dp}'
9447 * 'toFixed() rounding mode not an integer: {rm}'
9448 * 'toFixed() rounding mode out of range: {rm}'
9449 */
9450 P.toFixed = function ( dp, rm ) {
9451 return format( this, dp != null && isValidInt( dp, 0, MAX, 20 )
9452 ? ~~dp + this.e + 1 : null, rm, 20 );
9453 };
9454
9455
9456 /*
9457 * Return a string representing the value of this BigNumber in fixed-point notation rounded
9458 * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
9459 * of the FORMAT object (see BigNumber.config).
9460 *
9461 * FORMAT = {
9462 * decimalSeparator : '.',
9463 * groupSeparator : ',',
9464 * groupSize : 3,
9465 * secondaryGroupSize : 0,
9466 * fractionGroupSeparator : '\xA0', // non-breaking space
9467 * fractionGroupSize : 0
9468 * };
9469 *
9470 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
9471 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
9472 *
9473 * 'toFormat() decimal places not an integer: {dp}'
9474 * 'toFormat() decimal places out of range: {dp}'
9475 * 'toFormat() rounding mode not an integer: {rm}'
9476 * 'toFormat() rounding mode out of range: {rm}'
9477 */
9478 P.toFormat = function ( dp, rm ) {
9479 var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 )
9480 ? ~~dp + this.e + 1 : null, rm, 21 );
9481
9482 if ( this.c ) {
9483 var i,
9484 arr = str.split('.'),
9485 g1 = +FORMAT.groupSize,
9486 g2 = +FORMAT.secondaryGroupSize,
9487 groupSeparator = FORMAT.groupSeparator,
9488 intPart = arr[0],
9489 fractionPart = arr[1],
9490 isNeg = this.s < 0,
9491 intDigits = isNeg ? intPart.slice(1) : intPart,
9492 len = intDigits.length;
9493
9494 if (g2) i = g1, g1 = g2, g2 = i, len -= i;
9495
9496 if ( g1 > 0 && len > 0 ) {
9497 i = len % g1 || g1;
9498 intPart = intDigits.substr( 0, i );
9499
9500 for ( ; i < len; i += g1 ) {
9501 intPart += groupSeparator + intDigits.substr( i, g1 );
9502 }
9503
9504 if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i);
9505 if (isNeg) intPart = '-' + intPart;
9506 }
9507
9508 str = fractionPart
9509 ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize )
9510 ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ),
9511 '$&' + FORMAT.fractionGroupSeparator )
9512 : fractionPart )
9513 : intPart;
9514 }
9515
9516 return str;
9517 };
9518
9519
9520 /*
9521 * Return a string array representing the value of this BigNumber as a simple fraction with
9522 * an integer numerator and an integer denominator. The denominator will be a positive
9523 * non-zero value less than or equal to the specified maximum denominator. If a maximum
9524 * denominator is not specified, the denominator will be the lowest value necessary to
9525 * represent the number exactly.
9526 *
9527 * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.
9528 *
9529 * 'toFraction() max denominator not an integer: {md}'
9530 * 'toFraction() max denominator out of range: {md}'
9531 */
9532 P.toFraction = function (md) {
9533 var arr, d0, d2, e, exp, n, n0, q, s,
9534 k = ERRORS,
9535 x = this,
9536 xc = x.c,
9537 d = new BigNumber(ONE),
9538 n1 = d0 = new BigNumber(ONE),
9539 d1 = n0 = new BigNumber(ONE);
9540
9541 if ( md != null ) {
9542 ERRORS = false;
9543 n = new BigNumber(md);
9544 ERRORS = k;
9545
9546 if ( !( k = n.isInt() ) || n.lt(ONE) ) {
9547
9548 if (ERRORS) {
9549 raise( 22,
9550 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
9551 }
9552
9553 // ERRORS is false:
9554 // If md is a finite non-integer >= 1, round it to an integer and use it.
9555 md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null;
9556 }
9557 }
9558
9559 if ( !xc ) return x.toString();
9560 s = coeffToString(xc);
9561
9562 // Determine initial denominator.
9563 // d is a power of 10 and the minimum max denominator that specifies the value exactly.
9564 e = d.e = s.length - x.e - 1;
9565 d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];
9566 md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n;
9567
9568 exp = MAX_EXP;
9569 MAX_EXP = 1 / 0;
9570 n = new BigNumber(s);
9571
9572 // n0 = d1 = 0
9573 n0.c[0] = 0;
9574
9575 for ( ; ; ) {
9576 q = div( n, d, 0, 1 );
9577 d2 = d0.plus( q.times(d1) );
9578 if ( d2.cmp(md) == 1 ) break;
9579 d0 = d1;
9580 d1 = d2;
9581 n1 = n0.plus( q.times( d2 = n1 ) );
9582 n0 = d2;
9583 d = n.minus( q.times( d2 = d ) );
9584 n = d2;
9585 }
9586
9587 d2 = div( md.minus(d0), d1, 0, 1 );
9588 n0 = n0.plus( d2.times(n1) );
9589 d0 = d0.plus( d2.times(d1) );
9590 n0.s = n1.s = x.s;
9591 e *= 2;
9592
9593 // Determine which fraction is closer to x, n0/d0 or n1/d1
9594 arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp(
9595 div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1
9596 ? [ n1.toString(), d1.toString() ]
9597 : [ n0.toString(), d0.toString() ];
9598
9599 MAX_EXP = exp;
9600 return arr;
9601 };
9602
9603
9604 /*
9605 * Return the value of this BigNumber converted to a number primitive.
9606 */
9607 P.toNumber = function () {
9608 return +this;
9609 };
9610
9611
9612 /*
9613 * Return a BigNumber whose value is the value of this BigNumber raised to the power n.
9614 * If m is present, return the result modulo m.
9615 * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
9616 * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using
9617 * ROUNDING_MODE.
9618 *
9619 * The modular power operation works efficiently when x, n, and m are positive integers,
9620 * otherwise it is equivalent to calculating x.toPower(n).modulo(m) (with POW_PRECISION 0).
9621 *
9622 * n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
9623 * [m] {number|string|BigNumber} The modulus.
9624 *
9625 * 'pow() exponent not an integer: {n}'
9626 * 'pow() exponent out of range: {n}'
9627 *
9628 * Performs 54 loop iterations for n of 9007199254740991.
9629 */
9630 P.toPower = P.pow = function ( n, m ) {
9631 var k, y, z,
9632 i = mathfloor( n < 0 ? -n : +n ),
9633 x = this;
9634
9635 if ( m != null ) {
9636 id = 23;
9637 m = new BigNumber(m);
9638 }
9639
9640 // Pass ±Infinity to Math.pow if exponent is out of range.
9641 if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) &&
9642 ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) ||
9643 parseFloat(n) != n && !( n = NaN ) ) || n == 0 ) {
9644 k = Math.pow( +x, n );
9645 return new BigNumber( m ? k % m : k );
9646 }
9647
9648 if (m) {
9649 if ( n > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt() ) {
9650 x = x.mod(m);
9651 } else {
9652 z = m;
9653
9654 // Nullify m so only a single mod operation is performed at the end.
9655 m = null;
9656 }
9657 } else if (POW_PRECISION) {
9658
9659 // Truncating each coefficient array to a length of k after each multiplication
9660 // equates to truncating significant digits to POW_PRECISION + [28, 41],
9661 // i.e. there will be a minimum of 28 guard digits retained.
9662 // (Using + 1.5 would give [9, 21] guard digits.)
9663 k = mathceil( POW_PRECISION / LOG_BASE + 2 );
9664 }
9665
9666 y = new BigNumber(ONE);
9667
9668 for ( ; ; ) {
9669 if ( i % 2 ) {
9670 y = y.times(x);
9671 if ( !y.c ) break;
9672 if (k) {
9673 if ( y.c.length > k ) y.c.length = k;
9674 } else if (m) {
9675 y = y.mod(m);
9676 }
9677 }
9678
9679 i = mathfloor( i / 2 );
9680 if ( !i ) break;
9681 x = x.times(x);
9682 if (k) {
9683 if ( x.c && x.c.length > k ) x.c.length = k;
9684 } else if (m) {
9685 x = x.mod(m);
9686 }
9687 }
9688
9689 if (m) return y;
9690 if ( n < 0 ) y = ONE.div(y);
9691
9692 return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;
9693 };
9694
9695
9696 /*
9697 * Return a string representing the value of this BigNumber rounded to sd significant digits
9698 * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
9699 * necessary to represent the integer part of the value in fixed-point notation, then use
9700 * exponential notation.
9701 *
9702 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
9703 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
9704 *
9705 * 'toPrecision() precision not an integer: {sd}'
9706 * 'toPrecision() precision out of range: {sd}'
9707 * 'toPrecision() rounding mode not an integer: {rm}'
9708 * 'toPrecision() rounding mode out of range: {rm}'
9709 */
9710 P.toPrecision = function ( sd, rm ) {
9711 return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' )
9712 ? sd | 0 : null, rm, 24 );
9713 };
9714
9715
9716 /*
9717 * Return a string representing the value of this BigNumber in base b, or base 10 if b is
9718 * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
9719 * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
9720 * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
9721 * TO_EXP_NEG, return exponential notation.
9722 *
9723 * [b] {number} Integer, 2 to 64 inclusive.
9724 *
9725 * 'toString() base not an integer: {b}'
9726 * 'toString() base out of range: {b}'
9727 */
9728 P.toString = function (b) {
9729 var str,
9730 n = this,
9731 s = n.s,
9732 e = n.e;
9733
9734 // Infinity or NaN?
9735 if ( e === null ) {
9736
9737 if (s) {
9738 str = 'Infinity';
9739 if ( s < 0 ) str = '-' + str;
9740 } else {
9741 str = 'NaN';
9742 }
9743 } else {
9744 str = coeffToString( n.c );
9745
9746 if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) {
9747 str = e <= TO_EXP_NEG || e >= TO_EXP_POS
9748 ? toExponential( str, e )
9749 : toFixedPoint( str, e );
9750 } else {
9751 str = convertBase( toFixedPoint( str, e ), b | 0, 10, s );
9752 }
9753
9754 if ( s < 0 && n.c[0] ) str = '-' + str;
9755 }
9756
9757 return str;
9758 };
9759
9760
9761 /*
9762 * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole
9763 * number.
9764 */
9765 P.truncated = P.trunc = function () {
9766 return round( new BigNumber(this), this.e + 1, 1 );
9767 };
9768
9769
9770 /*
9771 * Return as toString, but do not accept a base argument, and include the minus sign for
9772 * negative zero.
9773 */
9774 P.valueOf = P.toJSON = function () {
9775 var str,
9776 n = this,
9777 e = n.e;
9778
9779 if ( e === null ) return n.toString();
9780
9781 str = coeffToString( n.c );
9782
9783 str = e <= TO_EXP_NEG || e >= TO_EXP_POS
9784 ? toExponential( str, e )
9785 : toFixedPoint( str, e );
9786
9787 return n.s < 0 ? '-' + str : str;
9788 };
9789
9790
9791 P.isBigNumber = true;
9792
9793 if ( config != null ) BigNumber.config(config);
9794
9795 return BigNumber;
9796 }
9797
9798
9799 // PRIVATE HELPER FUNCTIONS
9800
9801
9802 function bitFloor(n) {
9803 var i = n | 0;
9804 return n > 0 || n === i ? i : i - 1;
9805 }
9806
9807
9808 // Return a coefficient array as a string of base 10 digits.
9809 function coeffToString(a) {
9810 var s, z,
9811 i = 1,
9812 j = a.length,
9813 r = a[0] + '';
9814
9815 for ( ; i < j; ) {
9816 s = a[i++] + '';
9817 z = LOG_BASE - s.length;
9818 for ( ; z--; s = '0' + s );
9819 r += s;
9820 }
9821
9822 // Determine trailing zeros.
9823 for ( j = r.length; r.charCodeAt(--j) === 48; );
9824 return r.slice( 0, j + 1 || 1 );
9825 }
9826
9827
9828 // Compare the value of BigNumbers x and y.
9829 function compare( x, y ) {
9830 var a, b,
9831 xc = x.c,
9832 yc = y.c,
9833 i = x.s,
9834 j = y.s,
9835 k = x.e,
9836 l = y.e;
9837
9838 // Either NaN?
9839 if ( !i || !j ) return null;
9840
9841 a = xc && !xc[0];
9842 b = yc && !yc[0];
9843
9844 // Either zero?
9845 if ( a || b ) return a ? b ? 0 : -j : i;
9846
9847 // Signs differ?
9848 if ( i != j ) return i;
9849
9850 a = i < 0;
9851 b = k == l;
9852
9853 // Either Infinity?
9854 if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1;
9855
9856 // Compare exponents.
9857 if ( !b ) return k > l ^ a ? 1 : -1;
9858
9859 j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
9860
9861 // Compare digit by digit.
9862 for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1;
9863
9864 // Compare lengths.
9865 return k == l ? 0 : k > l ^ a ? 1 : -1;
9866 }
9867
9868
9869 /*
9870 * Return true if n is a valid number in range, otherwise false.
9871 * Use for argument validation when ERRORS is false.
9872 * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10.
9873 */
9874 function intValidatorNoErrors( n, min, max ) {
9875 return ( n = truncate(n) ) >= min && n <= max;
9876 }
9877
9878
9879 function isArray(obj) {
9880 return Object.prototype.toString.call(obj) == '[object Array]';
9881 }
9882
9883
9884 /*
9885 * Convert string of baseIn to an array of numbers of baseOut.
9886 * Eg. convertBase('255', 10, 16) returns [15, 15].
9887 * Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
9888 */
9889 function toBaseOut( str, baseIn, baseOut ) {
9890 var j,
9891 arr = [0],
9892 arrL,
9893 i = 0,
9894 len = str.length;
9895
9896 for ( ; i < len; ) {
9897 for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );
9898 arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) );
9899
9900 for ( ; j < arr.length; j++ ) {
9901
9902 if ( arr[j] > baseOut - 1 ) {
9903 if ( arr[j + 1] == null ) arr[j + 1] = 0;
9904 arr[j + 1] += arr[j] / baseOut | 0;
9905 arr[j] %= baseOut;
9906 }
9907 }
9908 }
9909
9910 return arr.reverse();
9911 }
9912
9913
9914 function toExponential( str, e ) {
9915 return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) +
9916 ( e < 0 ? 'e' : 'e+' ) + e;
9917 }
9918
9919
9920 function toFixedPoint( str, e ) {
9921 var len, z;
9922
9923 // Negative exponent?
9924 if ( e < 0 ) {
9925
9926 // Prepend zeros.
9927 for ( z = '0.'; ++e; z += '0' );
9928 str = z + str;
9929
9930 // Positive exponent
9931 } else {
9932 len = str.length;
9933
9934 // Append zeros.
9935 if ( ++e > len ) {
9936 for ( z = '0', e -= len; --e; z += '0' );
9937 str += z;
9938 } else if ( e < len ) {
9939 str = str.slice( 0, e ) + '.' + str.slice(e);
9940 }
9941 }
9942
9943 return str;
9944 }
9945
9946
9947 function truncate(n) {
9948 n = parseFloat(n);
9949 return n < 0 ? mathceil(n) : mathfloor(n);
9950 }
9951
9952
9953 // EXPORT
9954
9955
9956 BigNumber = constructorFactory();
9957 BigNumber['default'] = BigNumber.BigNumber = BigNumber;
9958
9959
9960 // AMD.
9961 if ( typeof define == 'function' && define.amd ) {
9962 define( function () { return BigNumber; } );
9963
9964 // Node.js and other environments that support module.exports.
9965 } else if ( typeof module != 'undefined' && module.exports ) {
9966 module.exports = BigNumber;
9967
9968 // Browser.
9969 } else {
9970 if ( !globalObj ) globalObj = typeof self != 'undefined' ? self : Function('return this')();
9971 globalObj.BigNumber = BigNumber;
9972 }
9973})(this);
9974
9975},{}],74:[function(require,module,exports){
9976// Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki 5008// Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki
9977// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] 5009// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
9978// NOTE: SIGHASH byte ignored AND restricted, truncate before use 5010// NOTE: SIGHASH byte ignored AND restricted, truncate before use
@@ -10087,7 +5119,7 @@ module.exports = {
10087 encode: encode 5119 encode: encode
10088} 5120}
10089 5121
10090},{"safe-buffer":247}],75:[function(require,module,exports){ 5122},{"safe-buffer":156}],21:[function(require,module,exports){
10091(function (module, exports) { 5123(function (module, exports) {
10092 'use strict'; 5124 'use strict';
10093 5125
@@ -13516,7 +8548,7 @@ module.exports = {
13516 }; 8548 };
13517})(typeof module === 'undefined' || module, this); 8549})(typeof module === 'undefined' || module, this);
13518 8550
13519},{"buffer":77}],76:[function(require,module,exports){ 8551},{"buffer":23}],22:[function(require,module,exports){
13520var r; 8552var r;
13521 8553
13522module.exports = function rand(len) { 8554module.exports = function rand(len) {
@@ -13583,9 +8615,9 @@ if (typeof self === 'object') {
13583 } 8615 }
13584} 8616}
13585 8617
13586},{"crypto":77}],77:[function(require,module,exports){ 8618},{"crypto":23}],23:[function(require,module,exports){
13587 8619
13588},{}],78:[function(require,module,exports){ 8620},{}],24:[function(require,module,exports){
13589// based on the aes implimentation in triple sec 8621// based on the aes implimentation in triple sec
13590// https://github.com/keybase/triplesec 8622// https://github.com/keybase/triplesec
13591// which is in turn based on the one from crypto-js 8623// which is in turn based on the one from crypto-js
@@ -13815,7 +8847,7 @@ AES.prototype.scrub = function () {
13815 8847
13816module.exports.AES = AES 8848module.exports.AES = AES
13817 8849
13818},{"safe-buffer":247}],79:[function(require,module,exports){ 8850},{"safe-buffer":156}],25:[function(require,module,exports){
13819var aes = require('./aes') 8851var aes = require('./aes')
13820var Buffer = require('safe-buffer').Buffer 8852var Buffer = require('safe-buffer').Buffer
13821var Transform = require('cipher-base') 8853var Transform = require('cipher-base')
@@ -13934,7 +8966,7 @@ StreamCipher.prototype.setAAD = function setAAD (buf) {
13934 8966
13935module.exports = StreamCipher 8967module.exports = StreamCipher
13936 8968
13937},{"./aes":78,"./ghash":83,"./incr32":84,"buffer-xor":106,"cipher-base":108,"inherits":163,"safe-buffer":247}],80:[function(require,module,exports){ 8969},{"./aes":24,"./ghash":29,"./incr32":30,"buffer-xor":52,"cipher-base":54,"inherits":107,"safe-buffer":156}],26:[function(require,module,exports){
13938var ciphers = require('./encrypter') 8970var ciphers = require('./encrypter')
13939var deciphers = require('./decrypter') 8971var deciphers = require('./decrypter')
13940var modes = require('./modes/list.json') 8972var modes = require('./modes/list.json')
@@ -13949,7 +8981,7 @@ exports.createDecipher = exports.Decipher = deciphers.createDecipher
13949exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv 8981exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
13950exports.listCiphers = exports.getCiphers = getCiphers 8982exports.listCiphers = exports.getCiphers = getCiphers
13951 8983
13952},{"./decrypter":81,"./encrypter":82,"./modes/list.json":92}],81:[function(require,module,exports){ 8984},{"./decrypter":27,"./encrypter":28,"./modes/list.json":38}],27:[function(require,module,exports){
13953var AuthCipher = require('./authCipher') 8985var AuthCipher = require('./authCipher')
13954var Buffer = require('safe-buffer').Buffer 8986var Buffer = require('safe-buffer').Buffer
13955var MODES = require('./modes') 8987var MODES = require('./modes')
@@ -14072,7 +9104,7 @@ function createDecipher (suite, password) {
14072exports.createDecipher = createDecipher 9104exports.createDecipher = createDecipher
14073exports.createDecipheriv = createDecipheriv 9105exports.createDecipheriv = createDecipheriv
14074 9106
14075},{"./aes":78,"./authCipher":79,"./modes":91,"./streamCipher":94,"cipher-base":108,"evp_bytestokey":144,"inherits":163,"safe-buffer":247}],82:[function(require,module,exports){ 9107},{"./aes":24,"./authCipher":25,"./modes":37,"./streamCipher":40,"cipher-base":54,"evp_bytestokey":90,"inherits":107,"safe-buffer":156}],28:[function(require,module,exports){
14076var MODES = require('./modes') 9108var MODES = require('./modes')
14077var AuthCipher = require('./authCipher') 9109var AuthCipher = require('./authCipher')
14078var Buffer = require('safe-buffer').Buffer 9110var Buffer = require('safe-buffer').Buffer
@@ -14188,7 +9220,7 @@ function createCipher (suite, password) {
14188exports.createCipheriv = createCipheriv 9220exports.createCipheriv = createCipheriv
14189exports.createCipher = createCipher 9221exports.createCipher = createCipher
14190 9222
14191},{"./aes":78,"./authCipher":79,"./modes":91,"./streamCipher":94,"cipher-base":108,"evp_bytestokey":144,"inherits":163,"safe-buffer":247}],83:[function(require,module,exports){ 9223},{"./aes":24,"./authCipher":25,"./modes":37,"./streamCipher":40,"cipher-base":54,"evp_bytestokey":90,"inherits":107,"safe-buffer":156}],29:[function(require,module,exports){
14192var Buffer = require('safe-buffer').Buffer 9224var Buffer = require('safe-buffer').Buffer
14193var ZEROES = Buffer.alloc(16, 0) 9225var ZEROES = Buffer.alloc(16, 0)
14194 9226
@@ -14279,7 +9311,7 @@ GHASH.prototype.final = function (abl, bl) {
14279 9311
14280module.exports = GHASH 9312module.exports = GHASH
14281 9313
14282},{"safe-buffer":247}],84:[function(require,module,exports){ 9314},{"safe-buffer":156}],30:[function(require,module,exports){
14283function incr32 (iv) { 9315function incr32 (iv) {
14284 var len = iv.length 9316 var len = iv.length
14285 var item 9317 var item
@@ -14296,7 +9328,7 @@ function incr32 (iv) {
14296} 9328}
14297module.exports = incr32 9329module.exports = incr32
14298 9330
14299},{}],85:[function(require,module,exports){ 9331},{}],31:[function(require,module,exports){
14300var xor = require('buffer-xor') 9332var xor = require('buffer-xor')
14301 9333
14302exports.encrypt = function (self, block) { 9334exports.encrypt = function (self, block) {
@@ -14315,7 +9347,7 @@ exports.decrypt = function (self, block) {
14315 return xor(out, pad) 9347 return xor(out, pad)
14316} 9348}
14317 9349
14318},{"buffer-xor":106}],86:[function(require,module,exports){ 9350},{"buffer-xor":52}],32:[function(require,module,exports){
14319var Buffer = require('safe-buffer').Buffer 9351var Buffer = require('safe-buffer').Buffer
14320var xor = require('buffer-xor') 9352var xor = require('buffer-xor')
14321 9353
@@ -14350,7 +9382,7 @@ exports.encrypt = function (self, data, decrypt) {
14350 return out 9382 return out
14351} 9383}
14352 9384
14353},{"buffer-xor":106,"safe-buffer":247}],87:[function(require,module,exports){ 9385},{"buffer-xor":52,"safe-buffer":156}],33:[function(require,module,exports){
14354var Buffer = require('safe-buffer').Buffer 9386var Buffer = require('safe-buffer').Buffer
14355 9387
14356function encryptByte (self, byteParam, decrypt) { 9388function encryptByte (self, byteParam, decrypt) {
@@ -14394,7 +9426,7 @@ exports.encrypt = function (self, chunk, decrypt) {
14394 return out 9426 return out
14395} 9427}
14396 9428
14397},{"safe-buffer":247}],88:[function(require,module,exports){ 9429},{"safe-buffer":156}],34:[function(require,module,exports){
14398var Buffer = require('safe-buffer').Buffer 9430var Buffer = require('safe-buffer').Buffer
14399 9431
14400function encryptByte (self, byteParam, decrypt) { 9432function encryptByte (self, byteParam, decrypt) {
@@ -14421,7 +9453,7 @@ exports.encrypt = function (self, chunk, decrypt) {
14421 return out 9453 return out
14422} 9454}
14423 9455
14424},{"safe-buffer":247}],89:[function(require,module,exports){ 9456},{"safe-buffer":156}],35:[function(require,module,exports){
14425var xor = require('buffer-xor') 9457var xor = require('buffer-xor')
14426var Buffer = require('safe-buffer').Buffer 9458var Buffer = require('safe-buffer').Buffer
14427var incr32 = require('../incr32') 9459var incr32 = require('../incr32')
@@ -14453,7 +9485,7 @@ exports.encrypt = function (self, chunk) {
14453 return xor(chunk, pad) 9485 return xor(chunk, pad)
14454} 9486}
14455 9487
14456},{"../incr32":84,"buffer-xor":106,"safe-buffer":247}],90:[function(require,module,exports){ 9488},{"../incr32":30,"buffer-xor":52,"safe-buffer":156}],36:[function(require,module,exports){
14457exports.encrypt = function (self, block) { 9489exports.encrypt = function (self, block) {
14458 return self._cipher.encryptBlock(block) 9490 return self._cipher.encryptBlock(block)
14459} 9491}
@@ -14462,7 +9494,7 @@ exports.decrypt = function (self, block) {
14462 return self._cipher.decryptBlock(block) 9494 return self._cipher.decryptBlock(block)
14463} 9495}
14464 9496
14465},{}],91:[function(require,module,exports){ 9497},{}],37:[function(require,module,exports){
14466var modeModules = { 9498var modeModules = {
14467 ECB: require('./ecb'), 9499 ECB: require('./ecb'),
14468 CBC: require('./cbc'), 9500 CBC: require('./cbc'),
@@ -14482,7 +9514,7 @@ for (var key in modes) {
14482 9514
14483module.exports = modes 9515module.exports = modes
14484 9516
14485},{"./cbc":85,"./cfb":86,"./cfb1":87,"./cfb8":88,"./ctr":89,"./ecb":90,"./list.json":92,"./ofb":93}],92:[function(require,module,exports){ 9517},{"./cbc":31,"./cfb":32,"./cfb1":33,"./cfb8":34,"./ctr":35,"./ecb":36,"./list.json":38,"./ofb":39}],38:[function(require,module,exports){
14486module.exports={ 9518module.exports={
14487 "aes-128-ecb": { 9519 "aes-128-ecb": {
14488 "cipher": "AES", 9520 "cipher": "AES",
@@ -14675,7 +9707,7 @@ module.exports={
14675 } 9707 }
14676} 9708}
14677 9709
14678},{}],93:[function(require,module,exports){ 9710},{}],39:[function(require,module,exports){
14679(function (Buffer){ 9711(function (Buffer){
14680var xor = require('buffer-xor') 9712var xor = require('buffer-xor')
14681 9713
@@ -14695,7 +9727,7 @@ exports.encrypt = function (self, chunk) {
14695} 9727}
14696 9728
14697}).call(this,require("buffer").Buffer) 9729}).call(this,require("buffer").Buffer)
14698},{"buffer":107,"buffer-xor":106}],94:[function(require,module,exports){ 9730},{"buffer":53,"buffer-xor":52}],40:[function(require,module,exports){
14699var aes = require('./aes') 9731var aes = require('./aes')
14700var Buffer = require('safe-buffer').Buffer 9732var Buffer = require('safe-buffer').Buffer
14701var Transform = require('cipher-base') 9733var Transform = require('cipher-base')
@@ -14724,7 +9756,7 @@ StreamCipher.prototype._final = function () {
14724 9756
14725module.exports = StreamCipher 9757module.exports = StreamCipher
14726 9758
14727},{"./aes":78,"cipher-base":108,"inherits":163,"safe-buffer":247}],95:[function(require,module,exports){ 9759},{"./aes":24,"cipher-base":54,"inherits":107,"safe-buffer":156}],41:[function(require,module,exports){
14728var ebtk = require('evp_bytestokey') 9760var ebtk = require('evp_bytestokey')
14729var aes = require('browserify-aes/browser') 9761var aes = require('browserify-aes/browser')
14730var DES = require('browserify-des') 9762var DES = require('browserify-des')
@@ -14799,7 +9831,7 @@ function getCiphers () {
14799} 9831}
14800exports.listCiphers = exports.getCiphers = getCiphers 9832exports.listCiphers = exports.getCiphers = getCiphers
14801 9833
14802},{"browserify-aes/browser":80,"browserify-aes/modes":91,"browserify-des":96,"browserify-des/modes":97,"evp_bytestokey":144}],96:[function(require,module,exports){ 9834},{"browserify-aes/browser":26,"browserify-aes/modes":37,"browserify-des":42,"browserify-des/modes":43,"evp_bytestokey":90}],42:[function(require,module,exports){
14803(function (Buffer){ 9835(function (Buffer){
14804var CipherBase = require('cipher-base') 9836var CipherBase = require('cipher-base')
14805var des = require('des.js') 9837var des = require('des.js')
@@ -14846,7 +9878,7 @@ DES.prototype._final = function () {
14846} 9878}
14847 9879
14848}).call(this,require("buffer").Buffer) 9880}).call(this,require("buffer").Buffer)
14849},{"buffer":107,"cipher-base":108,"des.js":117,"inherits":163}],97:[function(require,module,exports){ 9881},{"buffer":53,"cipher-base":54,"des.js":63,"inherits":107}],43:[function(require,module,exports){
14850exports['des-ecb'] = { 9882exports['des-ecb'] = {
14851 key: 8, 9883 key: 8,
14852 iv: 0 9884 iv: 0
@@ -14872,7 +9904,7 @@ exports['des-ede'] = {
14872 iv: 0 9904 iv: 0
14873} 9905}
14874 9906
14875},{}],98:[function(require,module,exports){ 9907},{}],44:[function(require,module,exports){
14876(function (Buffer){ 9908(function (Buffer){
14877var bn = require('bn.js'); 9909var bn = require('bn.js');
14878var randomBytes = require('randombytes'); 9910var randomBytes = require('randombytes');
@@ -14916,10 +9948,10 @@ function getr(priv) {
14916} 9948}
14917 9949
14918}).call(this,require("buffer").Buffer) 9950}).call(this,require("buffer").Buffer)
14919},{"bn.js":75,"buffer":107,"randombytes":231}],99:[function(require,module,exports){ 9951},{"bn.js":21,"buffer":53,"randombytes":140}],45:[function(require,module,exports){
14920module.exports = require('./browser/algorithms.json') 9952module.exports = require('./browser/algorithms.json')
14921 9953
14922},{"./browser/algorithms.json":100}],100:[function(require,module,exports){ 9954},{"./browser/algorithms.json":46}],46:[function(require,module,exports){
14923module.exports={ 9955module.exports={
14924 "sha224WithRSAEncryption": { 9956 "sha224WithRSAEncryption": {
14925 "sign": "rsa", 9957 "sign": "rsa",
@@ -15073,7 +10105,7 @@ module.exports={
15073 } 10105 }
15074} 10106}
15075 10107
15076},{}],101:[function(require,module,exports){ 10108},{}],47:[function(require,module,exports){
15077module.exports={ 10109module.exports={
15078 "1.3.132.0.10": "secp256k1", 10110 "1.3.132.0.10": "secp256k1",
15079 "1.3.132.0.33": "p224", 10111 "1.3.132.0.33": "p224",
@@ -15083,7 +10115,7 @@ module.exports={
15083 "1.3.132.0.35": "p521" 10115 "1.3.132.0.35": "p521"
15084} 10116}
15085 10117
15086},{}],102:[function(require,module,exports){ 10118},{}],48:[function(require,module,exports){
15087(function (Buffer){ 10119(function (Buffer){
15088var createHash = require('create-hash') 10120var createHash = require('create-hash')
15089var stream = require('stream') 10121var stream = require('stream')
@@ -15178,7 +10210,7 @@ module.exports = {
15178} 10210}
15179 10211
15180}).call(this,require("buffer").Buffer) 10212}).call(this,require("buffer").Buffer)
15181},{"./algorithms.json":100,"./sign":103,"./verify":104,"buffer":107,"create-hash":111,"inherits":163,"stream":263}],103:[function(require,module,exports){ 10213},{"./algorithms.json":46,"./sign":49,"./verify":50,"buffer":53,"create-hash":57,"inherits":107,"stream":172}],49:[function(require,module,exports){
15182(function (Buffer){ 10214(function (Buffer){
15183// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js 10215// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
15184var createHmac = require('create-hmac') 10216var createHmac = require('create-hmac')
@@ -15327,7 +10359,7 @@ module.exports.getKey = getKey
15327module.exports.makeKey = makeKey 10359module.exports.makeKey = makeKey
15328 10360
15329}).call(this,require("buffer").Buffer) 10361}).call(this,require("buffer").Buffer)
15330},{"./curves.json":101,"bn.js":75,"browserify-rsa":98,"buffer":107,"create-hmac":114,"elliptic":127,"parse-asn1":182}],104:[function(require,module,exports){ 10362},{"./curves.json":47,"bn.js":21,"browserify-rsa":44,"buffer":53,"create-hmac":60,"elliptic":73,"parse-asn1":126}],50:[function(require,module,exports){
15331(function (Buffer){ 10363(function (Buffer){
15332// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js 10364// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
15333var BN = require('bn.js') 10365var BN = require('bn.js')
@@ -15414,13 +10446,13 @@ function checkValue (b, q) {
15414module.exports = verify 10446module.exports = verify
15415 10447
15416}).call(this,require("buffer").Buffer) 10448}).call(this,require("buffer").Buffer)
15417},{"./curves.json":101,"bn.js":75,"buffer":107,"elliptic":127,"parse-asn1":182}],105:[function(require,module,exports){ 10449},{"./curves.json":47,"bn.js":21,"buffer":53,"elliptic":73,"parse-asn1":126}],51:[function(require,module,exports){
15418var basex = require('base-x') 10450var basex = require('base-x')
15419var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' 10451var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
15420 10452
15421module.exports = basex(ALPHABET) 10453module.exports = basex(ALPHABET)
15422 10454
15423},{"base-x":71}],106:[function(require,module,exports){ 10455},{"base-x":17}],52:[function(require,module,exports){
15424(function (Buffer){ 10456(function (Buffer){
15425module.exports = function xor (a, b) { 10457module.exports = function xor (a, b) {
15426 var length = Math.min(a.length, b.length) 10458 var length = Math.min(a.length, b.length)
@@ -15434,7 +10466,7 @@ module.exports = function xor (a, b) {
15434} 10466}
15435 10467
15436}).call(this,require("buffer").Buffer) 10468}).call(this,require("buffer").Buffer)
15437},{"buffer":107}],107:[function(require,module,exports){ 10469},{"buffer":53}],53:[function(require,module,exports){
15438/*! 10470/*!
15439 * The buffer module from node.js, for the browser. 10471 * The buffer module from node.js, for the browser.
15440 * 10472 *
@@ -17150,7 +12182,7 @@ function numberIsNaN (obj) {
17150 return obj !== obj // eslint-disable-line no-self-compare 12182 return obj !== obj // eslint-disable-line no-self-compare
17151} 12183}
17152 12184
17153},{"base64-js":72,"ieee754":161}],108:[function(require,module,exports){ 12185},{"base64-js":18,"ieee754":105}],54:[function(require,module,exports){
17154var Buffer = require('safe-buffer').Buffer 12186var Buffer = require('safe-buffer').Buffer
17155var Transform = require('stream').Transform 12187var Transform = require('stream').Transform
17156var StringDecoder = require('string_decoder').StringDecoder 12188var StringDecoder = require('string_decoder').StringDecoder
@@ -17251,7 +12283,7 @@ CipherBase.prototype._toString = function (value, enc, fin) {
17251 12283
17252module.exports = CipherBase 12284module.exports = CipherBase
17253 12285
17254},{"inherits":163,"safe-buffer":247,"stream":263,"string_decoder":264}],109:[function(require,module,exports){ 12286},{"inherits":107,"safe-buffer":156,"stream":172,"string_decoder":173}],55:[function(require,module,exports){
17255(function (Buffer){ 12287(function (Buffer){
17256// Copyright Joyent, Inc. and other Node contributors. 12288// Copyright Joyent, Inc. and other Node contributors.
17257// 12289//
@@ -17362,44 +12394,44 @@ function objectToString(o) {
17362} 12394}
17363 12395
17364}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) 12396}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
17365},{"../../is-buffer/index.js":164}],110:[function(require,module,exports){ 12397},{"../../is-buffer/index.js":108}],56:[function(require,module,exports){
17366(function (Buffer){ 12398(function (Buffer){
17367var elliptic = require('elliptic'); 12399var elliptic = require('elliptic');
17368var BN = require('bn.js'); 12400var BN = require('bn.js');
17369 12401
17370module.exports = function createECDH(curve) { 12402module.exports = function createECDH(curve) {
17371 return new ECDH(curve); 12403 return new ECDH(curve);
17372}; 12404};
17373 12405
17374var aliases = { 12406var aliases = {
17375 secp256k1: { 12407 secp256k1: {
17376 name: 'secp256k1', 12408 name: 'secp256k1',
17377 byteLength: 32 12409 byteLength: 32
17378 }, 12410 },
17379 secp224r1: { 12411 secp224r1: {
17380 name: 'p224', 12412 name: 'p224',
17381 byteLength: 28 12413 byteLength: 28
17382 }, 12414 },
17383 prime256v1: { 12415 prime256v1: {
17384 name: 'p256', 12416 name: 'p256',
17385 byteLength: 32 12417 byteLength: 32
17386 }, 12418 },
17387 prime192v1: { 12419 prime192v1: {
17388 name: 'p192', 12420 name: 'p192',
17389 byteLength: 24 12421 byteLength: 24
17390 }, 12422 },
17391 ed25519: { 12423 ed25519: {
17392 name: 'ed25519', 12424 name: 'ed25519',
17393 byteLength: 32 12425 byteLength: 32
17394 }, 12426 },
17395 secp384r1: { 12427 secp384r1: {
17396 name: 'p384', 12428 name: 'p384',
17397 byteLength: 48 12429 byteLength: 48
17398 }, 12430 },
17399 secp521r1: { 12431 secp521r1: {
17400 name: 'p521', 12432 name: 'p521',
17401 byteLength: 66 12433 byteLength: 66
17402 } 12434 }
17403}; 12435};
17404 12436
17405aliases.p224 = aliases.secp224r1; 12437aliases.p224 = aliases.secp224r1;
@@ -17409,86 +12441,86 @@ aliases.p384 = aliases.secp384r1;
17409aliases.p521 = aliases.secp521r1; 12441aliases.p521 = aliases.secp521r1;
17410 12442
17411function ECDH(curve) { 12443function ECDH(curve) {
17412 this.curveType = aliases[curve]; 12444 this.curveType = aliases[curve];
17413 if (!this.curveType ) { 12445 if (!this.curveType ) {
17414 this.curveType = { 12446 this.curveType = {
17415 name: curve 12447 name: curve
17416 }; 12448 };
17417 } 12449 }
17418 this.curve = new elliptic.ec(this.curveType.name); 12450 this.curve = new elliptic.ec(this.curveType.name);
17419 this.keys = void 0; 12451 this.keys = void 0;
17420} 12452}
17421 12453
17422ECDH.prototype.generateKeys = function (enc, format) { 12454ECDH.prototype.generateKeys = function (enc, format) {
17423 this.keys = this.curve.genKeyPair(); 12455 this.keys = this.curve.genKeyPair();
17424 return this.getPublicKey(enc, format); 12456 return this.getPublicKey(enc, format);
17425}; 12457};
17426 12458
17427ECDH.prototype.computeSecret = function (other, inenc, enc) { 12459ECDH.prototype.computeSecret = function (other, inenc, enc) {
17428 inenc = inenc || 'utf8'; 12460 inenc = inenc || 'utf8';
17429 if (!Buffer.isBuffer(other)) { 12461 if (!Buffer.isBuffer(other)) {
17430 other = new Buffer(other, inenc); 12462 other = new Buffer(other, inenc);
17431 } 12463 }
17432 var otherPub = this.curve.keyFromPublic(other).getPublic(); 12464 var otherPub = this.curve.keyFromPublic(other).getPublic();
17433 var out = otherPub.mul(this.keys.getPrivate()).getX(); 12465 var out = otherPub.mul(this.keys.getPrivate()).getX();
17434 return formatReturnValue(out, enc, this.curveType.byteLength); 12466 return formatReturnValue(out, enc, this.curveType.byteLength);
17435}; 12467};
17436 12468
17437ECDH.prototype.getPublicKey = function (enc, format) { 12469ECDH.prototype.getPublicKey = function (enc, format) {
17438 var key = this.keys.getPublic(format === 'compressed', true); 12470 var key = this.keys.getPublic(format === 'compressed', true);
17439 if (format === 'hybrid') { 12471 if (format === 'hybrid') {
17440 if (key[key.length - 1] % 2) { 12472 if (key[key.length - 1] % 2) {
17441 key[0] = 7; 12473 key[0] = 7;
17442 } else { 12474 } else {
17443 key [0] = 6; 12475 key [0] = 6;
17444 } 12476 }
17445 } 12477 }
17446 return formatReturnValue(key, enc); 12478 return formatReturnValue(key, enc);
17447}; 12479};
17448 12480
17449ECDH.prototype.getPrivateKey = function (enc) { 12481ECDH.prototype.getPrivateKey = function (enc) {
17450 return formatReturnValue(this.keys.getPrivate(), enc); 12482 return formatReturnValue(this.keys.getPrivate(), enc);
17451}; 12483};
17452 12484
17453ECDH.prototype.setPublicKey = function (pub, enc) { 12485ECDH.prototype.setPublicKey = function (pub, enc) {
17454 enc = enc || 'utf8'; 12486 enc = enc || 'utf8';
17455 if (!Buffer.isBuffer(pub)) { 12487 if (!Buffer.isBuffer(pub)) {
17456 pub = new Buffer(pub, enc); 12488 pub = new Buffer(pub, enc);
17457 } 12489 }
17458 this.keys._importPublic(pub); 12490 this.keys._importPublic(pub);
17459 return this; 12491 return this;
17460}; 12492};
17461 12493
17462ECDH.prototype.setPrivateKey = function (priv, enc) { 12494ECDH.prototype.setPrivateKey = function (priv, enc) {
17463 enc = enc || 'utf8'; 12495 enc = enc || 'utf8';
17464 if (!Buffer.isBuffer(priv)) { 12496 if (!Buffer.isBuffer(priv)) {
17465 priv = new Buffer(priv, enc); 12497 priv = new Buffer(priv, enc);
17466 } 12498 }
17467 var _priv = new BN(priv); 12499 var _priv = new BN(priv);
17468 _priv = _priv.toString(16); 12500 _priv = _priv.toString(16);
17469 this.keys._importPrivate(_priv); 12501 this.keys._importPrivate(_priv);
17470 return this; 12502 return this;
17471}; 12503};
17472 12504
17473function formatReturnValue(bn, enc, len) { 12505function formatReturnValue(bn, enc, len) {
17474 if (!Array.isArray(bn)) { 12506 if (!Array.isArray(bn)) {
17475 bn = bn.toArray(); 12507 bn = bn.toArray();
17476 } 12508 }
17477 var buf = new Buffer(bn); 12509 var buf = new Buffer(bn);
17478 if (len && buf.length < len) { 12510 if (len && buf.length < len) {
17479 var zeros = new Buffer(len - buf.length); 12511 var zeros = new Buffer(len - buf.length);
17480 zeros.fill(0); 12512 zeros.fill(0);
17481 buf = Buffer.concat([zeros, buf]); 12513 buf = Buffer.concat([zeros, buf]);
17482 } 12514 }
17483 if (!enc) { 12515 if (!enc) {
17484 return buf; 12516 return buf;
17485 } else { 12517 } else {
17486 return buf.toString(enc); 12518 return buf.toString(enc);
17487 } 12519 }
17488} 12520}
17489 12521
17490}).call(this,require("buffer").Buffer) 12522}).call(this,require("buffer").Buffer)
17491},{"bn.js":75,"buffer":107,"elliptic":127}],111:[function(require,module,exports){ 12523},{"bn.js":21,"buffer":53,"elliptic":73}],57:[function(require,module,exports){
17492(function (Buffer){ 12524(function (Buffer){
17493'use strict' 12525'use strict'
17494var inherits = require('inherits') 12526var inherits = require('inherits')
@@ -17544,7 +12576,7 @@ module.exports = function createHash (alg) {
17544} 12576}
17545 12577
17546}).call(this,require("buffer").Buffer) 12578}).call(this,require("buffer").Buffer)
17547},{"./md5":113,"buffer":107,"cipher-base":108,"inherits":163,"ripemd160":246,"sha.js":256}],112:[function(require,module,exports){ 12579},{"./md5":59,"buffer":53,"cipher-base":54,"inherits":107,"ripemd160":155,"sha.js":165}],58:[function(require,module,exports){
17548(function (Buffer){ 12580(function (Buffer){
17549'use strict' 12581'use strict'
17550var intSize = 4 12582var intSize = 4
@@ -17578,7 +12610,7 @@ module.exports = function hash (buf, fn) {
17578} 12610}
17579 12611
17580}).call(this,require("buffer").Buffer) 12612}).call(this,require("buffer").Buffer)
17581},{"buffer":107}],113:[function(require,module,exports){ 12613},{"buffer":53}],59:[function(require,module,exports){
17582'use strict' 12614'use strict'
17583/* 12615/*
17584 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message 12616 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
@@ -17731,7 +12763,7 @@ module.exports = function md5 (buf) {
17731 return makeHash(buf, core_md5) 12763 return makeHash(buf, core_md5)
17732} 12764}
17733 12765
17734},{"./make-hash":112}],114:[function(require,module,exports){ 12766},{"./make-hash":58}],60:[function(require,module,exports){
17735'use strict' 12767'use strict'
17736var inherits = require('inherits') 12768var inherits = require('inherits')
17737var Legacy = require('./legacy') 12769var Legacy = require('./legacy')
@@ -17795,7 +12827,7 @@ module.exports = function createHmac (alg, key) {
17795 return new Hmac(alg, key) 12827 return new Hmac(alg, key)
17796} 12828}
17797 12829
17798},{"./legacy":115,"cipher-base":108,"create-hash/md5":113,"inherits":163,"ripemd160":246,"safe-buffer":247,"sha.js":256}],115:[function(require,module,exports){ 12830},{"./legacy":61,"cipher-base":54,"create-hash/md5":59,"inherits":107,"ripemd160":155,"safe-buffer":156,"sha.js":165}],61:[function(require,module,exports){
17799'use strict' 12831'use strict'
17800var inherits = require('inherits') 12832var inherits = require('inherits')
17801var Buffer = require('safe-buffer').Buffer 12833var Buffer = require('safe-buffer').Buffer
@@ -17843,7 +12875,7 @@ Hmac.prototype._final = function () {
17843} 12875}
17844module.exports = Hmac 12876module.exports = Hmac
17845 12877
17846},{"cipher-base":108,"inherits":163,"safe-buffer":247}],116:[function(require,module,exports){ 12878},{"cipher-base":54,"inherits":107,"safe-buffer":156}],62:[function(require,module,exports){
17847'use strict' 12879'use strict'
17848 12880
17849exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes') 12881exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes')
@@ -17942,7 +12974,7 @@ exports.constants = {
17942 'POINT_CONVERSION_HYBRID': 6 12974 'POINT_CONVERSION_HYBRID': 6
17943} 12975}
17944 12976
17945},{"browserify-cipher":95,"browserify-sign":102,"browserify-sign/algos":99,"create-ecdh":110,"create-hash":111,"create-hmac":114,"diffie-hellman":123,"pbkdf2":184,"public-encrypt":225,"randombytes":231,"randomfill":232}],117:[function(require,module,exports){ 12977},{"browserify-cipher":41,"browserify-sign":48,"browserify-sign/algos":45,"create-ecdh":56,"create-hash":57,"create-hmac":60,"diffie-hellman":69,"pbkdf2":127,"public-encrypt":134,"randombytes":140,"randomfill":141}],63:[function(require,module,exports){
17946'use strict'; 12978'use strict';
17947 12979
17948exports.utils = require('./des/utils'); 12980exports.utils = require('./des/utils');
@@ -17951,7 +12983,7 @@ exports.DES = require('./des/des');
17951exports.CBC = require('./des/cbc'); 12983exports.CBC = require('./des/cbc');
17952exports.EDE = require('./des/ede'); 12984exports.EDE = require('./des/ede');
17953 12985
17954},{"./des/cbc":118,"./des/cipher":119,"./des/des":120,"./des/ede":121,"./des/utils":122}],118:[function(require,module,exports){ 12986},{"./des/cbc":64,"./des/cipher":65,"./des/des":66,"./des/ede":67,"./des/utils":68}],64:[function(require,module,exports){
17955'use strict'; 12987'use strict';
17956 12988
17957var assert = require('minimalistic-assert'); 12989var assert = require('minimalistic-assert');
@@ -18018,7 +13050,7 @@ proto._update = function _update(inp, inOff, out, outOff) {
18018 } 13050 }
18019}; 13051};
18020 13052
18021},{"inherits":163,"minimalistic-assert":176}],119:[function(require,module,exports){ 13053},{"inherits":107,"minimalistic-assert":120}],65:[function(require,module,exports){
18022'use strict'; 13054'use strict';
18023 13055
18024var assert = require('minimalistic-assert'); 13056var assert = require('minimalistic-assert');
@@ -18161,7 +13193,7 @@ Cipher.prototype._finalDecrypt = function _finalDecrypt() {
18161 return this._unpad(out); 13193 return this._unpad(out);
18162}; 13194};
18163 13195
18164},{"minimalistic-assert":176}],120:[function(require,module,exports){ 13196},{"minimalistic-assert":120}],66:[function(require,module,exports){
18165'use strict'; 13197'use strict';
18166 13198
18167var assert = require('minimalistic-assert'); 13199var assert = require('minimalistic-assert');
@@ -18306,7 +13338,7 @@ DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {
18306 utils.rip(l, r, out, off); 13338 utils.rip(l, r, out, off);
18307}; 13339};
18308 13340
18309},{"../des":117,"inherits":163,"minimalistic-assert":176}],121:[function(require,module,exports){ 13341},{"../des":63,"inherits":107,"minimalistic-assert":120}],67:[function(require,module,exports){
18310'use strict'; 13342'use strict';
18311 13343
18312var assert = require('minimalistic-assert'); 13344var assert = require('minimalistic-assert');
@@ -18363,7 +13395,7 @@ EDE.prototype._update = function _update(inp, inOff, out, outOff) {
18363EDE.prototype._pad = DES.prototype._pad; 13395EDE.prototype._pad = DES.prototype._pad;
18364EDE.prototype._unpad = DES.prototype._unpad; 13396EDE.prototype._unpad = DES.prototype._unpad;
18365 13397
18366},{"../des":117,"inherits":163,"minimalistic-assert":176}],122:[function(require,module,exports){ 13398},{"../des":63,"inherits":107,"minimalistic-assert":120}],68:[function(require,module,exports){
18367'use strict'; 13399'use strict';
18368 13400
18369exports.readUInt32BE = function readUInt32BE(bytes, off) { 13401exports.readUInt32BE = function readUInt32BE(bytes, off) {
@@ -18621,7 +13653,7 @@ exports.padSplit = function padSplit(num, size, group) {
18621 return out.join(' '); 13653 return out.join(' ');
18622}; 13654};
18623 13655
18624},{}],123:[function(require,module,exports){ 13656},{}],69:[function(require,module,exports){
18625(function (Buffer){ 13657(function (Buffer){
18626var generatePrime = require('./lib/generatePrime') 13658var generatePrime = require('./lib/generatePrime')
18627var primes = require('./lib/primes.json') 13659var primes = require('./lib/primes.json')
@@ -18667,7 +13699,7 @@ exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffi
18667exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman 13699exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman
18668 13700
18669}).call(this,require("buffer").Buffer) 13701}).call(this,require("buffer").Buffer)
18670},{"./lib/dh":124,"./lib/generatePrime":125,"./lib/primes.json":126,"buffer":107}],124:[function(require,module,exports){ 13702},{"./lib/dh":70,"./lib/generatePrime":71,"./lib/primes.json":72,"buffer":53}],70:[function(require,module,exports){
18671(function (Buffer){ 13703(function (Buffer){
18672var BN = require('bn.js'); 13704var BN = require('bn.js');
18673var MillerRabin = require('miller-rabin'); 13705var MillerRabin = require('miller-rabin');
@@ -18835,7 +13867,7 @@ function formatReturnValue(bn, enc) {
18835} 13867}
18836 13868
18837}).call(this,require("buffer").Buffer) 13869}).call(this,require("buffer").Buffer)
18838},{"./generatePrime":125,"bn.js":75,"buffer":107,"miller-rabin":175,"randombytes":231}],125:[function(require,module,exports){ 13870},{"./generatePrime":71,"bn.js":21,"buffer":53,"miller-rabin":119,"randombytes":140}],71:[function(require,module,exports){
18839var randomBytes = require('randombytes'); 13871var randomBytes = require('randombytes');
18840module.exports = findPrime; 13872module.exports = findPrime;
18841findPrime.simpleSieve = simpleSieve; 13873findPrime.simpleSieve = simpleSieve;
@@ -18942,7 +13974,7 @@ function findPrime(bits, gen) {
18942 13974
18943} 13975}
18944 13976
18945},{"bn.js":75,"miller-rabin":175,"randombytes":231}],126:[function(require,module,exports){ 13977},{"bn.js":21,"miller-rabin":119,"randombytes":140}],72:[function(require,module,exports){
18946module.exports={ 13978module.exports={
18947 "modp1": { 13979 "modp1": {
18948 "gen": "02", 13980 "gen": "02",
@@ -18977,7 +14009,7 @@ module.exports={
18977 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff" 14009 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"
18978 } 14010 }
18979} 14011}
18980},{}],127:[function(require,module,exports){ 14012},{}],73:[function(require,module,exports){
18981'use strict'; 14013'use strict';
18982 14014
18983var elliptic = exports; 14015var elliptic = exports;
@@ -18992,7 +14024,7 @@ elliptic.curves = require('./elliptic/curves');
18992elliptic.ec = require('./elliptic/ec'); 14024elliptic.ec = require('./elliptic/ec');
18993elliptic.eddsa = require('./elliptic/eddsa'); 14025elliptic.eddsa = require('./elliptic/eddsa');
18994 14026
18995},{"../package.json":142,"./elliptic/curve":130,"./elliptic/curves":133,"./elliptic/ec":134,"./elliptic/eddsa":137,"./elliptic/utils":141,"brorand":76}],128:[function(require,module,exports){ 14027},{"../package.json":88,"./elliptic/curve":76,"./elliptic/curves":79,"./elliptic/ec":80,"./elliptic/eddsa":83,"./elliptic/utils":87,"brorand":22}],74:[function(require,module,exports){
18996'use strict'; 14028'use strict';
18997 14029
18998var BN = require('bn.js'); 14030var BN = require('bn.js');
@@ -19369,7 +14401,7 @@ BasePoint.prototype.dblp = function dblp(k) {
19369 return r; 14401 return r;
19370}; 14402};
19371 14403
19372},{"../../elliptic":127,"bn.js":75}],129:[function(require,module,exports){ 14404},{"../../elliptic":73,"bn.js":21}],75:[function(require,module,exports){
19373'use strict'; 14405'use strict';
19374 14406
19375var curve = require('../curve'); 14407var curve = require('../curve');
@@ -19804,7 +14836,7 @@ Point.prototype.eqXToP = function eqXToP(x) {
19804Point.prototype.toP = Point.prototype.normalize; 14836Point.prototype.toP = Point.prototype.normalize;
19805Point.prototype.mixedAdd = Point.prototype.add; 14837Point.prototype.mixedAdd = Point.prototype.add;
19806 14838
19807},{"../../elliptic":127,"../curve":130,"bn.js":75,"inherits":163}],130:[function(require,module,exports){ 14839},{"../../elliptic":73,"../curve":76,"bn.js":21,"inherits":107}],76:[function(require,module,exports){
19808'use strict'; 14840'use strict';
19809 14841
19810var curve = exports; 14842var curve = exports;
@@ -19814,7 +14846,7 @@ curve.short = require('./short');
19814curve.mont = require('./mont'); 14846curve.mont = require('./mont');
19815curve.edwards = require('./edwards'); 14847curve.edwards = require('./edwards');
19816 14848
19817},{"./base":128,"./edwards":129,"./mont":131,"./short":132}],131:[function(require,module,exports){ 14849},{"./base":74,"./edwards":75,"./mont":77,"./short":78}],77:[function(require,module,exports){
19818'use strict'; 14850'use strict';
19819 14851
19820var curve = require('../curve'); 14852var curve = require('../curve');
@@ -19996,7 +15028,7 @@ Point.prototype.getX = function getX() {
19996 return this.x.fromRed(); 15028 return this.x.fromRed();
19997}; 15029};
19998 15030
19999},{"../../elliptic":127,"../curve":130,"bn.js":75,"inherits":163}],132:[function(require,module,exports){ 15031},{"../../elliptic":73,"../curve":76,"bn.js":21,"inherits":107}],78:[function(require,module,exports){
20000'use strict'; 15032'use strict';
20001 15033
20002var curve = require('../curve'); 15034var curve = require('../curve');
@@ -20936,7 +15968,7 @@ JPoint.prototype.isInfinity = function isInfinity() {
20936 return this.z.cmpn(0) === 0; 15968 return this.z.cmpn(0) === 0;
20937}; 15969};
20938 15970
20939},{"../../elliptic":127,"../curve":130,"bn.js":75,"inherits":163}],133:[function(require,module,exports){ 15971},{"../../elliptic":73,"../curve":76,"bn.js":21,"inherits":107}],79:[function(require,module,exports){
20940'use strict'; 15972'use strict';
20941 15973
20942var curves = exports; 15974var curves = exports;
@@ -21143,7 +16175,7 @@ defineCurve('secp256k1', {
21143 ] 16175 ]
21144}); 16176});
21145 16177
21146},{"../elliptic":127,"./precomputed/secp256k1":140,"hash.js":147}],134:[function(require,module,exports){ 16178},{"../elliptic":73,"./precomputed/secp256k1":86,"hash.js":92}],80:[function(require,module,exports){
21147'use strict'; 16179'use strict';
21148 16180
21149var BN = require('bn.js'); 16181var BN = require('bn.js');
@@ -21385,7 +16417,7 @@ EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
21385 throw new Error('Unable to find valid recovery factor'); 16417 throw new Error('Unable to find valid recovery factor');
21386}; 16418};
21387 16419
21388},{"../../elliptic":127,"./key":135,"./signature":136,"bn.js":75,"hmac-drbg":159}],135:[function(require,module,exports){ 16420},{"../../elliptic":73,"./key":81,"./signature":82,"bn.js":21,"hmac-drbg":104}],81:[function(require,module,exports){
21389'use strict'; 16421'use strict';
21390 16422
21391var BN = require('bn.js'); 16423var BN = require('bn.js');
@@ -21506,7 +16538,7 @@ KeyPair.prototype.inspect = function inspect() {
21506 ' pub: ' + (this.pub && this.pub.inspect()) + ' >'; 16538 ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
21507}; 16539};
21508 16540
21509},{"../../elliptic":127,"bn.js":75}],136:[function(require,module,exports){ 16541},{"../../elliptic":73,"bn.js":21}],82:[function(require,module,exports){
21510'use strict'; 16542'use strict';
21511 16543
21512var BN = require('bn.js'); 16544var BN = require('bn.js');
@@ -21643,7 +16675,7 @@ Signature.prototype.toDER = function toDER(enc) {
21643 return utils.encode(res, enc); 16675 return utils.encode(res, enc);
21644}; 16676};
21645 16677
21646},{"../../elliptic":127,"bn.js":75}],137:[function(require,module,exports){ 16678},{"../../elliptic":73,"bn.js":21}],83:[function(require,module,exports){
21647'use strict'; 16679'use strict';
21648 16680
21649var hash = require('hash.js'); 16681var hash = require('hash.js');
@@ -21763,7 +16795,7 @@ EDDSA.prototype.isPoint = function isPoint(val) {
21763 return val instanceof this.pointClass; 16795 return val instanceof this.pointClass;
21764}; 16796};
21765 16797
21766},{"../../elliptic":127,"./key":138,"./signature":139,"hash.js":147}],138:[function(require,module,exports){ 16798},{"../../elliptic":73,"./key":84,"./signature":85,"hash.js":92}],84:[function(require,module,exports){
21767'use strict'; 16799'use strict';
21768 16800
21769var elliptic = require('../../elliptic'); 16801var elliptic = require('../../elliptic');
@@ -21861,7 +16893,7 @@ KeyPair.prototype.getPublic = function getPublic(enc) {
21861 16893
21862module.exports = KeyPair; 16894module.exports = KeyPair;
21863 16895
21864},{"../../elliptic":127}],139:[function(require,module,exports){ 16896},{"../../elliptic":73}],85:[function(require,module,exports){
21865'use strict'; 16897'use strict';
21866 16898
21867var BN = require('bn.js'); 16899var BN = require('bn.js');
@@ -21929,7 +16961,7 @@ Signature.prototype.toHex = function toHex() {
21929 16961
21930module.exports = Signature; 16962module.exports = Signature;
21931 16963
21932},{"../../elliptic":127,"bn.js":75}],140:[function(require,module,exports){ 16964},{"../../elliptic":73,"bn.js":21}],86:[function(require,module,exports){
21933module.exports = { 16965module.exports = {
21934 doubles: { 16966 doubles: {
21935 step: 4, 16967 step: 4,
@@ -22711,7 +17743,7 @@ module.exports = {
22711 } 17743 }
22712}; 17744};
22713 17745
22714},{}],141:[function(require,module,exports){ 17746},{}],87:[function(require,module,exports){
22715'use strict'; 17747'use strict';
22716 17748
22717var utils = exports; 17749var utils = exports;
@@ -22833,32 +17865,38 @@ function intFromLE(bytes) {
22833utils.intFromLE = intFromLE; 17865utils.intFromLE = intFromLE;
22834 17866
22835 17867
22836},{"bn.js":75,"minimalistic-assert":176,"minimalistic-crypto-utils":177}],142:[function(require,module,exports){ 17868},{"bn.js":21,"minimalistic-assert":120,"minimalistic-crypto-utils":121}],88:[function(require,module,exports){
22837module.exports={ 17869module.exports={
22838 "_from": "elliptic@^6.0.0", 17870 "_args": [
17871 [
17872 "elliptic@6.4.0",
17873 "/home/gleb/work/cryptocurrencies/nas-hardwallet/neb.js"
17874 ]
17875 ],
17876 "_from": "elliptic@6.4.0",
22839 "_id": "elliptic@6.4.0", 17877 "_id": "elliptic@6.4.0",
22840 "_inBundle": false, 17878 "_inBundle": false,
22841 "_integrity": "sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=", 17879 "_integrity": "sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=",
22842 "_location": "/elliptic", 17880 "_location": "/elliptic",
22843 "_phantomChildren": {}, 17881 "_phantomChildren": {},
22844 "_requested": { 17882 "_requested": {
22845 "type": "range", 17883 "type": "version",
22846 "registry": true, 17884 "registry": true,
22847 "raw": "elliptic@^6.0.0", 17885 "raw": "elliptic@6.4.0",
22848 "name": "elliptic", 17886 "name": "elliptic",
22849 "escapedName": "elliptic", 17887 "escapedName": "elliptic",
22850 "rawSpec": "^6.0.0", 17888 "rawSpec": "6.4.0",
22851 "saveSpec": null, 17889 "saveSpec": null,
22852 "fetchSpec": "^6.0.0" 17890 "fetchSpec": "6.4.0"
22853 }, 17891 },
22854 "_requiredBy": [ 17892 "_requiredBy": [
22855 "/browserify-sign", 17893 "/browserify-sign",
22856 "/create-ecdh" 17894 "/create-ecdh",
17895 "/secp256k1"
22857 ], 17896 ],
22858 "_resolved": "http://registry.npm.taobao.org/elliptic/download/elliptic-6.4.0.tgz", 17897 "_resolved": "http://registry.npm.taobao.org/elliptic/download/elliptic-6.4.0.tgz",
22859 "_shasum": "cac9af8762c85836187003c8dfe193e5e2eae5df", 17898 "_spec": "6.4.0",
22860 "_spec": "elliptic@^6.0.0", 17899 "_where": "/home/gleb/work/cryptocurrencies/nas-hardwallet/neb.js",
22861 "_where": "/Users/qywang/workspace/go/src/github.com/nebulasio/go-nebulas/cmd/console/neb.js/node_modules/browserify-sign",
22862 "author": { 17900 "author": {
22863 "name": "Fedor Indutny", 17901 "name": "Fedor Indutny",
22864 "email": "fedor@indutny.com" 17902 "email": "fedor@indutny.com"
@@ -22866,7 +17904,6 @@ module.exports={
22866 "bugs": { 17904 "bugs": {
22867 "url": "https://github.com/indutny/elliptic/issues" 17905 "url": "https://github.com/indutny/elliptic/issues"
22868 }, 17906 },
22869 "bundleDependencies": false,
22870 "dependencies": { 17907 "dependencies": {
22871 "bn.js": "^4.4.0", 17908 "bn.js": "^4.4.0",
22872 "brorand": "^1.0.1", 17909 "brorand": "^1.0.1",
@@ -22876,7 +17913,6 @@ module.exports={
22876 "minimalistic-assert": "^1.0.0", 17913 "minimalistic-assert": "^1.0.0",
22877 "minimalistic-crypto-utils": "^1.0.0" 17914 "minimalistic-crypto-utils": "^1.0.0"
22878 }, 17915 },
22879 "deprecated": false,
22880 "description": "EC cryptography", 17916 "description": "EC cryptography",
22881 "devDependencies": { 17917 "devDependencies": {
22882 "brfs": "^1.4.3", 17918 "brfs": "^1.4.3",
@@ -22922,7 +17958,7 @@ module.exports={
22922 "version": "6.4.0" 17958 "version": "6.4.0"
22923} 17959}
22924 17960
22925},{}],143:[function(require,module,exports){ 17961},{}],89:[function(require,module,exports){
22926// Copyright Joyent, Inc. and other Node contributors. 17962// Copyright Joyent, Inc. and other Node contributors.
22927// 17963//
22928// Permission is hereby granted, free of charge, to any person obtaining a 17964// Permission is hereby granted, free of charge, to any person obtaining a
@@ -23226,7 +18262,7 @@ function isUndefined(arg) {
23226 return arg === void 0; 18262 return arg === void 0;
23227} 18263}
23228 18264
23229},{}],144:[function(require,module,exports){ 18265},{}],90:[function(require,module,exports){
23230var Buffer = require('safe-buffer').Buffer 18266var Buffer = require('safe-buffer').Buffer
23231var MD5 = require('md5.js') 18267var MD5 = require('md5.js')
23232 18268
@@ -23273,95 +18309,7 @@ function EVP_BytesToKey (password, salt, keyBits, ivLen) {
23273 18309
23274module.exports = EVP_BytesToKey 18310module.exports = EVP_BytesToKey
23275 18311
23276},{"md5.js":173,"safe-buffer":247}],145:[function(require,module,exports){ 18312},{"md5.js":117,"safe-buffer":156}],91:[function(require,module,exports){
23277'use strict';
23278
23279var hasOwn = Object.prototype.hasOwnProperty;
23280var toStr = Object.prototype.toString;
23281
23282var isArray = function isArray(arr) {
23283 if (typeof Array.isArray === 'function') {
23284 return Array.isArray(arr);
23285 }
23286
23287 return toStr.call(arr) === '[object Array]';
23288};
23289
23290var isPlainObject = function isPlainObject(obj) {
23291 if (!obj || toStr.call(obj) !== '[object Object]') {
23292 return false;
23293 }
23294
23295 var hasOwnConstructor = hasOwn.call(obj, 'constructor');
23296 var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
23297 // Not own constructor property must be Object
23298 if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
23299 return false;
23300 }
23301
23302 // Own properties are enumerated firstly, so to speed up,
23303 // if last one is own, then all properties are own.
23304 var key;
23305 for (key in obj) { /**/ }
23306
23307 return typeof key === 'undefined' || hasOwn.call(obj, key);
23308};
23309
23310module.exports = function extend() {
23311 var options, name, src, copy, copyIsArray, clone;
23312 var target = arguments[0];
23313 var i = 1;
23314 var length = arguments.length;
23315 var deep = false;
23316
23317 // Handle a deep copy situation
23318 if (typeof target === 'boolean') {
23319 deep = target;
23320 target = arguments[1] || {};
23321 // skip the boolean and the target
23322 i = 2;
23323 }
23324 if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
23325 target = {};
23326 }
23327
23328 for (; i < length; ++i) {
23329 options = arguments[i];
23330 // Only deal with non-null/undefined values
23331 if (options != null) {
23332 // Extend the base object
23333 for (name in options) {
23334 src = target[name];
23335 copy = options[name];
23336
23337 // Prevent never-ending loop
23338 if (target !== copy) {
23339 // Recurse if we're merging plain objects or arrays
23340 if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
23341 if (copyIsArray) {
23342 copyIsArray = false;
23343 clone = src && isArray(src) ? src : [];
23344 } else {
23345 clone = src && isPlainObject(src) ? src : {};
23346 }
23347
23348 // Never move original objects, clone them
23349 target[name] = extend(deep, clone, copy);
23350
23351 // Don't bring in undefined values
23352 } else if (typeof copy !== 'undefined') {
23353 target[name] = copy;
23354 }
23355 }
23356 }
23357 }
23358 }
23359
23360 // Return the modified object
23361 return target;
23362};
23363
23364},{}],146:[function(require,module,exports){
23365(function (Buffer){ 18313(function (Buffer){
23366'use strict' 18314'use strict'
23367var Transform = require('stream').Transform 18315var Transform = require('stream').Transform
@@ -23448,7 +18396,7 @@ HashBase.prototype._digest = function () {
23448module.exports = HashBase 18396module.exports = HashBase
23449 18397
23450}).call(this,require("buffer").Buffer) 18398}).call(this,require("buffer").Buffer)
23451},{"buffer":107,"inherits":163,"stream":263}],147:[function(require,module,exports){ 18399},{"buffer":53,"inherits":107,"stream":172}],92:[function(require,module,exports){
23452var hash = exports; 18400var hash = exports;
23453 18401
23454hash.utils = require('./hash/utils'); 18402hash.utils = require('./hash/utils');
@@ -23465,7 +18413,7 @@ hash.sha384 = hash.sha.sha384;
23465hash.sha512 = hash.sha.sha512; 18413hash.sha512 = hash.sha.sha512;
23466hash.ripemd160 = hash.ripemd.ripemd160; 18414hash.ripemd160 = hash.ripemd.ripemd160;
23467 18415
23468},{"./hash/common":148,"./hash/hmac":149,"./hash/ripemd":150,"./hash/sha":151,"./hash/utils":158}],148:[function(require,module,exports){ 18416},{"./hash/common":93,"./hash/hmac":94,"./hash/ripemd":95,"./hash/sha":96,"./hash/utils":103}],93:[function(require,module,exports){
23469'use strict'; 18417'use strict';
23470 18418
23471var utils = require('./utils'); 18419var utils = require('./utils');
@@ -23559,7 +18507,7 @@ BlockHash.prototype._pad = function pad() {
23559 return res; 18507 return res;
23560}; 18508};
23561 18509
23562},{"./utils":158,"minimalistic-assert":176}],149:[function(require,module,exports){ 18510},{"./utils":103,"minimalistic-assert":120}],94:[function(require,module,exports){
23563'use strict'; 18511'use strict';
23564 18512
23565var utils = require('./utils'); 18513var utils = require('./utils');
@@ -23608,7 +18556,7 @@ Hmac.prototype.digest = function digest(enc) {
23608 return this.outer.digest(enc); 18556 return this.outer.digest(enc);
23609}; 18557};
23610 18558
23611},{"./utils":158,"minimalistic-assert":176}],150:[function(require,module,exports){ 18559},{"./utils":103,"minimalistic-assert":120}],95:[function(require,module,exports){
23612'use strict'; 18560'use strict';
23613 18561
23614var utils = require('./utils'); 18562var utils = require('./utils');
@@ -23756,7 +18704,7 @@ var sh = [
23756 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 18704 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
23757]; 18705];
23758 18706
23759},{"./common":148,"./utils":158}],151:[function(require,module,exports){ 18707},{"./common":93,"./utils":103}],96:[function(require,module,exports){
23760'use strict'; 18708'use strict';
23761 18709
23762exports.sha1 = require('./sha/1'); 18710exports.sha1 = require('./sha/1');
@@ -23765,7 +18713,7 @@ exports.sha256 = require('./sha/256');
23765exports.sha384 = require('./sha/384'); 18713exports.sha384 = require('./sha/384');
23766exports.sha512 = require('./sha/512'); 18714exports.sha512 = require('./sha/512');
23767 18715
23768},{"./sha/1":152,"./sha/224":153,"./sha/256":154,"./sha/384":155,"./sha/512":156}],152:[function(require,module,exports){ 18716},{"./sha/1":97,"./sha/224":98,"./sha/256":99,"./sha/384":100,"./sha/512":101}],97:[function(require,module,exports){
23769'use strict'; 18717'use strict';
23770 18718
23771var utils = require('../utils'); 18719var utils = require('../utils');
@@ -23841,7 +18789,7 @@ SHA1.prototype._digest = function digest(enc) {
23841 return utils.split32(this.h, 'big'); 18789 return utils.split32(this.h, 'big');
23842}; 18790};
23843 18791
23844},{"../common":148,"../utils":158,"./common":157}],153:[function(require,module,exports){ 18792},{"../common":93,"../utils":103,"./common":102}],98:[function(require,module,exports){
23845'use strict'; 18793'use strict';
23846 18794
23847var utils = require('../utils'); 18795var utils = require('../utils');
@@ -23873,7 +18821,7 @@ SHA224.prototype._digest = function digest(enc) {
23873}; 18821};
23874 18822
23875 18823
23876},{"../utils":158,"./256":154}],154:[function(require,module,exports){ 18824},{"../utils":103,"./256":99}],99:[function(require,module,exports){
23877'use strict'; 18825'use strict';
23878 18826
23879var utils = require('../utils'); 18827var utils = require('../utils');
@@ -23980,7 +18928,7 @@ SHA256.prototype._digest = function digest(enc) {
23980 return utils.split32(this.h, 'big'); 18928 return utils.split32(this.h, 'big');
23981}; 18929};
23982 18930
23983},{"../common":148,"../utils":158,"./common":157,"minimalistic-assert":176}],155:[function(require,module,exports){ 18931},{"../common":93,"../utils":103,"./common":102,"minimalistic-assert":120}],100:[function(require,module,exports){
23984'use strict'; 18932'use strict';
23985 18933
23986var utils = require('../utils'); 18934var utils = require('../utils');
@@ -24017,7 +18965,7 @@ SHA384.prototype._digest = function digest(enc) {
24017 return utils.split32(this.h.slice(0, 12), 'big'); 18965 return utils.split32(this.h.slice(0, 12), 'big');
24018}; 18966};
24019 18967
24020},{"../utils":158,"./512":156}],156:[function(require,module,exports){ 18968},{"../utils":103,"./512":101}],101:[function(require,module,exports){
24021'use strict'; 18969'use strict';
24022 18970
24023var utils = require('../utils'); 18971var utils = require('../utils');
@@ -24349,7 +19297,7 @@ function g1_512_lo(xh, xl) {
24349 return r; 19297 return r;
24350} 19298}
24351 19299
24352},{"../common":148,"../utils":158,"minimalistic-assert":176}],157:[function(require,module,exports){ 19300},{"../common":93,"../utils":103,"minimalistic-assert":120}],102:[function(require,module,exports){
24353'use strict'; 19301'use strict';
24354 19302
24355var utils = require('../utils'); 19303var utils = require('../utils');
@@ -24400,7 +19348,7 @@ function g1_256(x) {
24400} 19348}
24401exports.g1_256 = g1_256; 19349exports.g1_256 = g1_256;
24402 19350
24403},{"../utils":158}],158:[function(require,module,exports){ 19351},{"../utils":103}],103:[function(require,module,exports){
24404'use strict'; 19352'use strict';
24405 19353
24406var assert = require('minimalistic-assert'); 19354var assert = require('minimalistic-assert');
@@ -24655,7 +19603,7 @@ function shr64_lo(ah, al, num) {
24655} 19603}
24656exports.shr64_lo = shr64_lo; 19604exports.shr64_lo = shr64_lo;
24657 19605
24658},{"inherits":163,"minimalistic-assert":176}],159:[function(require,module,exports){ 19606},{"inherits":107,"minimalistic-assert":120}],104:[function(require,module,exports){
24659'use strict'; 19607'use strict';
24660 19608
24661var hash = require('hash.js'); 19609var hash = require('hash.js');
@@ -24770,51 +19718,7 @@ HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
24770 return utils.encode(res, enc); 19718 return utils.encode(res, enc);
24771}; 19719};
24772 19720
24773},{"hash.js":147,"minimalistic-assert":176,"minimalistic-crypto-utils":177}],160:[function(require,module,exports){ 19721},{"hash.js":92,"minimalistic-assert":120,"minimalistic-crypto-utils":121}],105:[function(require,module,exports){
24774/**
24775 * Properly escape JSON for usage as an object literal inside of a `<script>` tag.
24776 * JS implementation of http://golang.org/pkg/encoding/json/#HTMLEscape
24777 * More info: http://timelessrepo.com/json-isnt-a-javascript-subset
24778 */
24779
24780'use strict';
24781
24782var ESCAPE_LOOKUP = {
24783 '&': '\\u0026',
24784 '>': '\\u003e',
24785 '<': '\\u003c',
24786 '\u2028': '\\u2028',
24787 '\u2029': '\\u2029'
24788};
24789
24790var ESCAPE_REGEX = /[&><\u2028\u2029]/g;
24791
24792function escaper(match) {
24793 return ESCAPE_LOOKUP[match];
24794}
24795
24796module.exports = function(obj) {
24797 return JSON.stringify(obj).replace(ESCAPE_REGEX, escaper);
24798};
24799
24800/***/
24801
24802var TERMINATORS_LOOKUP = {
24803 '\u2028': '\\u2028',
24804 '\u2029': '\\u2029'
24805};
24806
24807var TERMINATORS_REGEX = /[\u2028\u2029]/g;
24808
24809function sanitizer(match) {
24810 return TERMINATORS_LOOKUP[match];
24811}
24812
24813module.exports.sanitize = function(str) {
24814 return str.replace(TERMINATORS_REGEX, sanitizer);
24815};
24816
24817},{}],161:[function(require,module,exports){
24818exports.read = function (buffer, offset, isLE, mLen, nBytes) { 19722exports.read = function (buffer, offset, isLE, mLen, nBytes) {
24819 var e, m 19723 var e, m
24820 var eLen = nBytes * 8 - mLen - 1 19724 var eLen = nBytes * 8 - mLen - 1
@@ -24900,7 +19804,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
24900 buffer[offset + i - d] |= s * 128 19804 buffer[offset + i - d] |= s * 128
24901} 19805}
24902 19806
24903},{}],162:[function(require,module,exports){ 19807},{}],106:[function(require,module,exports){
24904 19808
24905var indexOf = [].indexOf; 19809var indexOf = [].indexOf;
24906 19810
@@ -24911,7 +19815,7 @@ module.exports = function(arr, obj){
24911 } 19815 }
24912 return -1; 19816 return -1;
24913}; 19817};
24914},{}],163:[function(require,module,exports){ 19818},{}],107:[function(require,module,exports){
24915if (typeof Object.create === 'function') { 19819if (typeof Object.create === 'function') {
24916 // implementation from standard node.js 'util' module 19820 // implementation from standard node.js 'util' module
24917 module.exports = function inherits(ctor, superCtor) { 19821 module.exports = function inherits(ctor, superCtor) {
@@ -24936,7 +19840,7 @@ if (typeof Object.create === 'function') {
24936 } 19840 }
24937} 19841}
24938 19842
24939},{}],164:[function(require,module,exports){ 19843},{}],108:[function(require,module,exports){
24940/*! 19844/*!
24941 * Determine if an object is a Buffer 19845 * Determine if an object is a Buffer
24942 * 19846 *
@@ -24959,14 +19863,14 @@ function isSlowBuffer (obj) {
24959 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) 19863 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
24960} 19864}
24961 19865
24962},{}],165:[function(require,module,exports){ 19866},{}],109:[function(require,module,exports){
24963var toString = {}.toString; 19867var toString = {}.toString;
24964 19868
24965module.exports = Array.isArray || function (arr) { 19869module.exports = Array.isArray || function (arr) {
24966 return toString.call(arr) == '[object Array]'; 19870 return toString.call(arr) == '[object Array]';
24967}; 19871};
24968 19872
24969},{}],166:[function(require,module,exports){ 19873},{}],110:[function(require,module,exports){
24970/* 19874/*
24971 A JavaScript implementation of the SHA family of hashes, as 19875 A JavaScript implementation of the SHA family of hashes, as
24972 defined in FIPS PUB 180-4 and FIPS PUB 202, as well as the corresponding 19876 defined in FIPS PUB 180-4 and FIPS PUB 202, as well as the corresponding
@@ -25013,11 +19917,11 @@ new b(d[40],1290863460),new b(d[41],3158454273),new b(d[42],3505952657),new b(d[
250131246189591)];X=[new b(0,1),new b(0,32898),new b(2147483648,32906),new b(2147483648,2147516416),new b(0,32907),new b(0,2147483649),new b(2147483648,2147516545),new b(2147483648,32777),new b(0,138),new b(0,136),new b(0,2147516425),new b(0,2147483658),new b(0,2147516555),new b(2147483648,139),new b(2147483648,32905),new b(2147483648,32771),new b(2147483648,32770),new b(2147483648,128),new b(0,32778),new b(2147483648,2147483658),new b(2147483648,2147516545),new b(2147483648,32896),new b(0,2147483649), 199171246189591)];X=[new b(0,1),new b(0,32898),new b(2147483648,32906),new b(2147483648,2147516416),new b(0,32907),new b(0,2147483649),new b(2147483648,2147516545),new b(2147483648,32777),new b(0,138),new b(0,136),new b(0,2147516425),new b(0,2147483658),new b(0,2147516555),new b(2147483648,139),new b(2147483648,32905),new b(2147483648,32771),new b(2147483648,32770),new b(2147483648,128),new b(0,32778),new b(2147483648,2147483658),new b(2147483648,2147516545),new b(2147483648,32896),new b(0,2147483649),
25014new b(2147483648,2147516424)];W=[[0,36,3,41,18],[1,44,10,45,2],[62,6,43,15,61],[28,55,25,21,56],[27,20,39,8,14]];"function"===typeof define&&define.amd?define(function(){return C}):"undefined"!==typeof exports?("undefined"!==typeof module&&module.exports&&(module.exports=C),exports=C):Y.jsSHA=C})(this); 19918new b(2147483648,2147516424)];W=[[0,36,3,41,18],[1,44,10,45,2],[62,6,43,15,61],[28,55,25,21,56],[27,20,39,8,14]];"function"===typeof define&&define.amd?define(function(){return C}):"undefined"!==typeof exports?("undefined"!==typeof module&&module.exports&&(module.exports=C),exports=C):Y.jsSHA=C})(this);
25015 19919
25016},{}],167:[function(require,module,exports){ 19920},{}],111:[function(require,module,exports){
25017'use strict' 19921'use strict'
25018module.exports = require('./lib/api')(require('./lib/keccak')) 19922module.exports = require('./lib/api')(require('./lib/keccak'))
25019 19923
25020},{"./lib/api":168,"./lib/keccak":172}],168:[function(require,module,exports){ 19924},{"./lib/api":112,"./lib/keccak":116}],112:[function(require,module,exports){
25021'use strict' 19925'use strict'
25022var createKeccak = require('./keccak') 19926var createKeccak = require('./keccak')
25023var createShake = require('./shake') 19927var createShake = require('./shake')
@@ -25047,7 +19951,7 @@ module.exports = function (KeccakState) {
25047 } 19951 }
25048} 19952}
25049 19953
25050},{"./keccak":169,"./shake":170}],169:[function(require,module,exports){ 19954},{"./keccak":113,"./shake":114}],113:[function(require,module,exports){
25051'use strict' 19955'use strict'
25052var Buffer = require('safe-buffer').Buffer 19956var Buffer = require('safe-buffer').Buffer
25053var Transform = require('stream').Transform 19957var Transform = require('stream').Transform
@@ -25133,7 +20037,7 @@ module.exports = function (KeccakState) {
25133 return Keccak 20037 return Keccak
25134} 20038}
25135 20039
25136},{"inherits":163,"safe-buffer":247,"stream":263}],170:[function(require,module,exports){ 20040},{"inherits":107,"safe-buffer":156,"stream":172}],114:[function(require,module,exports){
25137'use strict' 20041'use strict'
25138var Buffer = require('safe-buffer').Buffer 20042var Buffer = require('safe-buffer').Buffer
25139var Transform = require('stream').Transform 20043var Transform = require('stream').Transform
@@ -25210,7 +20114,7 @@ module.exports = function (KeccakState) {
25210 return Shake 20114 return Shake
25211} 20115}
25212 20116
25213},{"inherits":163,"safe-buffer":247,"stream":263}],171:[function(require,module,exports){ 20117},{"inherits":107,"safe-buffer":156,"stream":172}],115:[function(require,module,exports){
25214'use strict' 20118'use strict'
25215var P1600_ROUND_CONSTANTS = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648] 20119var P1600_ROUND_CONSTANTS = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]
25216 20120
@@ -25399,7 +20303,7 @@ exports.p1600 = function (s) {
25399 } 20303 }
25400} 20304}
25401 20305
25402},{}],172:[function(require,module,exports){ 20306},{}],116:[function(require,module,exports){
25403'use strict' 20307'use strict'
25404var Buffer = require('safe-buffer').Buffer 20308var Buffer = require('safe-buffer').Buffer
25405var keccakState = require('./keccak-state-unroll') 20309var keccakState = require('./keccak-state-unroll')
@@ -25471,7 +20375,7 @@ Keccak.prototype.copy = function (dest) {
25471 20375
25472module.exports = Keccak 20376module.exports = Keccak
25473 20377
25474},{"./keccak-state-unroll":171,"safe-buffer":247}],173:[function(require,module,exports){ 20378},{"./keccak-state-unroll":115,"safe-buffer":156}],117:[function(require,module,exports){
25475(function (Buffer){ 20379(function (Buffer){
25476'use strict' 20380'use strict'
25477var inherits = require('inherits') 20381var inherits = require('inherits')
@@ -25620,7 +20524,7 @@ function fnI (a, b, c, d, m, k, s) {
25620module.exports = MD5 20524module.exports = MD5
25621 20525
25622}).call(this,require("buffer").Buffer) 20526}).call(this,require("buffer").Buffer)
25623},{"buffer":107,"hash-base":174,"inherits":163}],174:[function(require,module,exports){ 20527},{"buffer":53,"hash-base":118,"inherits":107}],118:[function(require,module,exports){
25624'use strict' 20528'use strict'
25625var Buffer = require('safe-buffer').Buffer 20529var Buffer = require('safe-buffer').Buffer
25626var Transform = require('stream').Transform 20530var Transform = require('stream').Transform
@@ -25717,7 +20621,7 @@ HashBase.prototype._digest = function () {
25717 20621
25718module.exports = HashBase 20622module.exports = HashBase
25719 20623
25720},{"inherits":163,"safe-buffer":247,"stream":263}],175:[function(require,module,exports){ 20624},{"inherits":107,"safe-buffer":156,"stream":172}],119:[function(require,module,exports){
25721var bn = require('bn.js'); 20625var bn = require('bn.js');
25722var brorand = require('brorand'); 20626var brorand = require('brorand');
25723 20627
@@ -25834,7 +20738,7 @@ MillerRabin.prototype.getDivisor = function getDivisor(n, k) {
25834 return false; 20738 return false;
25835}; 20739};
25836 20740
25837},{"bn.js":75,"brorand":76}],176:[function(require,module,exports){ 20741},{"bn.js":21,"brorand":22}],120:[function(require,module,exports){
25838module.exports = assert; 20742module.exports = assert;
25839 20743
25840function assert(val, msg) { 20744function assert(val, msg) {
@@ -25847,7 +20751,7 @@ assert.equal = function assertEqual(l, r, msg) {
25847 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); 20751 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
25848}; 20752};
25849 20753
25850},{}],177:[function(require,module,exports){ 20754},{}],121:[function(require,module,exports){
25851'use strict'; 20755'use strict';
25852 20756
25853var utils = exports; 20757var utils = exports;
@@ -25907,7 +20811,7 @@ utils.encode = function encode(arr, enc) {
25907 return arr; 20811 return arr;
25908}; 20812};
25909 20813
25910},{}],178:[function(require,module,exports){ 20814},{}],122:[function(require,module,exports){
25911module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb", 20815module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb",
25912"2.16.840.1.101.3.4.1.2": "aes-128-cbc", 20816"2.16.840.1.101.3.4.1.2": "aes-128-cbc",
25913"2.16.840.1.101.3.4.1.3": "aes-128-ofb", 20817"2.16.840.1.101.3.4.1.3": "aes-128-ofb",
@@ -25921,7 +20825,7 @@ module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb",
25921"2.16.840.1.101.3.4.1.43": "aes-256-ofb", 20825"2.16.840.1.101.3.4.1.43": "aes-256-ofb",
25922"2.16.840.1.101.3.4.1.44": "aes-256-cfb" 20826"2.16.840.1.101.3.4.1.44": "aes-256-cfb"
25923} 20827}
25924},{}],179:[function(require,module,exports){ 20828},{}],123:[function(require,module,exports){
25925// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js 20829// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js
25926// Fedor, you are amazing. 20830// Fedor, you are amazing.
25927'use strict' 20831'use strict'
@@ -26045,7 +20949,7 @@ exports.signature = asn1.define('signature', function () {
26045 ) 20949 )
26046}) 20950})
26047 20951
26048},{"./certificate":180,"asn1.js":32}],180:[function(require,module,exports){ 20952},{"./certificate":124,"asn1.js":3}],124:[function(require,module,exports){
26049// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js 20953// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js
26050// thanks to @Rantanen 20954// thanks to @Rantanen
26051 20955
@@ -26135,7 +21039,7 @@ var X509Certificate = asn.define('X509Certificate', function () {
26135 21039
26136module.exports = X509Certificate 21040module.exports = X509Certificate
26137 21041
26138},{"asn1.js":32}],181:[function(require,module,exports){ 21042},{"asn1.js":3}],125:[function(require,module,exports){
26139(function (Buffer){ 21043(function (Buffer){
26140// adapted from https://github.com/apatil/pemstrip 21044// adapted from https://github.com/apatil/pemstrip
26141var findProc = /Proc-Type: 4,ENCRYPTED\n\r?DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\n\r?\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?/m 21045var findProc = /Proc-Type: 4,ENCRYPTED\n\r?DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\n\r?\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?/m
@@ -26169,7 +21073,7 @@ module.exports = function (okey, password) {
26169} 21073}
26170 21074
26171}).call(this,require("buffer").Buffer) 21075}).call(this,require("buffer").Buffer)
26172},{"browserify-aes":80,"buffer":107,"evp_bytestokey":144}],182:[function(require,module,exports){ 21076},{"browserify-aes":26,"buffer":53,"evp_bytestokey":90}],126:[function(require,module,exports){
26173(function (Buffer){ 21077(function (Buffer){
26174var asn1 = require('./asn1') 21078var asn1 = require('./asn1')
26175var aesid = require('./aesid.json') 21079var aesid = require('./aesid.json')
@@ -26279,241 +21183,13 @@ function decrypt (data, password) {
26279} 21183}
26280 21184
26281}).call(this,require("buffer").Buffer) 21185}).call(this,require("buffer").Buffer)
26282},{"./aesid.json":178,"./asn1":179,"./fixProc":181,"browserify-aes":80,"buffer":107,"pbkdf2":184}],183:[function(require,module,exports){ 21186},{"./aesid.json":122,"./asn1":123,"./fixProc":125,"browserify-aes":26,"buffer":53,"pbkdf2":127}],127:[function(require,module,exports){
26283(function (process){
26284// Copyright Joyent, Inc. and other Node contributors.
26285//
26286// Permission is hereby granted, free of charge, to any person obtaining a
26287// copy of this software and associated documentation files (the
26288// "Software"), to deal in the Software without restriction, including
26289// without limitation the rights to use, copy, modify, merge, publish,
26290// distribute, sublicense, and/or sell copies of the Software, and to permit
26291// persons to whom the Software is furnished to do so, subject to the
26292// following conditions:
26293//
26294// The above copyright notice and this permission notice shall be included
26295// in all copies or substantial portions of the Software.
26296//
26297// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
26298// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26299// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
26300// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
26301// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
26302// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
26303// USE OR OTHER DEALINGS IN THE SOFTWARE.
26304
26305// resolves . and .. elements in a path array with directory names there
26306// must be no slashes, empty elements, or device names (c:\) in the array
26307// (so also no leading and trailing slashes - it does not distinguish
26308// relative and absolute paths)
26309function normalizeArray(parts, allowAboveRoot) {
26310 // if the path tries to go above the root, `up` ends up > 0
26311 var up = 0;
26312 for (var i = parts.length - 1; i >= 0; i--) {
26313 var last = parts[i];
26314 if (last === '.') {
26315 parts.splice(i, 1);
26316 } else if (last === '..') {
26317 parts.splice(i, 1);
26318 up++;
26319 } else if (up) {
26320 parts.splice(i, 1);
26321 up--;
26322 }
26323 }
26324
26325 // if the path is allowed to go above the root, restore leading ..s
26326 if (allowAboveRoot) {
26327 for (; up--; up) {
26328 parts.unshift('..');
26329 }
26330 }
26331
26332 return parts;
26333}
26334
26335// Split a filename into [root, dir, basename, ext], unix version
26336// 'root' is just a slash, or nothing.
26337var splitPathRe =
26338 /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
26339var splitPath = function(filename) {
26340 return splitPathRe.exec(filename).slice(1);
26341};
26342
26343// path.resolve([from ...], to)
26344// posix version
26345exports.resolve = function() {
26346 var resolvedPath = '',
26347 resolvedAbsolute = false;
26348
26349 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
26350 var path = (i >= 0) ? arguments[i] : process.cwd();
26351
26352 // Skip empty and invalid entries
26353 if (typeof path !== 'string') {
26354 throw new TypeError('Arguments to path.resolve must be strings');
26355 } else if (!path) {
26356 continue;
26357 }
26358
26359 resolvedPath = path + '/' + resolvedPath;
26360 resolvedAbsolute = path.charAt(0) === '/';
26361 }
26362
26363 // At this point the path should be resolved to a full absolute path, but
26364 // handle relative paths to be safe (might happen when process.cwd() fails)
26365
26366 // Normalize the path
26367 resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
26368 return !!p;
26369 }), !resolvedAbsolute).join('/');
26370
26371 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
26372};
26373
26374// path.normalize(path)
26375// posix version
26376exports.normalize = function(path) {
26377 var isAbsolute = exports.isAbsolute(path),
26378 trailingSlash = substr(path, -1) === '/';
26379
26380 // Normalize the path
26381 path = normalizeArray(filter(path.split('/'), function(p) {
26382 return !!p;
26383 }), !isAbsolute).join('/');
26384
26385 if (!path && !isAbsolute) {
26386 path = '.';
26387 }
26388 if (path && trailingSlash) {
26389 path += '/';
26390 }
26391
26392 return (isAbsolute ? '/' : '') + path;
26393};
26394
26395// posix version
26396exports.isAbsolute = function(path) {
26397 return path.charAt(0) === '/';
26398};
26399
26400// posix version
26401exports.join = function() {
26402 var paths = Array.prototype.slice.call(arguments, 0);
26403 return exports.normalize(filter(paths, function(p, index) {
26404 if (typeof p !== 'string') {
26405 throw new TypeError('Arguments to path.join must be strings');
26406 }
26407 return p;
26408 }).join('/'));
26409};
26410
26411
26412// path.relative(from, to)
26413// posix version
26414exports.relative = function(from, to) {
26415 from = exports.resolve(from).substr(1);
26416 to = exports.resolve(to).substr(1);
26417
26418 function trim(arr) {
26419 var start = 0;
26420 for (; start < arr.length; start++) {
26421 if (arr[start] !== '') break;
26422 }
26423
26424 var end = arr.length - 1;
26425 for (; end >= 0; end--) {
26426 if (arr[end] !== '') break;
26427 }
26428
26429 if (start > end) return [];
26430 return arr.slice(start, end - start + 1);
26431 }
26432
26433 var fromParts = trim(from.split('/'));
26434 var toParts = trim(to.split('/'));
26435
26436 var length = Math.min(fromParts.length, toParts.length);
26437 var samePartsLength = length;
26438 for (var i = 0; i < length; i++) {
26439 if (fromParts[i] !== toParts[i]) {
26440 samePartsLength = i;
26441 break;
26442 }
26443 }
26444
26445 var outputParts = [];
26446 for (var i = samePartsLength; i < fromParts.length; i++) {
26447 outputParts.push('..');
26448 }
26449
26450 outputParts = outputParts.concat(toParts.slice(samePartsLength));
26451
26452 return outputParts.join('/');
26453};
26454
26455exports.sep = '/';
26456exports.delimiter = ':';
26457
26458exports.dirname = function(path) {
26459 var result = splitPath(path),
26460 root = result[0],
26461 dir = result[1];
26462
26463 if (!root && !dir) {
26464 // No dirname whatsoever
26465 return '.';
26466 }
26467
26468 if (dir) {
26469 // It has a dirname, strip trailing slash
26470 dir = dir.substr(0, dir.length - 1);
26471 }
26472
26473 return root + dir;
26474};
26475
26476
26477exports.basename = function(path, ext) {
26478 var f = splitPath(path)[2];
26479 // TODO: make this comparison case-insensitive on windows?
26480 if (ext && f.substr(-1 * ext.length) === ext) {
26481 f = f.substr(0, f.length - ext.length);
26482 }
26483 return f;
26484};
26485
26486
26487exports.extname = function(path) {
26488 return splitPath(path)[3];
26489};
26490
26491function filter (xs, f) {
26492 if (xs.filter) return xs.filter(f);
26493 var res = [];
26494 for (var i = 0; i < xs.length; i++) {
26495 if (f(xs[i], i, xs)) res.push(xs[i]);
26496 }
26497 return res;
26498}
26499
26500// String.prototype.substr - negative index don't work in IE8
26501var substr = 'ab'.substr(-1) === 'b'
26502 ? function (str, start, len) { return str.substr(start, len) }
26503 : function (str, start, len) {
26504 if (start < 0) start = str.length + start;
26505 return str.substr(start, len);
26506 }
26507;
26508
26509}).call(this,require('_process'))
26510},{"_process":190}],184:[function(require,module,exports){
26511 21187
26512exports.pbkdf2 = require('./lib/async') 21188exports.pbkdf2 = require('./lib/async')
26513 21189
26514exports.pbkdf2Sync = require('./lib/sync') 21190exports.pbkdf2Sync = require('./lib/sync')
26515 21191
26516},{"./lib/async":185,"./lib/sync":188}],185:[function(require,module,exports){ 21192},{"./lib/async":128,"./lib/sync":131}],128:[function(require,module,exports){
26517(function (process,global){ 21193(function (process,global){
26518var checkParameters = require('./precondition') 21194var checkParameters = require('./precondition')
26519var defaultEncoding = require('./default-encoding') 21195var defaultEncoding = require('./default-encoding')
@@ -26615,7 +21291,7 @@ module.exports = function (password, salt, iterations, keylen, digest, callback)
26615} 21291}
26616 21292
26617}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 21293}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
26618},{"./default-encoding":186,"./precondition":187,"./sync":188,"_process":190,"safe-buffer":247}],186:[function(require,module,exports){ 21294},{"./default-encoding":129,"./precondition":130,"./sync":131,"_process":133,"safe-buffer":156}],129:[function(require,module,exports){
26619(function (process){ 21295(function (process){
26620var defaultEncoding 21296var defaultEncoding
26621/* istanbul ignore next */ 21297/* istanbul ignore next */
@@ -26629,7 +21305,7 @@ if (process.browser) {
26629module.exports = defaultEncoding 21305module.exports = defaultEncoding
26630 21306
26631}).call(this,require('_process')) 21307}).call(this,require('_process'))
26632},{"_process":190}],187:[function(require,module,exports){ 21308},{"_process":133}],130:[function(require,module,exports){
26633var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs 21309var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs
26634module.exports = function (iterations, keylen) { 21310module.exports = function (iterations, keylen) {
26635 if (typeof iterations !== 'number') { 21311 if (typeof iterations !== 'number') {
@@ -26649,7 +21325,7 @@ module.exports = function (iterations, keylen) {
26649 } 21325 }
26650} 21326}
26651 21327
26652},{}],188:[function(require,module,exports){ 21328},{}],131:[function(require,module,exports){
26653var md5 = require('create-hash/md5') 21329var md5 = require('create-hash/md5')
26654var rmd160 = require('ripemd160') 21330var rmd160 = require('ripemd160')
26655var sha = require('sha.js') 21331var sha = require('sha.js')
@@ -26752,7 +21428,7 @@ function pbkdf2 (password, salt, iterations, keylen, digest) {
26752 21428
26753module.exports = pbkdf2 21429module.exports = pbkdf2
26754 21430
26755},{"./default-encoding":186,"./precondition":187,"create-hash/md5":113,"ripemd160":246,"safe-buffer":247,"sha.js":256}],189:[function(require,module,exports){ 21431},{"./default-encoding":129,"./precondition":130,"create-hash/md5":59,"ripemd160":155,"safe-buffer":156,"sha.js":165}],132:[function(require,module,exports){
26756(function (process){ 21432(function (process){
26757'use strict'; 21433'use strict';
26758 21434
@@ -26799,7 +21475,7 @@ function nextTick(fn, arg1, arg2, arg3) {
26799} 21475}
26800 21476
26801}).call(this,require('_process')) 21477}).call(this,require('_process'))
26802},{"_process":190}],190:[function(require,module,exports){ 21478},{"_process":133}],133:[function(require,module,exports){
26803// shim for using process in browser 21479// shim for using process in browser
26804var process = module.exports = {}; 21480var process = module.exports = {};
26805 21481
@@ -26985,7608 +21661,7 @@ process.chdir = function (dir) {
26985}; 21661};
26986process.umask = function() { return 0; }; 21662process.umask = function() { return 0; };
26987 21663
26988},{}],191:[function(require,module,exports){ 21664},{}],134:[function(require,module,exports){
26989// full library entry point.
26990
26991"use strict";
26992module.exports = require("./src/index");
26993
26994},{"./src/index":200}],192:[function(require,module,exports){
26995"use strict";
26996module.exports = common;
26997
26998var commonRe = /\/|\./;
26999
27000/**
27001 * Provides common type definitions.
27002 * Can also be used to provide additional google types or your own custom types.
27003 * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name
27004 * @param {Object.<string,*>} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition
27005 * @returns {undefined}
27006 * @property {INamespace} google/protobuf/any.proto Any
27007 * @property {INamespace} google/protobuf/duration.proto Duration
27008 * @property {INamespace} google/protobuf/empty.proto Empty
27009 * @property {INamespace} google/protobuf/field_mask.proto FieldMask
27010 * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue
27011 * @property {INamespace} google/protobuf/timestamp.proto Timestamp
27012 * @property {INamespace} google/protobuf/wrappers.proto Wrappers
27013 * @example
27014 * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension)
27015 * protobuf.common("descriptor", descriptorJson);
27016 *
27017 * // manually provides a custom definition (uses my.foo namespace)
27018 * protobuf.common("my/foo/bar.proto", myFooBarJson);
27019 */
27020function common(name, json) {
27021 if (!commonRe.test(name)) {
27022 name = "google/protobuf/" + name + ".proto";
27023 json = { nested: { google: { nested: { protobuf: { nested: json } } } } };
27024 }
27025 common[name] = json;
27026}
27027
27028// Not provided because of limited use (feel free to discuss or to provide yourself):
27029//
27030// google/protobuf/descriptor.proto
27031// google/protobuf/source_context.proto
27032// google/protobuf/type.proto
27033//
27034// Stripped and pre-parsed versions of these non-bundled files are instead available as part of
27035// the repository or package within the google/protobuf directory.
27036
27037common("any", {
27038
27039 /**
27040 * Properties of a google.protobuf.Any message.
27041 * @interface IAny
27042 * @type {Object}
27043 * @property {string} [typeUrl]
27044 * @property {Uint8Array} [bytes]
27045 * @memberof common
27046 */
27047 Any: {
27048 fields: {
27049 type_url: {
27050 type: "string",
27051 id: 1
27052 },
27053 value: {
27054 type: "bytes",
27055 id: 2
27056 }
27057 }
27058 }
27059});
27060
27061var timeType;
27062
27063common("duration", {
27064
27065 /**
27066 * Properties of a google.protobuf.Duration message.
27067 * @interface IDuration
27068 * @type {Object}
27069 * @property {number|Long} [seconds]
27070 * @property {number} [nanos]
27071 * @memberof common
27072 */
27073 Duration: timeType = {
27074 fields: {
27075 seconds: {
27076 type: "int64",
27077 id: 1
27078 },
27079 nanos: {
27080 type: "int32",
27081 id: 2
27082 }
27083 }
27084 }
27085});
27086
27087common("timestamp", {
27088
27089 /**
27090 * Properties of a google.protobuf.Timestamp message.
27091 * @interface ITimestamp
27092 * @type {Object}
27093 * @property {number|Long} [seconds]
27094 * @property {number} [nanos]
27095 * @memberof common
27096 */
27097 Timestamp: timeType
27098});
27099
27100common("empty", {
27101
27102 /**
27103 * Properties of a google.protobuf.Empty message.
27104 * @interface IEmpty
27105 * @memberof common
27106 */
27107 Empty: {
27108 fields: {}
27109 }
27110});
27111
27112common("struct", {
27113
27114 /**
27115 * Properties of a google.protobuf.Struct message.
27116 * @interface IStruct
27117 * @type {Object}
27118 * @property {Object.<string,IValue>} [fields]
27119 * @memberof common
27120 */
27121 Struct: {
27122 fields: {
27123 fields: {
27124 keyType: "string",
27125 type: "Value",
27126 id: 1
27127 }
27128 }
27129 },
27130
27131 /**
27132 * Properties of a google.protobuf.Value message.
27133 * @interface IValue
27134 * @type {Object}
27135 * @property {string} [kind]
27136 * @property {0} [nullValue]
27137 * @property {number} [numberValue]
27138 * @property {string} [stringValue]
27139 * @property {boolean} [boolValue]
27140 * @property {IStruct} [structValue]
27141 * @property {IListValue} [listValue]
27142 * @memberof common
27143 */
27144 Value: {
27145 oneofs: {
27146 kind: {
27147 oneof: [
27148 "nullValue",
27149 "numberValue",
27150 "stringValue",
27151 "boolValue",
27152 "structValue",
27153 "listValue"
27154 ]
27155 }
27156 },
27157 fields: {
27158 nullValue: {
27159 type: "NullValue",
27160 id: 1
27161 },
27162 numberValue: {
27163 type: "double",
27164 id: 2
27165 },
27166 stringValue: {
27167 type: "string",
27168 id: 3
27169 },
27170 boolValue: {
27171 type: "bool",
27172 id: 4
27173 },
27174 structValue: {
27175 type: "Struct",
27176 id: 5
27177 },
27178 listValue: {
27179 type: "ListValue",
27180 id: 6
27181 }
27182 }
27183 },
27184
27185 NullValue: {
27186 values: {
27187 NULL_VALUE: 0
27188 }
27189 },
27190
27191 /**
27192 * Properties of a google.protobuf.ListValue message.
27193 * @interface IListValue
27194 * @type {Object}
27195 * @property {Array.<IValue>} [values]
27196 * @memberof common
27197 */
27198 ListValue: {
27199 fields: {
27200 values: {
27201 rule: "repeated",
27202 type: "Value",
27203 id: 1
27204 }
27205 }
27206 }
27207});
27208
27209common("wrappers", {
27210
27211 /**
27212 * Properties of a google.protobuf.DoubleValue message.
27213 * @interface IDoubleValue
27214 * @type {Object}
27215 * @property {number} [value]
27216 * @memberof common
27217 */
27218 DoubleValue: {
27219 fields: {
27220 value: {
27221 type: "double",
27222 id: 1
27223 }
27224 }
27225 },
27226
27227 /**
27228 * Properties of a google.protobuf.FloatValue message.
27229 * @interface IFloatValue
27230 * @type {Object}
27231 * @property {number} [value]
27232 * @memberof common
27233 */
27234 FloatValue: {
27235 fields: {
27236 value: {
27237 type: "float",
27238 id: 1
27239 }
27240 }
27241 },
27242
27243 /**
27244 * Properties of a google.protobuf.Int64Value message.
27245 * @interface IInt64Value
27246 * @type {Object}
27247 * @property {number|Long} [value]
27248 * @memberof common
27249 */
27250 Int64Value: {
27251 fields: {
27252 value: {
27253 type: "int64",
27254 id: 1
27255 }
27256 }
27257 },
27258
27259 /**
27260 * Properties of a google.protobuf.UInt64Value message.
27261 * @interface IUInt64Value
27262 * @type {Object}
27263 * @property {number|Long} [value]
27264 * @memberof common
27265 */
27266 UInt64Value: {
27267 fields: {
27268 value: {
27269 type: "uint64",
27270 id: 1
27271 }
27272 }
27273 },
27274
27275 /**
27276 * Properties of a google.protobuf.Int32Value message.
27277 * @interface IInt32Value
27278 * @type {Object}
27279 * @property {number} [value]
27280 * @memberof common
27281 */
27282 Int32Value: {
27283 fields: {
27284 value: {
27285 type: "int32",
27286 id: 1
27287 }
27288 }
27289 },
27290
27291 /**
27292 * Properties of a google.protobuf.UInt32Value message.
27293 * @interface IUInt32Value
27294 * @type {Object}
27295 * @property {number} [value]
27296 * @memberof common
27297 */
27298 UInt32Value: {
27299 fields: {
27300 value: {
27301 type: "uint32",
27302 id: 1
27303 }
27304 }
27305 },
27306
27307 /**
27308 * Properties of a google.protobuf.BoolValue message.
27309 * @interface IBoolValue
27310 * @type {Object}
27311 * @property {boolean} [value]
27312 * @memberof common
27313 */
27314 BoolValue: {
27315 fields: {
27316 value: {
27317 type: "bool",
27318 id: 1
27319 }
27320 }
27321 },
27322
27323 /**
27324 * Properties of a google.protobuf.StringValue message.
27325 * @interface IStringValue
27326 * @type {Object}
27327 * @property {string} [value]
27328 * @memberof common
27329 */
27330 StringValue: {
27331 fields: {
27332 value: {
27333 type: "string",
27334 id: 1
27335 }
27336 }
27337 },
27338
27339 /**
27340 * Properties of a google.protobuf.BytesValue message.
27341 * @interface IBytesValue
27342 * @type {Object}
27343 * @property {Uint8Array} [value]
27344 * @memberof common
27345 */
27346 BytesValue: {
27347 fields: {
27348 value: {
27349 type: "bytes",
27350 id: 1
27351 }
27352 }
27353 }
27354});
27355
27356common("field_mask", {
27357
27358 /**
27359 * Properties of a google.protobuf.FieldMask message.
27360 * @interface IDoubleValue
27361 * @type {Object}
27362 * @property {number} [value]
27363 * @memberof common
27364 */
27365 FieldMask: {
27366 fields: {
27367 paths: {
27368 rule: "repeated",
27369 type: "string",
27370 id: 1
27371 }
27372 }
27373 }
27374});
27375
27376/**
27377 * Gets the root definition of the specified common proto file.
27378 *
27379 * Bundled definitions are:
27380 * - google/protobuf/any.proto
27381 * - google/protobuf/duration.proto
27382 * - google/protobuf/empty.proto
27383 * - google/protobuf/field_mask.proto
27384 * - google/protobuf/struct.proto
27385 * - google/protobuf/timestamp.proto
27386 * - google/protobuf/wrappers.proto
27387 *
27388 * @param {string} file Proto file name
27389 * @returns {INamespace|null} Root definition or `null` if not defined
27390 */
27391common.get = function get(file) {
27392 return common[file] || null;
27393};
27394
27395},{}],193:[function(require,module,exports){
27396"use strict";
27397/**
27398 * Runtime message from/to plain object converters.
27399 * @namespace
27400 */
27401var converter = exports;
27402
27403var Enum = require("./enum"),
27404 util = require("./util");
27405
27406/**
27407 * Generates a partial value fromObject conveter.
27408 * @param {Codegen} gen Codegen instance
27409 * @param {Field} field Reflected field
27410 * @param {number} fieldIndex Field index
27411 * @param {string} prop Property reference
27412 * @returns {Codegen} Codegen instance
27413 * @ignore
27414 */
27415function genValuePartial_fromObject(gen, field, fieldIndex, prop) {
27416 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
27417 if (field.resolvedType) {
27418 if (field.resolvedType instanceof Enum) { gen
27419 ("switch(d%s){", prop);
27420 for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {
27421 if (field.repeated && values[keys[i]] === field.typeDefault) gen
27422 ("default:");
27423 gen
27424 ("case%j:", keys[i])
27425 ("case %i:", values[keys[i]])
27426 ("m%s=%j", prop, values[keys[i]])
27427 ("break");
27428 } gen
27429 ("}");
27430 } else gen
27431 ("if(typeof d%s!==\"object\")", prop)
27432 ("throw TypeError(%j)", field.fullName + ": object expected")
27433 ("m%s=types[%i].fromObject(d%s)", prop, fieldIndex, prop);
27434 } else {
27435 var isUnsigned = false;
27436 switch (field.type) {
27437 case "double":
27438 case "float": gen
27439 ("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity"
27440 break;
27441 case "uint32":
27442 case "fixed32": gen
27443 ("m%s=d%s>>>0", prop, prop);
27444 break;
27445 case "int32":
27446 case "sint32":
27447 case "sfixed32": gen
27448 ("m%s=d%s|0", prop, prop);
27449 break;
27450 case "uint64":
27451 isUnsigned = true;
27452 // eslint-disable-line no-fallthrough
27453 case "int64":
27454 case "sint64":
27455 case "fixed64":
27456 case "sfixed64": gen
27457 ("if(util.Long)")
27458 ("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned)
27459 ("else if(typeof d%s===\"string\")", prop)
27460 ("m%s=parseInt(d%s,10)", prop, prop)
27461 ("else if(typeof d%s===\"number\")", prop)
27462 ("m%s=d%s", prop, prop)
27463 ("else if(typeof d%s===\"object\")", prop)
27464 ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : "");
27465 break;
27466 case "bytes": gen
27467 ("if(typeof d%s===\"string\")", prop)
27468 ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop)
27469 ("else if(d%s.length)", prop)
27470 ("m%s=d%s", prop, prop);
27471 break;
27472 case "string": gen
27473 ("m%s=String(d%s)", prop, prop);
27474 break;
27475 case "bool": gen
27476 ("m%s=Boolean(d%s)", prop, prop);
27477 break;
27478 /* default: gen
27479 ("m%s=d%s", prop, prop);
27480 break; */
27481 }
27482 }
27483 return gen;
27484 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
27485}
27486
27487/**
27488 * Generates a plain object to runtime message converter specific to the specified message type.
27489 * @param {Type} mtype Message type
27490 * @returns {Codegen} Codegen instance
27491 */
27492converter.fromObject = function fromObject(mtype) {
27493 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
27494 var fields = mtype.fieldsArray;
27495 var gen = util.codegen(["d"], mtype.name + "$fromObject")
27496 ("if(d instanceof this.ctor)")
27497 ("return d");
27498 if (!fields.length) return gen
27499 ("return new this.ctor");
27500 gen
27501 ("var m=new this.ctor");
27502 for (var i = 0; i < fields.length; ++i) {
27503 var field = fields[i].resolve(),
27504 prop = util.safeProp(field.name);
27505
27506 // Map fields
27507 if (field.map) { gen
27508 ("if(d%s){", prop)
27509 ("if(typeof d%s!==\"object\")", prop)
27510 ("throw TypeError(%j)", field.fullName + ": object expected")
27511 ("m%s={}", prop)
27512 ("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){", prop);
27513 genValuePartial_fromObject(gen, field, /* not sorted */ i, prop + "[ks[i]]")
27514 ("}")
27515 ("}");
27516
27517 // Repeated fields
27518 } else if (field.repeated) { gen
27519 ("if(d%s){", prop)
27520 ("if(!Array.isArray(d%s))", prop)
27521 ("throw TypeError(%j)", field.fullName + ": array expected")
27522 ("m%s=[]", prop)
27523 ("for(var i=0;i<d%s.length;++i){", prop);
27524 genValuePartial_fromObject(gen, field, /* not sorted */ i, prop + "[i]")
27525 ("}")
27526 ("}");
27527
27528 // Non-repeated fields
27529 } else {
27530 if (!(field.resolvedType instanceof Enum)) gen // no need to test for null/undefined if an enum (uses switch)
27531 ("if(d%s!=null){", prop); // !== undefined && !== null
27532 genValuePartial_fromObject(gen, field, /* not sorted */ i, prop);
27533 if (!(field.resolvedType instanceof Enum)) gen
27534 ("}");
27535 }
27536 } return gen
27537 ("return m");
27538 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
27539};
27540
27541/**
27542 * Generates a partial value toObject converter.
27543 * @param {Codegen} gen Codegen instance
27544 * @param {Field} field Reflected field
27545 * @param {number} fieldIndex Field index
27546 * @param {string} prop Property reference
27547 * @returns {Codegen} Codegen instance
27548 * @ignore
27549 */
27550function genValuePartial_toObject(gen, field, fieldIndex, prop) {
27551 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
27552 if (field.resolvedType) {
27553 if (field.resolvedType instanceof Enum) gen
27554 ("d%s=o.enums===String?types[%i].values[m%s]:m%s", prop, fieldIndex, prop, prop);
27555 else gen
27556 ("d%s=types[%i].toObject(m%s,o)", prop, fieldIndex, prop);
27557 } else {
27558 var isUnsigned = false;
27559 switch (field.type) {
27560 case "double":
27561 case "float": gen
27562 ("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s", prop, prop, prop, prop);
27563 break;
27564 case "uint64":
27565 isUnsigned = true;
27566 // eslint-disable-line no-fallthrough
27567 case "int64":
27568 case "sint64":
27569 case "fixed64":
27570 case "sfixed64": gen
27571 ("if(typeof m%s===\"number\")", prop)
27572 ("d%s=o.longs===String?String(m%s):m%s", prop, prop, prop)
27573 ("else") // Long-like
27574 ("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true": "", prop);
27575 break;
27576 case "bytes": gen
27577 ("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop);
27578 break;
27579 default: gen
27580 ("d%s=m%s", prop, prop);
27581 break;
27582 }
27583 }
27584 return gen;
27585 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
27586}
27587
27588/**
27589 * Generates a runtime message to plain object converter specific to the specified message type.
27590 * @param {Type} mtype Message type
27591 * @returns {Codegen} Codegen instance
27592 */
27593converter.toObject = function toObject(mtype) {
27594 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
27595 var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);
27596 if (!fields.length)
27597 return util.codegen()("return {}");
27598 var gen = util.codegen(["m", "o"], mtype.name + "$toObject")
27599 ("if(!o)")
27600 ("o={}")
27601 ("var d={}");
27602
27603 var repeatedFields = [],
27604 mapFields = [],
27605 normalFields = [],
27606 i = 0;
27607 for (; i < fields.length; ++i)
27608 if (!fields[i].partOf)
27609 ( fields[i].resolve().repeated ? repeatedFields
27610 : fields[i].map ? mapFields
27611 : normalFields).push(fields[i]);
27612
27613 if (repeatedFields.length) { gen
27614 ("if(o.arrays||o.defaults){");
27615 for (i = 0; i < repeatedFields.length; ++i) gen
27616 ("d%s=[]", util.safeProp(repeatedFields[i].name));
27617 gen
27618 ("}");
27619 }
27620
27621 if (mapFields.length) { gen
27622 ("if(o.objects||o.defaults){");
27623 for (i = 0; i < mapFields.length; ++i) gen
27624 ("d%s={}", util.safeProp(mapFields[i].name));
27625 gen
27626 ("}");
27627 }
27628
27629 if (normalFields.length) { gen
27630 ("if(o.defaults){");
27631 for (i = 0; i < normalFields.length; ++i) {
27632 var field = normalFields[i],
27633 prop = util.safeProp(field.name);
27634 if (field.resolvedType instanceof Enum) gen
27635 ("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);
27636 else if (field.long) gen
27637 ("if(util.Long){")
27638 ("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)
27639 ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop)
27640 ("}else")
27641 ("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber());
27642 else if (field.bytes) gen
27643 ("d%s=o.bytes===String?%j:%s", prop, String.fromCharCode.apply(String, field.typeDefault), "[" + Array.prototype.slice.call(field.typeDefault).join(",") + "]");
27644 else gen
27645 ("d%s=%j", prop, field.typeDefault); // also messages (=null)
27646 } gen
27647 ("}");
27648 }
27649 var hasKs2 = false;
27650 for (i = 0; i < fields.length; ++i) {
27651 var field = fields[i],
27652 index = mtype._fieldsArray.indexOf(field),
27653 prop = util.safeProp(field.name);
27654 if (field.map) {
27655 if (!hasKs2) { hasKs2 = true; gen
27656 ("var ks2");
27657 } gen
27658 ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop)
27659 ("d%s={}", prop)
27660 ("for(var j=0;j<ks2.length;++j){");
27661 genValuePartial_toObject(gen, field, /* sorted */ index, prop + "[ks2[j]]")
27662 ("}");
27663 } else if (field.repeated) { gen
27664 ("if(m%s&&m%s.length){", prop, prop)
27665 ("d%s=[]", prop)
27666 ("for(var j=0;j<m%s.length;++j){", prop);
27667 genValuePartial_toObject(gen, field, /* sorted */ index, prop + "[j]")
27668 ("}");
27669 } else { gen
27670 ("if(m%s!=null&&m.hasOwnProperty(%j)){", prop, field.name); // !== undefined && !== null
27671 genValuePartial_toObject(gen, field, /* sorted */ index, prop);
27672 if (field.partOf) gen
27673 ("if(o.oneofs)")
27674 ("d%s=%j", util.safeProp(field.partOf.name), field.name);
27675 }
27676 gen
27677 ("}");
27678 }
27679 return gen
27680 ("return d");
27681 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
27682};
27683
27684},{"./enum":196,"./util":218}],194:[function(require,module,exports){
27685"use strict";
27686module.exports = decoder;
27687
27688var Enum = require("./enum"),
27689 types = require("./types"),
27690 util = require("./util");
27691
27692function missing(field) {
27693 return "missing required '" + field.name + "'";
27694}
27695
27696/**
27697 * Generates a decoder specific to the specified message type.
27698 * @param {Type} mtype Message type
27699 * @returns {Codegen} Codegen instance
27700 */
27701function decoder(mtype) {
27702 /* eslint-disable no-unexpected-multiline */
27703 var gen = util.codegen(["r", "l"], mtype.name + "$decode")
27704 ("if(!(r instanceof Reader))")
27705 ("r=Reader.create(r)")
27706 ("var c=l===undefined?r.len:r.pos+l,m=new this.ctor" + (mtype.fieldsArray.filter(function(field) { return field.map; }).length ? ",k" : ""))
27707 ("while(r.pos<c){")
27708 ("var t=r.uint32()");
27709 if (mtype.group) gen
27710 ("if((t&7)===4)")
27711 ("break");
27712 gen
27713 ("switch(t>>>3){");
27714
27715 var i = 0;
27716 for (; i < /* initializes */ mtype.fieldsArray.length; ++i) {
27717 var field = mtype._fieldsArray[i].resolve(),
27718 type = field.resolvedType instanceof Enum ? "int32" : field.type,
27719 ref = "m" + util.safeProp(field.name); gen
27720 ("case %i:", field.id);
27721
27722 // Map fields
27723 if (field.map) { gen
27724 ("r.skip().pos++") // assumes id 1 + key wireType
27725 ("if(%s===util.emptyObject)", ref)
27726 ("%s={}", ref)
27727 ("k=r.%s()", field.keyType)
27728 ("r.pos++"); // assumes id 2 + value wireType
27729 if (types.long[field.keyType] !== undefined) {
27730 if (types.basic[type] === undefined) gen
27731 ("%s[typeof k===\"object\"?util.longToHash(k):k]=types[%i].decode(r,r.uint32())", ref, i); // can't be groups
27732 else gen
27733 ("%s[typeof k===\"object\"?util.longToHash(k):k]=r.%s()", ref, type);
27734 } else {
27735 if (types.basic[type] === undefined) gen
27736 ("%s[k]=types[%i].decode(r,r.uint32())", ref, i); // can't be groups
27737 else gen
27738 ("%s[k]=r.%s()", ref, type);
27739 }
27740
27741 // Repeated fields
27742 } else if (field.repeated) { gen
27743
27744 ("if(!(%s&&%s.length))", ref, ref)
27745 ("%s=[]", ref);
27746
27747 // Packable (always check for forward and backward compatiblity)
27748 if (types.packed[type] !== undefined) gen
27749 ("if((t&7)===2){")
27750 ("var c2=r.uint32()+r.pos")
27751 ("while(r.pos<c2)")
27752 ("%s.push(r.%s())", ref, type)
27753 ("}else");
27754
27755 // Non-packed
27756 if (types.basic[type] === undefined) gen(field.resolvedType.group
27757 ? "%s.push(types[%i].decode(r))"
27758 : "%s.push(types[%i].decode(r,r.uint32()))", ref, i);
27759 else gen
27760 ("%s.push(r.%s())", ref, type);
27761
27762 // Non-repeated
27763 } else if (types.basic[type] === undefined) gen(field.resolvedType.group
27764 ? "%s=types[%i].decode(r)"
27765 : "%s=types[%i].decode(r,r.uint32())", ref, i);
27766 else gen
27767 ("%s=r.%s()", ref, type);
27768 gen
27769 ("break");
27770 // Unknown fields
27771 } gen
27772 ("default:")
27773 ("r.skipType(t&7)")
27774 ("break")
27775
27776 ("}")
27777 ("}");
27778
27779 // Field presence
27780 for (i = 0; i < mtype._fieldsArray.length; ++i) {
27781 var rfield = mtype._fieldsArray[i];
27782 if (rfield.required) gen
27783 ("if(!m.hasOwnProperty(%j))", rfield.name)
27784 ("throw util.ProtocolError(%j,{instance:m})", missing(rfield));
27785 }
27786
27787 return gen
27788 ("return m");
27789 /* eslint-enable no-unexpected-multiline */
27790}
27791
27792},{"./enum":196,"./types":217,"./util":218}],195:[function(require,module,exports){
27793"use strict";
27794module.exports = encoder;
27795
27796var Enum = require("./enum"),
27797 types = require("./types"),
27798 util = require("./util");
27799
27800/**
27801 * Generates a partial message type encoder.
27802 * @param {Codegen} gen Codegen instance
27803 * @param {Field} field Reflected field
27804 * @param {number} fieldIndex Field index
27805 * @param {string} ref Variable reference
27806 * @returns {Codegen} Codegen instance
27807 * @ignore
27808 */
27809function genTypePartial(gen, field, fieldIndex, ref) {
27810 return field.resolvedType.group
27811 ? gen("types[%i].encode(%s,w.uint32(%i)).uint32(%i)", fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0)
27812 : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0);
27813}
27814
27815/**
27816 * Generates an encoder specific to the specified message type.
27817 * @param {Type} mtype Message type
27818 * @returns {Codegen} Codegen instance
27819 */
27820function encoder(mtype) {
27821 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
27822 var gen = util.codegen(["m", "w"], mtype.name + "$encode")
27823 ("if(!w)")
27824 ("w=Writer.create()");
27825
27826 var i, ref;
27827
27828 // "when a message is serialized its known fields should be written sequentially by field number"
27829 var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);
27830
27831 for (var i = 0; i < fields.length; ++i) {
27832 var field = fields[i].resolve(),
27833 index = mtype._fieldsArray.indexOf(field),
27834 type = field.resolvedType instanceof Enum ? "int32" : field.type,
27835 wireType = types.basic[type];
27836 ref = "m" + util.safeProp(field.name);
27837
27838 // Map fields
27839 if (field.map) {
27840 gen
27841 ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name) // !== undefined && !== null
27842 ("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){", ref)
27843 ("w.uint32(%i).fork().uint32(%i).%s(ks[i])", (field.id << 3 | 2) >>> 0, 8 | types.mapKey[field.keyType], field.keyType);
27844 if (wireType === undefined) gen
27845 ("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); // can't be groups
27846 else gen
27847 (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref);
27848 gen
27849 ("}")
27850 ("}");
27851
27852 // Repeated fields
27853 } else if (field.repeated) { gen
27854 ("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null
27855
27856 // Packed repeated
27857 if (field.packed && types.packed[type] !== undefined) { gen
27858
27859 ("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0)
27860 ("for(var i=0;i<%s.length;++i)", ref)
27861 ("w.%s(%s[i])", type, ref)
27862 ("w.ldelim()");
27863
27864 // Non-packed
27865 } else { gen
27866
27867 ("for(var i=0;i<%s.length;++i)", ref);
27868 if (wireType === undefined)
27869 genTypePartial(gen, field, index, ref + "[i]");
27870 else gen
27871 ("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref);
27872
27873 } gen
27874 ("}");
27875
27876 // Non-repeated
27877 } else {
27878 if (field.optional) gen
27879 ("if(%s!=null&&m.hasOwnProperty(%j))", ref, field.name); // !== undefined && !== null
27880
27881 if (wireType === undefined)
27882 genTypePartial(gen, field, index, ref);
27883 else gen
27884 ("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref);
27885
27886 }
27887 }
27888
27889 return gen
27890 ("return w");
27891 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
27892}
27893},{"./enum":196,"./types":217,"./util":218}],196:[function(require,module,exports){
27894"use strict";
27895module.exports = Enum;
27896
27897// extends ReflectionObject
27898var ReflectionObject = require("./object");
27899((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum";
27900
27901var Namespace = require("./namespace"),
27902 util = require("./util");
27903
27904/**
27905 * Constructs a new enum instance.
27906 * @classdesc Reflected enum.
27907 * @extends ReflectionObject
27908 * @constructor
27909 * @param {string} name Unique name within its namespace
27910 * @param {Object.<string,number>} [values] Enum values as an object, by name
27911 * @param {Object.<string,*>} [options] Declared options
27912 * @param {string} [comment] The comment for this enum
27913 * @param {Object.<string,string>} [comments] The value comments for this enum
27914 */
27915function Enum(name, values, options, comment, comments) {
27916 ReflectionObject.call(this, name, options);
27917
27918 if (values && typeof values !== "object")
27919 throw TypeError("values must be an object");
27920
27921 /**
27922 * Enum values by id.
27923 * @type {Object.<number,string>}
27924 */
27925 this.valuesById = {};
27926
27927 /**
27928 * Enum values by name.
27929 * @type {Object.<string,number>}
27930 */
27931 this.values = Object.create(this.valuesById); // toJSON, marker
27932
27933 /**
27934 * Enum comment text.
27935 * @type {string|null}
27936 */
27937 this.comment = comment;
27938
27939 /**
27940 * Value comment texts, if any.
27941 * @type {Object.<string,string>}
27942 */
27943 this.comments = comments || {};
27944
27945 /**
27946 * Reserved ranges, if any.
27947 * @type {Array.<number[]|string>}
27948 */
27949 this.reserved = undefined; // toJSON
27950
27951 // Note that values inherit valuesById on their prototype which makes them a TypeScript-
27952 // compatible enum. This is used by pbts to write actual enum definitions that work for
27953 // static and reflection code alike instead of emitting generic object definitions.
27954
27955 if (values)
27956 for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)
27957 if (typeof values[keys[i]] === "number") // use forward entries only
27958 this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];
27959}
27960
27961/**
27962 * Enum descriptor.
27963 * @interface IEnum
27964 * @property {Object.<string,number>} values Enum values
27965 * @property {Object.<string,*>} [options] Enum options
27966 */
27967
27968/**
27969 * Constructs an enum from an enum descriptor.
27970 * @param {string} name Enum name
27971 * @param {IEnum} json Enum descriptor
27972 * @returns {Enum} Created enum
27973 * @throws {TypeError} If arguments are invalid
27974 */
27975Enum.fromJSON = function fromJSON(name, json) {
27976 var enm = new Enum(name, json.values, json.options, json.comment, json.comments);
27977 enm.reserved = json.reserved;
27978 return enm;
27979};
27980
27981/**
27982 * Converts this enum to an enum descriptor.
27983 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
27984 * @returns {IEnum} Enum descriptor
27985 */
27986Enum.prototype.toJSON = function toJSON(toJSONOptions) {
27987 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
27988 return util.toObject([
27989 "options" , this.options,
27990 "values" , this.values,
27991 "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined,
27992 "comment" , keepComments ? this.comment : undefined,
27993 "comments" , keepComments ? this.comments : undefined
27994 ]);
27995};
27996
27997/**
27998 * Adds a value to this enum.
27999 * @param {string} name Value name
28000 * @param {number} id Value id
28001 * @param {string} [comment] Comment, if any
28002 * @returns {Enum} `this`
28003 * @throws {TypeError} If arguments are invalid
28004 * @throws {Error} If there is already a value with this name or id
28005 */
28006Enum.prototype.add = function add(name, id, comment) {
28007 // utilized by the parser but not by .fromJSON
28008
28009 if (!util.isString(name))
28010 throw TypeError("name must be a string");
28011
28012 if (!util.isInteger(id))
28013 throw TypeError("id must be an integer");
28014
28015 if (this.values[name] !== undefined)
28016 throw Error("duplicate name '" + name + "' in " + this);
28017
28018 if (this.isReservedId(id))
28019 throw Error("id " + id + " is reserved in " + this);
28020
28021 if (this.isReservedName(name))
28022 throw Error("name '" + name + "' is reserved in " + this);
28023
28024 if (this.valuesById[id] !== undefined) {
28025 if (!(this.options && this.options.allow_alias))
28026 throw Error("duplicate id " + id + " in " + this);
28027 this.values[name] = id;
28028 } else
28029 this.valuesById[this.values[name] = id] = name;
28030
28031 this.comments[name] = comment || null;
28032 return this;
28033};
28034
28035/**
28036 * Removes a value from this enum
28037 * @param {string} name Value name
28038 * @returns {Enum} `this`
28039 * @throws {TypeError} If arguments are invalid
28040 * @throws {Error} If `name` is not a name of this enum
28041 */
28042Enum.prototype.remove = function remove(name) {
28043
28044 if (!util.isString(name))
28045 throw TypeError("name must be a string");
28046
28047 var val = this.values[name];
28048 if (val == null)
28049 throw Error("name '" + name + "' does not exist in " + this);
28050
28051 delete this.valuesById[val];
28052 delete this.values[name];
28053 delete this.comments[name];
28054
28055 return this;
28056};
28057
28058/**
28059 * Tests if the specified id is reserved.
28060 * @param {number} id Id to test
28061 * @returns {boolean} `true` if reserved, otherwise `false`
28062 */
28063Enum.prototype.isReservedId = function isReservedId(id) {
28064 return Namespace.isReservedId(this.reserved, id);
28065};
28066
28067/**
28068 * Tests if the specified name is reserved.
28069 * @param {string} name Name to test
28070 * @returns {boolean} `true` if reserved, otherwise `false`
28071 */
28072Enum.prototype.isReservedName = function isReservedName(name) {
28073 return Namespace.isReservedName(this.reserved, name);
28074};
28075
28076},{"./namespace":204,"./object":205,"./util":218}],197:[function(require,module,exports){
28077"use strict";
28078module.exports = Field;
28079
28080// extends ReflectionObject
28081var ReflectionObject = require("./object");
28082((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field";
28083
28084var Enum = require("./enum"),
28085 types = require("./types"),
28086 util = require("./util");
28087
28088var Type; // cyclic
28089
28090var ruleRe = /^required|optional|repeated$/;
28091
28092/**
28093 * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.
28094 * @name Field
28095 * @classdesc Reflected message field.
28096 * @extends FieldBase
28097 * @constructor
28098 * @param {string} name Unique name within its namespace
28099 * @param {number} id Unique id within its namespace
28100 * @param {string} type Value type
28101 * @param {string|Object.<string,*>} [rule="optional"] Field rule
28102 * @param {string|Object.<string,*>} [extend] Extended type if different from parent
28103 * @param {Object.<string,*>} [options] Declared options
28104 */
28105
28106/**
28107 * Constructs a field from a field descriptor.
28108 * @param {string} name Field name
28109 * @param {IField} json Field descriptor
28110 * @returns {Field} Created field
28111 * @throws {TypeError} If arguments are invalid
28112 */
28113Field.fromJSON = function fromJSON(name, json) {
28114 return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);
28115};
28116
28117/**
28118 * Not an actual constructor. Use {@link Field} instead.
28119 * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.
28120 * @exports FieldBase
28121 * @extends ReflectionObject
28122 * @constructor
28123 * @param {string} name Unique name within its namespace
28124 * @param {number} id Unique id within its namespace
28125 * @param {string} type Value type
28126 * @param {string|Object.<string,*>} [rule="optional"] Field rule
28127 * @param {string|Object.<string,*>} [extend] Extended type if different from parent
28128 * @param {Object.<string,*>} [options] Declared options
28129 * @param {string} [comment] Comment associated with this field
28130 */
28131function Field(name, id, type, rule, extend, options, comment) {
28132
28133 if (util.isObject(rule)) {
28134 comment = extend;
28135 options = rule;
28136 rule = extend = undefined;
28137 } else if (util.isObject(extend)) {
28138 comment = options;
28139 options = extend;
28140 extend = undefined;
28141 }
28142
28143 ReflectionObject.call(this, name, options);
28144
28145 if (!util.isInteger(id) || id < 0)
28146 throw TypeError("id must be a non-negative integer");
28147
28148 if (!util.isString(type))
28149 throw TypeError("type must be a string");
28150
28151 if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))
28152 throw TypeError("rule must be a string rule");
28153
28154 if (extend !== undefined && !util.isString(extend))
28155 throw TypeError("extend must be a string");
28156
28157 /**
28158 * Field rule, if any.
28159 * @type {string|undefined}
28160 */
28161 this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON
28162
28163 /**
28164 * Field type.
28165 * @type {string}
28166 */
28167 this.type = type; // toJSON
28168
28169 /**
28170 * Unique field id.
28171 * @type {number}
28172 */
28173 this.id = id; // toJSON, marker
28174
28175 /**
28176 * Extended type if different from parent.
28177 * @type {string|undefined}
28178 */
28179 this.extend = extend || undefined; // toJSON
28180
28181 /**
28182 * Whether this field is required.
28183 * @type {boolean}
28184 */
28185 this.required = rule === "required";
28186
28187 /**
28188 * Whether this field is optional.
28189 * @type {boolean}
28190 */
28191 this.optional = !this.required;
28192
28193 /**
28194 * Whether this field is repeated.
28195 * @type {boolean}
28196 */
28197 this.repeated = rule === "repeated";
28198
28199 /**
28200 * Whether this field is a map or not.
28201 * @type {boolean}
28202 */
28203 this.map = false;
28204
28205 /**
28206 * Message this field belongs to.
28207 * @type {Type|null}
28208 */
28209 this.message = null;
28210
28211 /**
28212 * OneOf this field belongs to, if any,
28213 * @type {OneOf|null}
28214 */
28215 this.partOf = null;
28216
28217 /**
28218 * The field type's default value.
28219 * @type {*}
28220 */
28221 this.typeDefault = null;
28222
28223 /**
28224 * The field's default value on prototypes.
28225 * @type {*}
28226 */
28227 this.defaultValue = null;
28228
28229 /**
28230 * Whether this field's value should be treated as a long.
28231 * @type {boolean}
28232 */
28233 this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;
28234
28235 /**
28236 * Whether this field's value is a buffer.
28237 * @type {boolean}
28238 */
28239 this.bytes = type === "bytes";
28240
28241 /**
28242 * Resolved type if not a basic type.
28243 * @type {Type|Enum|null}
28244 */
28245 this.resolvedType = null;
28246
28247 /**
28248 * Sister-field within the extended type if a declaring extension field.
28249 * @type {Field|null}
28250 */
28251 this.extensionField = null;
28252
28253 /**
28254 * Sister-field within the declaring namespace if an extended field.
28255 * @type {Field|null}
28256 */
28257 this.declaringField = null;
28258
28259 /**
28260 * Internally remembers whether this field is packed.
28261 * @type {boolean|null}
28262 * @private
28263 */
28264 this._packed = null;
28265
28266 /**
28267 * Comment for this field.
28268 * @type {string|null}
28269 */
28270 this.comment = comment;
28271}
28272
28273/**
28274 * Determines whether this field is packed. Only relevant when repeated and working with proto2.
28275 * @name Field#packed
28276 * @type {boolean}
28277 * @readonly
28278 */
28279Object.defineProperty(Field.prototype, "packed", {
28280 get: function() {
28281 // defaults to packed=true if not explicity set to false
28282 if (this._packed === null)
28283 this._packed = this.getOption("packed") !== false;
28284 return this._packed;
28285 }
28286});
28287
28288/**
28289 * @override
28290 */
28291Field.prototype.setOption = function setOption(name, value, ifNotSet) {
28292 if (name === "packed") // clear cached before setting
28293 this._packed = null;
28294 return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);
28295};
28296
28297/**
28298 * Field descriptor.
28299 * @interface IField
28300 * @property {string} [rule="optional"] Field rule
28301 * @property {string} type Field type
28302 * @property {number} id Field id
28303 * @property {Object.<string,*>} [options] Field options
28304 */
28305
28306/**
28307 * Extension field descriptor.
28308 * @interface IExtensionField
28309 * @extends IField
28310 * @property {string} extend Extended type
28311 */
28312
28313/**
28314 * Converts this field to a field descriptor.
28315 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
28316 * @returns {IField} Field descriptor
28317 */
28318Field.prototype.toJSON = function toJSON(toJSONOptions) {
28319 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
28320 return util.toObject([
28321 "rule" , this.rule !== "optional" && this.rule || undefined,
28322 "type" , this.type,
28323 "id" , this.id,
28324 "extend" , this.extend,
28325 "options" , this.options,
28326 "comment" , keepComments ? this.comment : undefined
28327 ]);
28328};
28329
28330/**
28331 * Resolves this field's type references.
28332 * @returns {Field} `this`
28333 * @throws {Error} If any reference cannot be resolved
28334 */
28335Field.prototype.resolve = function resolve() {
28336
28337 if (this.resolved)
28338 return this;
28339
28340 if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it
28341 this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);
28342 if (this.resolvedType instanceof Type)
28343 this.typeDefault = null;
28344 else // instanceof Enum
28345 this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined
28346 }
28347
28348 // use explicitly set default value if present
28349 if (this.options && this.options["default"] != null) {
28350 this.typeDefault = this.options["default"];
28351 if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string")
28352 this.typeDefault = this.resolvedType.values[this.typeDefault];
28353 }
28354
28355 // remove unnecessary options
28356 if (this.options) {
28357 if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))
28358 delete this.options.packed;
28359 if (!Object.keys(this.options).length)
28360 this.options = undefined;
28361 }
28362
28363 // convert to internal data type if necesssary
28364 if (this.long) {
28365 this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u");
28366
28367 /* istanbul ignore else */
28368 if (Object.freeze)
28369 Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)
28370
28371 } else if (this.bytes && typeof this.typeDefault === "string") {
28372 var buf;
28373 if (util.base64.test(this.typeDefault))
28374 util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);
28375 else
28376 util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);
28377 this.typeDefault = buf;
28378 }
28379
28380 // take special care of maps and repeated fields
28381 if (this.map)
28382 this.defaultValue = util.emptyObject;
28383 else if (this.repeated)
28384 this.defaultValue = util.emptyArray;
28385 else
28386 this.defaultValue = this.typeDefault;
28387
28388 // ensure proper value on prototype
28389 if (this.parent instanceof Type)
28390 this.parent.ctor.prototype[this.name] = this.defaultValue;
28391
28392 return ReflectionObject.prototype.resolve.call(this);
28393};
28394
28395/**
28396 * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).
28397 * @typedef FieldDecorator
28398 * @type {function}
28399 * @param {Object} prototype Target prototype
28400 * @param {string} fieldName Field name
28401 * @returns {undefined}
28402 */
28403
28404/**
28405 * Field decorator (TypeScript).
28406 * @name Field.d
28407 * @function
28408 * @param {number} fieldId Field id
28409 * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|Object} fieldType Field type
28410 * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule
28411 * @param {T} [defaultValue] Default value
28412 * @returns {FieldDecorator} Decorator function
28413 * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]
28414 */
28415Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {
28416
28417 // submessage: decorate the submessage and use its name as the type
28418 if (typeof fieldType === "function")
28419 fieldType = util.decorateType(fieldType).name;
28420
28421 // enum reference: create a reflected copy of the enum and keep reuseing it
28422 else if (fieldType && typeof fieldType === "object")
28423 fieldType = util.decorateEnum(fieldType).name;
28424
28425 return function fieldDecorator(prototype, fieldName) {
28426 util.decorateType(prototype.constructor)
28427 .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue }));
28428 };
28429};
28430
28431/**
28432 * Field decorator (TypeScript).
28433 * @name Field.d
28434 * @function
28435 * @param {number} fieldId Field id
28436 * @param {Constructor<T>|string} fieldType Field type
28437 * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule
28438 * @returns {FieldDecorator} Decorator function
28439 * @template T extends Message<T>
28440 * @variation 2
28441 */
28442// like Field.d but without a default value
28443
28444Field._configure = function configure(Type_) {
28445 Type = Type_;
28446};
28447
28448},{"./enum":196,"./object":205,"./types":217,"./util":218}],198:[function(require,module,exports){
28449"use strict";
28450var protobuf = module.exports = require("./index-minimal");
28451
28452protobuf.build = "light";
28453
28454/**
28455 * A node-style callback as used by {@link load} and {@link Root#load}.
28456 * @typedef LoadCallback
28457 * @type {function}
28458 * @param {Error|null} error Error, if any, otherwise `null`
28459 * @param {Root} [root] Root, if there hasn't been an error
28460 * @returns {undefined}
28461 */
28462
28463/**
28464 * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.
28465 * @param {string|string[]} filename One or multiple files to load
28466 * @param {Root} root Root namespace, defaults to create a new one if omitted.
28467 * @param {LoadCallback} callback Callback function
28468 * @returns {undefined}
28469 * @see {@link Root#load}
28470 */
28471function load(filename, root, callback) {
28472 if (typeof root === "function") {
28473 callback = root;
28474 root = new protobuf.Root();
28475 } else if (!root)
28476 root = new protobuf.Root();
28477 return root.load(filename, callback);
28478}
28479
28480/**
28481 * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.
28482 * @name load
28483 * @function
28484 * @param {string|string[]} filename One or multiple files to load
28485 * @param {LoadCallback} callback Callback function
28486 * @returns {undefined}
28487 * @see {@link Root#load}
28488 * @variation 2
28489 */
28490// function load(filename:string, callback:LoadCallback):undefined
28491
28492/**
28493 * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.
28494 * @name load
28495 * @function
28496 * @param {string|string[]} filename One or multiple files to load
28497 * @param {Root} [root] Root namespace, defaults to create a new one if omitted.
28498 * @returns {Promise<Root>} Promise
28499 * @see {@link Root#load}
28500 * @variation 3
28501 */
28502// function load(filename:string, [root:Root]):Promise<Root>
28503
28504protobuf.load = load;
28505
28506/**
28507 * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).
28508 * @param {string|string[]} filename One or multiple files to load
28509 * @param {Root} [root] Root namespace, defaults to create a new one if omitted.
28510 * @returns {Root} Root namespace
28511 * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid
28512 * @see {@link Root#loadSync}
28513 */
28514function loadSync(filename, root) {
28515 if (!root)
28516 root = new protobuf.Root();
28517 return root.loadSync(filename);
28518}
28519
28520protobuf.loadSync = loadSync;
28521
28522// Serialization
28523protobuf.encoder = require("./encoder");
28524protobuf.decoder = require("./decoder");
28525protobuf.verifier = require("./verifier");
28526protobuf.converter = require("./converter");
28527
28528// Reflection
28529protobuf.ReflectionObject = require("./object");
28530protobuf.Namespace = require("./namespace");
28531protobuf.Root = require("./root");
28532protobuf.Enum = require("./enum");
28533protobuf.Type = require("./type");
28534protobuf.Field = require("./field");
28535protobuf.OneOf = require("./oneof");
28536protobuf.MapField = require("./mapfield");
28537protobuf.Service = require("./service");
28538protobuf.Method = require("./method");
28539
28540// Runtime
28541protobuf.Message = require("./message");
28542protobuf.wrappers = require("./wrappers");
28543
28544// Utility
28545protobuf.types = require("./types");
28546protobuf.util = require("./util");
28547
28548// Configure reflection
28549protobuf.ReflectionObject._configure(protobuf.Root);
28550protobuf.Namespace._configure(protobuf.Type, protobuf.Service);
28551protobuf.Root._configure(protobuf.Type);
28552protobuf.Field._configure(protobuf.Type);
28553
28554},{"./converter":193,"./decoder":194,"./encoder":195,"./enum":196,"./field":197,"./index-minimal":199,"./mapfield":201,"./message":202,"./method":203,"./namespace":204,"./object":205,"./oneof":206,"./root":210,"./service":214,"./type":216,"./types":217,"./util":218,"./verifier":221,"./wrappers":222}],199:[function(require,module,exports){
28555"use strict";
28556var protobuf = exports;
28557
28558/**
28559 * Build type, one of `"full"`, `"light"` or `"minimal"`.
28560 * @name build
28561 * @type {string}
28562 * @const
28563 */
28564protobuf.build = "minimal";
28565
28566// Serialization
28567protobuf.Writer = require("./writer");
28568protobuf.BufferWriter = require("./writer_buffer");
28569protobuf.Reader = require("./reader");
28570protobuf.BufferReader = require("./reader_buffer");
28571
28572// Utility
28573protobuf.util = require("./util/minimal");
28574protobuf.rpc = require("./rpc");
28575protobuf.roots = require("./roots");
28576protobuf.configure = configure;
28577
28578/* istanbul ignore next */
28579/**
28580 * Reconfigures the library according to the environment.
28581 * @returns {undefined}
28582 */
28583function configure() {
28584 protobuf.Reader._configure(protobuf.BufferReader);
28585 protobuf.util._configure();
28586}
28587
28588// Configure serialization
28589protobuf.Writer._configure(protobuf.BufferWriter);
28590configure();
28591
28592},{"./reader":208,"./reader_buffer":209,"./roots":211,"./rpc":212,"./util/minimal":220,"./writer":223,"./writer_buffer":224}],200:[function(require,module,exports){
28593"use strict";
28594var protobuf = module.exports = require("./index-light");
28595
28596protobuf.build = "full";
28597
28598// Parser
28599protobuf.tokenize = require("./tokenize");
28600protobuf.parse = require("./parse");
28601protobuf.common = require("./common");
28602
28603// Configure parser
28604protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common);
28605
28606},{"./common":192,"./index-light":198,"./parse":207,"./tokenize":215}],201:[function(require,module,exports){
28607"use strict";
28608module.exports = MapField;
28609
28610// extends Field
28611var Field = require("./field");
28612((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField";
28613
28614var types = require("./types"),
28615 util = require("./util");
28616
28617/**
28618 * Constructs a new map field instance.
28619 * @classdesc Reflected map field.
28620 * @extends FieldBase
28621 * @constructor
28622 * @param {string} name Unique name within its namespace
28623 * @param {number} id Unique id within its namespace
28624 * @param {string} keyType Key type
28625 * @param {string} type Value type
28626 * @param {Object.<string,*>} [options] Declared options
28627 * @param {string} [comment] Comment associated with this field
28628 */
28629function MapField(name, id, keyType, type, options, comment) {
28630 Field.call(this, name, id, type, undefined, undefined, options, comment);
28631
28632 /* istanbul ignore if */
28633 if (!util.isString(keyType))
28634 throw TypeError("keyType must be a string");
28635
28636 /**
28637 * Key type.
28638 * @type {string}
28639 */
28640 this.keyType = keyType; // toJSON, marker
28641
28642 /**
28643 * Resolved key type if not a basic type.
28644 * @type {ReflectionObject|null}
28645 */
28646 this.resolvedKeyType = null;
28647
28648 // Overrides Field#map
28649 this.map = true;
28650}
28651
28652/**
28653 * Map field descriptor.
28654 * @interface IMapField
28655 * @extends {IField}
28656 * @property {string} keyType Key type
28657 */
28658
28659/**
28660 * Extension map field descriptor.
28661 * @interface IExtensionMapField
28662 * @extends IMapField
28663 * @property {string} extend Extended type
28664 */
28665
28666/**
28667 * Constructs a map field from a map field descriptor.
28668 * @param {string} name Field name
28669 * @param {IMapField} json Map field descriptor
28670 * @returns {MapField} Created map field
28671 * @throws {TypeError} If arguments are invalid
28672 */
28673MapField.fromJSON = function fromJSON(name, json) {
28674 return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);
28675};
28676
28677/**
28678 * Converts this map field to a map field descriptor.
28679 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
28680 * @returns {IMapField} Map field descriptor
28681 */
28682MapField.prototype.toJSON = function toJSON(toJSONOptions) {
28683 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
28684 return util.toObject([
28685 "keyType" , this.keyType,
28686 "type" , this.type,
28687 "id" , this.id,
28688 "extend" , this.extend,
28689 "options" , this.options,
28690 "comment" , keepComments ? this.comment : undefined
28691 ]);
28692};
28693
28694/**
28695 * @override
28696 */
28697MapField.prototype.resolve = function resolve() {
28698 if (this.resolved)
28699 return this;
28700
28701 // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes"
28702 if (types.mapKey[this.keyType] === undefined)
28703 throw Error("invalid key type: " + this.keyType);
28704
28705 return Field.prototype.resolve.call(this);
28706};
28707
28708/**
28709 * Map field decorator (TypeScript).
28710 * @name MapField.d
28711 * @function
28712 * @param {number} fieldId Field id
28713 * @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type
28714 * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type
28715 * @returns {FieldDecorator} Decorator function
28716 * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }
28717 */
28718MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {
28719
28720 // submessage value: decorate the submessage and use its name as the type
28721 if (typeof fieldValueType === "function")
28722 fieldValueType = util.decorateType(fieldValueType).name;
28723
28724 // enum reference value: create a reflected copy of the enum and keep reuseing it
28725 else if (fieldValueType && typeof fieldValueType === "object")
28726 fieldValueType = util.decorateEnum(fieldValueType).name;
28727
28728 return function mapFieldDecorator(prototype, fieldName) {
28729 util.decorateType(prototype.constructor)
28730 .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));
28731 };
28732};
28733
28734},{"./field":197,"./types":217,"./util":218}],202:[function(require,module,exports){
28735"use strict";
28736module.exports = Message;
28737
28738var util = require("./util/minimal");
28739
28740/**
28741 * Constructs a new message instance.
28742 * @classdesc Abstract runtime message.
28743 * @constructor
28744 * @param {Properties<T>} [properties] Properties to set
28745 * @template T extends object
28746 */
28747function Message(properties) {
28748 // not used internally
28749 if (properties)
28750 for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)
28751 this[keys[i]] = properties[keys[i]];
28752}
28753
28754/**
28755 * Reference to the reflected type.
28756 * @name Message.$type
28757 * @type {Type}
28758 * @readonly
28759 */
28760
28761/**
28762 * Reference to the reflected type.
28763 * @name Message#$type
28764 * @type {Type}
28765 * @readonly
28766 */
28767
28768/*eslint-disable valid-jsdoc*/
28769
28770/**
28771 * Creates a new message of this type using the specified properties.
28772 * @param {Object.<string,*>} [properties] Properties to set
28773 * @returns {Message<T>} Message instance
28774 * @template T extends Message<T>
28775 * @this Constructor<T>
28776 */
28777Message.create = function create(properties) {
28778 return this.$type.create(properties);
28779};
28780
28781/**
28782 * Encodes a message of this type.
28783 * @param {T|Object.<string,*>} message Message to encode
28784 * @param {Writer} [writer] Writer to use
28785 * @returns {Writer} Writer
28786 * @template T extends Message<T>
28787 * @this Constructor<T>
28788 */
28789Message.encode = function encode(message, writer) {
28790 return this.$type.encode(message, writer);
28791};
28792
28793/**
28794 * Encodes a message of this type preceeded by its length as a varint.
28795 * @param {T|Object.<string,*>} message Message to encode
28796 * @param {Writer} [writer] Writer to use
28797 * @returns {Writer} Writer
28798 * @template T extends Message<T>
28799 * @this Constructor<T>
28800 */
28801Message.encodeDelimited = function encodeDelimited(message, writer) {
28802 return this.$type.encodeDelimited(message, writer);
28803};
28804
28805/**
28806 * Decodes a message of this type.
28807 * @name Message.decode
28808 * @function
28809 * @param {Reader|Uint8Array} reader Reader or buffer to decode
28810 * @returns {T} Decoded message
28811 * @template T extends Message<T>
28812 * @this Constructor<T>
28813 */
28814Message.decode = function decode(reader) {
28815 return this.$type.decode(reader);
28816};
28817
28818/**
28819 * Decodes a message of this type preceeded by its length as a varint.
28820 * @name Message.decodeDelimited
28821 * @function
28822 * @param {Reader|Uint8Array} reader Reader or buffer to decode
28823 * @returns {T} Decoded message
28824 * @template T extends Message<T>
28825 * @this Constructor<T>
28826 */
28827Message.decodeDelimited = function decodeDelimited(reader) {
28828 return this.$type.decodeDelimited(reader);
28829};
28830
28831/**
28832 * Verifies a message of this type.
28833 * @name Message.verify
28834 * @function
28835 * @param {Object.<string,*>} message Plain object to verify
28836 * @returns {string|null} `null` if valid, otherwise the reason why it is not
28837 */
28838Message.verify = function verify(message) {
28839 return this.$type.verify(message);
28840};
28841
28842/**
28843 * Creates a new message of this type from a plain object. Also converts values to their respective internal types.
28844 * @param {Object.<string,*>} object Plain object
28845 * @returns {T} Message instance
28846 * @template T extends Message<T>
28847 * @this Constructor<T>
28848 */
28849Message.fromObject = function fromObject(object) {
28850 return this.$type.fromObject(object);
28851};
28852
28853/**
28854 * Creates a plain object from a message of this type. Also converts values to other types if specified.
28855 * @param {T} message Message instance
28856 * @param {IConversionOptions} [options] Conversion options
28857 * @returns {Object.<string,*>} Plain object
28858 * @template T extends Message<T>
28859 * @this Constructor<T>
28860 */
28861Message.toObject = function toObject(message, options) {
28862 return this.$type.toObject(message, options);
28863};
28864
28865/**
28866 * Converts this message to JSON.
28867 * @returns {Object.<string,*>} JSON object
28868 */
28869Message.prototype.toJSON = function toJSON() {
28870 return this.$type.toObject(this, util.toJSONOptions);
28871};
28872
28873/*eslint-enable valid-jsdoc*/
28874},{"./util/minimal":220}],203:[function(require,module,exports){
28875"use strict";
28876module.exports = Method;
28877
28878// extends ReflectionObject
28879var ReflectionObject = require("./object");
28880((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method";
28881
28882var util = require("./util");
28883
28884/**
28885 * Constructs a new service method instance.
28886 * @classdesc Reflected service method.
28887 * @extends ReflectionObject
28888 * @constructor
28889 * @param {string} name Method name
28890 * @param {string|undefined} type Method type, usually `"rpc"`
28891 * @param {string} requestType Request message type
28892 * @param {string} responseType Response message type
28893 * @param {boolean|Object.<string,*>} [requestStream] Whether the request is streamed
28894 * @param {boolean|Object.<string,*>} [responseStream] Whether the response is streamed
28895 * @param {Object.<string,*>} [options] Declared options
28896 * @param {string} [comment] The comment for this method
28897 */
28898function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment) {
28899
28900 /* istanbul ignore next */
28901 if (util.isObject(requestStream)) {
28902 options = requestStream;
28903 requestStream = responseStream = undefined;
28904 } else if (util.isObject(responseStream)) {
28905 options = responseStream;
28906 responseStream = undefined;
28907 }
28908
28909 /* istanbul ignore if */
28910 if (!(type === undefined || util.isString(type)))
28911 throw TypeError("type must be a string");
28912
28913 /* istanbul ignore if */
28914 if (!util.isString(requestType))
28915 throw TypeError("requestType must be a string");
28916
28917 /* istanbul ignore if */
28918 if (!util.isString(responseType))
28919 throw TypeError("responseType must be a string");
28920
28921 ReflectionObject.call(this, name, options);
28922
28923 /**
28924 * Method type.
28925 * @type {string}
28926 */
28927 this.type = type || "rpc"; // toJSON
28928
28929 /**
28930 * Request type.
28931 * @type {string}
28932 */
28933 this.requestType = requestType; // toJSON, marker
28934
28935 /**
28936 * Whether requests are streamed or not.
28937 * @type {boolean|undefined}
28938 */
28939 this.requestStream = requestStream ? true : undefined; // toJSON
28940
28941 /**
28942 * Response type.
28943 * @type {string}
28944 */
28945 this.responseType = responseType; // toJSON
28946
28947 /**
28948 * Whether responses are streamed or not.
28949 * @type {boolean|undefined}
28950 */
28951 this.responseStream = responseStream ? true : undefined; // toJSON
28952
28953 /**
28954 * Resolved request type.
28955 * @type {Type|null}
28956 */
28957 this.resolvedRequestType = null;
28958
28959 /**
28960 * Resolved response type.
28961 * @type {Type|null}
28962 */
28963 this.resolvedResponseType = null;
28964
28965 /**
28966 * Comment for this method
28967 * @type {string|null}
28968 */
28969 this.comment = comment;
28970}
28971
28972/**
28973 * Method descriptor.
28974 * @interface IMethod
28975 * @property {string} [type="rpc"] Method type
28976 * @property {string} requestType Request type
28977 * @property {string} responseType Response type
28978 * @property {boolean} [requestStream=false] Whether requests are streamed
28979 * @property {boolean} [responseStream=false] Whether responses are streamed
28980 * @property {Object.<string,*>} [options] Method options
28981 */
28982
28983/**
28984 * Constructs a method from a method descriptor.
28985 * @param {string} name Method name
28986 * @param {IMethod} json Method descriptor
28987 * @returns {Method} Created method
28988 * @throws {TypeError} If arguments are invalid
28989 */
28990Method.fromJSON = function fromJSON(name, json) {
28991 return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment);
28992};
28993
28994/**
28995 * Converts this method to a method descriptor.
28996 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
28997 * @returns {IMethod} Method descriptor
28998 */
28999Method.prototype.toJSON = function toJSON(toJSONOptions) {
29000 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
29001 return util.toObject([
29002 "type" , this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined,
29003 "requestType" , this.requestType,
29004 "requestStream" , this.requestStream,
29005 "responseType" , this.responseType,
29006 "responseStream" , this.responseStream,
29007 "options" , this.options,
29008 "comment" , keepComments ? this.comment : undefined
29009 ]);
29010};
29011
29012/**
29013 * @override
29014 */
29015Method.prototype.resolve = function resolve() {
29016
29017 /* istanbul ignore if */
29018 if (this.resolved)
29019 return this;
29020
29021 this.resolvedRequestType = this.parent.lookupType(this.requestType);
29022 this.resolvedResponseType = this.parent.lookupType(this.responseType);
29023
29024 return ReflectionObject.prototype.resolve.call(this);
29025};
29026
29027},{"./object":205,"./util":218}],204:[function(require,module,exports){
29028"use strict";
29029module.exports = Namespace;
29030
29031// extends ReflectionObject
29032var ReflectionObject = require("./object");
29033((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace";
29034
29035var Enum = require("./enum"),
29036 Field = require("./field"),
29037 util = require("./util");
29038
29039var Type, // cyclic
29040 Service; // "
29041
29042/**
29043 * Constructs a new namespace instance.
29044 * @name Namespace
29045 * @classdesc Reflected namespace.
29046 * @extends NamespaceBase
29047 * @constructor
29048 * @param {string} name Namespace name
29049 * @param {Object.<string,*>} [options] Declared options
29050 */
29051
29052/**
29053 * Constructs a namespace from JSON.
29054 * @memberof Namespace
29055 * @function
29056 * @param {string} name Namespace name
29057 * @param {Object.<string,*>} json JSON object
29058 * @returns {Namespace} Created namespace
29059 * @throws {TypeError} If arguments are invalid
29060 */
29061Namespace.fromJSON = function fromJSON(name, json) {
29062 return new Namespace(name, json.options).addJSON(json.nested);
29063};
29064
29065/**
29066 * Converts an array of reflection objects to JSON.
29067 * @memberof Namespace
29068 * @param {ReflectionObject[]} array Object array
29069 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
29070 * @returns {Object.<string,*>|undefined} JSON object or `undefined` when array is empty
29071 */
29072function arrayToJSON(array, toJSONOptions) {
29073 if (!(array && array.length))
29074 return undefined;
29075 var obj = {};
29076 for (var i = 0; i < array.length; ++i)
29077 obj[array[i].name] = array[i].toJSON(toJSONOptions);
29078 return obj;
29079}
29080
29081Namespace.arrayToJSON = arrayToJSON;
29082
29083/**
29084 * Tests if the specified id is reserved.
29085 * @param {Array.<number[]|string>|undefined} reserved Array of reserved ranges and names
29086 * @param {number} id Id to test
29087 * @returns {boolean} `true` if reserved, otherwise `false`
29088 */
29089Namespace.isReservedId = function isReservedId(reserved, id) {
29090 if (reserved)
29091 for (var i = 0; i < reserved.length; ++i)
29092 if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] >= id)
29093 return true;
29094 return false;
29095};
29096
29097/**
29098 * Tests if the specified name is reserved.
29099 * @param {Array.<number[]|string>|undefined} reserved Array of reserved ranges and names
29100 * @param {string} name Name to test
29101 * @returns {boolean} `true` if reserved, otherwise `false`
29102 */
29103Namespace.isReservedName = function isReservedName(reserved, name) {
29104 if (reserved)
29105 for (var i = 0; i < reserved.length; ++i)
29106 if (reserved[i] === name)
29107 return true;
29108 return false;
29109};
29110
29111/**
29112 * Not an actual constructor. Use {@link Namespace} instead.
29113 * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.
29114 * @exports NamespaceBase
29115 * @extends ReflectionObject
29116 * @abstract
29117 * @constructor
29118 * @param {string} name Namespace name
29119 * @param {Object.<string,*>} [options] Declared options
29120 * @see {@link Namespace}
29121 */
29122function Namespace(name, options) {
29123 ReflectionObject.call(this, name, options);
29124
29125 /**
29126 * Nested objects by name.
29127 * @type {Object.<string,ReflectionObject>|undefined}
29128 */
29129 this.nested = undefined; // toJSON
29130
29131 /**
29132 * Cached nested objects as an array.
29133 * @type {ReflectionObject[]|null}
29134 * @private
29135 */
29136 this._nestedArray = null;
29137}
29138
29139function clearCache(namespace) {
29140 namespace._nestedArray = null;
29141 return namespace;
29142}
29143
29144/**
29145 * Nested objects of this namespace as an array for iteration.
29146 * @name NamespaceBase#nestedArray
29147 * @type {ReflectionObject[]}
29148 * @readonly
29149 */
29150Object.defineProperty(Namespace.prototype, "nestedArray", {
29151 get: function() {
29152 return this._nestedArray || (this._nestedArray = util.toArray(this.nested));
29153 }
29154});
29155
29156/**
29157 * Namespace descriptor.
29158 * @interface INamespace
29159 * @property {Object.<string,*>} [options] Namespace options
29160 * @property {Object.<string,AnyNestedObject>} [nested] Nested object descriptors
29161 */
29162
29163/**
29164 * Any extension field descriptor.
29165 * @typedef AnyExtensionField
29166 * @type {IExtensionField|IExtensionMapField}
29167 */
29168
29169/**
29170 * Any nested object descriptor.
29171 * @typedef AnyNestedObject
29172 * @type {IEnum|IType|IService|AnyExtensionField|INamespace}
29173 */
29174// ^ BEWARE: VSCode hangs forever when using more than 5 types (that's why AnyExtensionField exists in the first place)
29175
29176/**
29177 * Converts this namespace to a namespace descriptor.
29178 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
29179 * @returns {INamespace} Namespace descriptor
29180 */
29181Namespace.prototype.toJSON = function toJSON(toJSONOptions) {
29182 return util.toObject([
29183 "options" , this.options,
29184 "nested" , arrayToJSON(this.nestedArray, toJSONOptions)
29185 ]);
29186};
29187
29188/**
29189 * Adds nested objects to this namespace from nested object descriptors.
29190 * @param {Object.<string,AnyNestedObject>} nestedJson Any nested object descriptors
29191 * @returns {Namespace} `this`
29192 */
29193Namespace.prototype.addJSON = function addJSON(nestedJson) {
29194 var ns = this;
29195 /* istanbul ignore else */
29196 if (nestedJson) {
29197 for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {
29198 nested = nestedJson[names[i]];
29199 ns.add( // most to least likely
29200 ( nested.fields !== undefined
29201 ? Type.fromJSON
29202 : nested.values !== undefined
29203 ? Enum.fromJSON
29204 : nested.methods !== undefined
29205 ? Service.fromJSON
29206 : nested.id !== undefined
29207 ? Field.fromJSON
29208 : Namespace.fromJSON )(names[i], nested)
29209 );
29210 }
29211 }
29212 return this;
29213};
29214
29215/**
29216 * Gets the nested object of the specified name.
29217 * @param {string} name Nested object name
29218 * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist
29219 */
29220Namespace.prototype.get = function get(name) {
29221 return this.nested && this.nested[name]
29222 || null;
29223};
29224
29225/**
29226 * Gets the values of the nested {@link Enum|enum} of the specified name.
29227 * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.
29228 * @param {string} name Nested enum name
29229 * @returns {Object.<string,number>} Enum values
29230 * @throws {Error} If there is no such enum
29231 */
29232Namespace.prototype.getEnum = function getEnum(name) {
29233 if (this.nested && this.nested[name] instanceof Enum)
29234 return this.nested[name].values;
29235 throw Error("no such enum: " + name);
29236};
29237
29238/**
29239 * Adds a nested object to this namespace.
29240 * @param {ReflectionObject} object Nested object to add
29241 * @returns {Namespace} `this`
29242 * @throws {TypeError} If arguments are invalid
29243 * @throws {Error} If there is already a nested object with this name
29244 */
29245Namespace.prototype.add = function add(object) {
29246
29247 if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof Enum || object instanceof Service || object instanceof Namespace))
29248 throw TypeError("object must be a valid nested object");
29249
29250 if (!this.nested)
29251 this.nested = {};
29252 else {
29253 var prev = this.get(object.name);
29254 if (prev) {
29255 if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {
29256 // replace plain namespace but keep existing nested elements and options
29257 var nested = prev.nestedArray;
29258 for (var i = 0; i < nested.length; ++i)
29259 object.add(nested[i]);
29260 this.remove(prev);
29261 if (!this.nested)
29262 this.nested = {};
29263 object.setOptions(prev.options, true);
29264
29265 } else
29266 throw Error("duplicate name '" + object.name + "' in " + this);
29267 }
29268 }
29269 this.nested[object.name] = object;
29270 object.onAdd(this);
29271 return clearCache(this);
29272};
29273
29274/**
29275 * Removes a nested object from this namespace.
29276 * @param {ReflectionObject} object Nested object to remove
29277 * @returns {Namespace} `this`
29278 * @throws {TypeError} If arguments are invalid
29279 * @throws {Error} If `object` is not a member of this namespace
29280 */
29281Namespace.prototype.remove = function remove(object) {
29282
29283 if (!(object instanceof ReflectionObject))
29284 throw TypeError("object must be a ReflectionObject");
29285 if (object.parent !== this)
29286 throw Error(object + " is not a member of " + this);
29287
29288 delete this.nested[object.name];
29289 if (!Object.keys(this.nested).length)
29290 this.nested = undefined;
29291
29292 object.onRemove(this);
29293 return clearCache(this);
29294};
29295
29296/**
29297 * Defines additial namespaces within this one if not yet existing.
29298 * @param {string|string[]} path Path to create
29299 * @param {*} [json] Nested types to create from JSON
29300 * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty
29301 */
29302Namespace.prototype.define = function define(path, json) {
29303
29304 if (util.isString(path))
29305 path = path.split(".");
29306 else if (!Array.isArray(path))
29307 throw TypeError("illegal path");
29308 if (path && path.length && path[0] === "")
29309 throw Error("path must be relative");
29310
29311 var ptr = this;
29312 while (path.length > 0) {
29313 var part = path.shift();
29314 if (ptr.nested && ptr.nested[part]) {
29315 ptr = ptr.nested[part];
29316 if (!(ptr instanceof Namespace))
29317 throw Error("path conflicts with non-namespace objects");
29318 } else
29319 ptr.add(ptr = new Namespace(part));
29320 }
29321 if (json)
29322 ptr.addJSON(json);
29323 return ptr;
29324};
29325
29326/**
29327 * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.
29328 * @returns {Namespace} `this`
29329 */
29330Namespace.prototype.resolveAll = function resolveAll() {
29331 var nested = this.nestedArray, i = 0;
29332 while (i < nested.length)
29333 if (nested[i] instanceof Namespace)
29334 nested[i++].resolveAll();
29335 else
29336 nested[i++].resolve();
29337 return this.resolve();
29338};
29339
29340/**
29341 * Recursively looks up the reflection object matching the specified path in the scope of this namespace.
29342 * @param {string|string[]} path Path to look up
29343 * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.
29344 * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked
29345 * @returns {ReflectionObject|null} Looked up object or `null` if none could be found
29346 */
29347Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {
29348
29349 /* istanbul ignore next */
29350 if (typeof filterTypes === "boolean") {
29351 parentAlreadyChecked = filterTypes;
29352 filterTypes = undefined;
29353 } else if (filterTypes && !Array.isArray(filterTypes))
29354 filterTypes = [ filterTypes ];
29355
29356 if (util.isString(path) && path.length) {
29357 if (path === ".")
29358 return this.root;
29359 path = path.split(".");
29360 } else if (!path.length)
29361 return this;
29362
29363 // Start at root if path is absolute
29364 if (path[0] === "")
29365 return this.root.lookup(path.slice(1), filterTypes);
29366
29367 // Test if the first part matches any nested object, and if so, traverse if path contains more
29368 var found = this.get(path[0]);
29369 if (found) {
29370 if (path.length === 1) {
29371 if (!filterTypes || filterTypes.indexOf(found.constructor) > -1)
29372 return found;
29373 } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true)))
29374 return found;
29375
29376 // Otherwise try each nested namespace
29377 } else
29378 for (var i = 0; i < this.nestedArray.length; ++i)
29379 if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true)))
29380 return found;
29381
29382 // If there hasn't been a match, try again at the parent
29383 if (this.parent === null || parentAlreadyChecked)
29384 return null;
29385 return this.parent.lookup(path, filterTypes);
29386};
29387
29388/**
29389 * Looks up the reflection object at the specified path, relative to this namespace.
29390 * @name NamespaceBase#lookup
29391 * @function
29392 * @param {string|string[]} path Path to look up
29393 * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked
29394 * @returns {ReflectionObject|null} Looked up object or `null` if none could be found
29395 * @variation 2
29396 */
29397// lookup(path: string, [parentAlreadyChecked: boolean])
29398
29399/**
29400 * Looks up the {@link Type|type} at the specified path, relative to this namespace.
29401 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
29402 * @param {string|string[]} path Path to look up
29403 * @returns {Type} Looked up type
29404 * @throws {Error} If `path` does not point to a type
29405 */
29406Namespace.prototype.lookupType = function lookupType(path) {
29407 var found = this.lookup(path, [ Type ]);
29408 if (!found)
29409 throw Error("no such type: " + path);
29410 return found;
29411};
29412
29413/**
29414 * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.
29415 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
29416 * @param {string|string[]} path Path to look up
29417 * @returns {Enum} Looked up enum
29418 * @throws {Error} If `path` does not point to an enum
29419 */
29420Namespace.prototype.lookupEnum = function lookupEnum(path) {
29421 var found = this.lookup(path, [ Enum ]);
29422 if (!found)
29423 throw Error("no such Enum '" + path + "' in " + this);
29424 return found;
29425};
29426
29427/**
29428 * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.
29429 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
29430 * @param {string|string[]} path Path to look up
29431 * @returns {Type} Looked up type or enum
29432 * @throws {Error} If `path` does not point to a type or enum
29433 */
29434Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {
29435 var found = this.lookup(path, [ Type, Enum ]);
29436 if (!found)
29437 throw Error("no such Type or Enum '" + path + "' in " + this);
29438 return found;
29439};
29440
29441/**
29442 * Looks up the {@link Service|service} at the specified path, relative to this namespace.
29443 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
29444 * @param {string|string[]} path Path to look up
29445 * @returns {Service} Looked up service
29446 * @throws {Error} If `path` does not point to a service
29447 */
29448Namespace.prototype.lookupService = function lookupService(path) {
29449 var found = this.lookup(path, [ Service ]);
29450 if (!found)
29451 throw Error("no such Service '" + path + "' in " + this);
29452 return found;
29453};
29454
29455Namespace._configure = function(Type_, Service_) {
29456 Type = Type_;
29457 Service = Service_;
29458};
29459
29460},{"./enum":196,"./field":197,"./object":205,"./util":218}],205:[function(require,module,exports){
29461"use strict";
29462module.exports = ReflectionObject;
29463
29464ReflectionObject.className = "ReflectionObject";
29465
29466var util = require("./util");
29467
29468var Root; // cyclic
29469
29470/**
29471 * Constructs a new reflection object instance.
29472 * @classdesc Base class of all reflection objects.
29473 * @constructor
29474 * @param {string} name Object name
29475 * @param {Object.<string,*>} [options] Declared options
29476 * @abstract
29477 */
29478function ReflectionObject(name, options) {
29479
29480 if (!util.isString(name))
29481 throw TypeError("name must be a string");
29482
29483 if (options && !util.isObject(options))
29484 throw TypeError("options must be an object");
29485
29486 /**
29487 * Options.
29488 * @type {Object.<string,*>|undefined}
29489 */
29490 this.options = options; // toJSON
29491
29492 /**
29493 * Unique name within its namespace.
29494 * @type {string}
29495 */
29496 this.name = name;
29497
29498 /**
29499 * Parent namespace.
29500 * @type {Namespace|null}
29501 */
29502 this.parent = null;
29503
29504 /**
29505 * Whether already resolved or not.
29506 * @type {boolean}
29507 */
29508 this.resolved = false;
29509
29510 /**
29511 * Comment text, if any.
29512 * @type {string|null}
29513 */
29514 this.comment = null;
29515
29516 /**
29517 * Defining file name.
29518 * @type {string|null}
29519 */
29520 this.filename = null;
29521}
29522
29523Object.defineProperties(ReflectionObject.prototype, {
29524
29525 /**
29526 * Reference to the root namespace.
29527 * @name ReflectionObject#root
29528 * @type {Root}
29529 * @readonly
29530 */
29531 root: {
29532 get: function() {
29533 var ptr = this;
29534 while (ptr.parent !== null)
29535 ptr = ptr.parent;
29536 return ptr;
29537 }
29538 },
29539
29540 /**
29541 * Full name including leading dot.
29542 * @name ReflectionObject#fullName
29543 * @type {string}
29544 * @readonly
29545 */
29546 fullName: {
29547 get: function() {
29548 var path = [ this.name ],
29549 ptr = this.parent;
29550 while (ptr) {
29551 path.unshift(ptr.name);
29552 ptr = ptr.parent;
29553 }
29554 return path.join(".");
29555 }
29556 }
29557});
29558
29559/**
29560 * Converts this reflection object to its descriptor representation.
29561 * @returns {Object.<string,*>} Descriptor
29562 * @abstract
29563 */
29564ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {
29565 throw Error(); // not implemented, shouldn't happen
29566};
29567
29568/**
29569 * Called when this object is added to a parent.
29570 * @param {ReflectionObject} parent Parent added to
29571 * @returns {undefined}
29572 */
29573ReflectionObject.prototype.onAdd = function onAdd(parent) {
29574 if (this.parent && this.parent !== parent)
29575 this.parent.remove(this);
29576 this.parent = parent;
29577 this.resolved = false;
29578 var root = parent.root;
29579 if (root instanceof Root)
29580 root._handleAdd(this);
29581};
29582
29583/**
29584 * Called when this object is removed from a parent.
29585 * @param {ReflectionObject} parent Parent removed from
29586 * @returns {undefined}
29587 */
29588ReflectionObject.prototype.onRemove = function onRemove(parent) {
29589 var root = parent.root;
29590 if (root instanceof Root)
29591 root._handleRemove(this);
29592 this.parent = null;
29593 this.resolved = false;
29594};
29595
29596/**
29597 * Resolves this objects type references.
29598 * @returns {ReflectionObject} `this`
29599 */
29600ReflectionObject.prototype.resolve = function resolve() {
29601 if (this.resolved)
29602 return this;
29603 if (this.root instanceof Root)
29604 this.resolved = true; // only if part of a root
29605 return this;
29606};
29607
29608/**
29609 * Gets an option value.
29610 * @param {string} name Option name
29611 * @returns {*} Option value or `undefined` if not set
29612 */
29613ReflectionObject.prototype.getOption = function getOption(name) {
29614 if (this.options)
29615 return this.options[name];
29616 return undefined;
29617};
29618
29619/**
29620 * Sets an option.
29621 * @param {string} name Option name
29622 * @param {*} value Option value
29623 * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set
29624 * @returns {ReflectionObject} `this`
29625 */
29626ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {
29627 if (!ifNotSet || !this.options || this.options[name] === undefined)
29628 (this.options || (this.options = {}))[name] = value;
29629 return this;
29630};
29631
29632/**
29633 * Sets multiple options.
29634 * @param {Object.<string,*>} options Options to set
29635 * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set
29636 * @returns {ReflectionObject} `this`
29637 */
29638ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {
29639 if (options)
29640 for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)
29641 this.setOption(keys[i], options[keys[i]], ifNotSet);
29642 return this;
29643};
29644
29645/**
29646 * Converts this instance to its string representation.
29647 * @returns {string} Class name[, space, full name]
29648 */
29649ReflectionObject.prototype.toString = function toString() {
29650 var className = this.constructor.className,
29651 fullName = this.fullName;
29652 if (fullName.length)
29653 return className + " " + fullName;
29654 return className;
29655};
29656
29657ReflectionObject._configure = function(Root_) {
29658 Root = Root_;
29659};
29660
29661},{"./util":218}],206:[function(require,module,exports){
29662"use strict";
29663module.exports = OneOf;
29664
29665// extends ReflectionObject
29666var ReflectionObject = require("./object");
29667((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf";
29668
29669var Field = require("./field"),
29670 util = require("./util");
29671
29672/**
29673 * Constructs a new oneof instance.
29674 * @classdesc Reflected oneof.
29675 * @extends ReflectionObject
29676 * @constructor
29677 * @param {string} name Oneof name
29678 * @param {string[]|Object.<string,*>} [fieldNames] Field names
29679 * @param {Object.<string,*>} [options] Declared options
29680 * @param {string} [comment] Comment associated with this field
29681 */
29682function OneOf(name, fieldNames, options, comment) {
29683 if (!Array.isArray(fieldNames)) {
29684 options = fieldNames;
29685 fieldNames = undefined;
29686 }
29687 ReflectionObject.call(this, name, options);
29688
29689 /* istanbul ignore if */
29690 if (!(fieldNames === undefined || Array.isArray(fieldNames)))
29691 throw TypeError("fieldNames must be an Array");
29692
29693 /**
29694 * Field names that belong to this oneof.
29695 * @type {string[]}
29696 */
29697 this.oneof = fieldNames || []; // toJSON, marker
29698
29699 /**
29700 * Fields that belong to this oneof as an array for iteration.
29701 * @type {Field[]}
29702 * @readonly
29703 */
29704 this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent
29705
29706 /**
29707 * Comment for this field.
29708 * @type {string|null}
29709 */
29710 this.comment = comment;
29711}
29712
29713/**
29714 * Oneof descriptor.
29715 * @interface IOneOf
29716 * @property {Array.<string>} oneof Oneof field names
29717 * @property {Object.<string,*>} [options] Oneof options
29718 */
29719
29720/**
29721 * Constructs a oneof from a oneof descriptor.
29722 * @param {string} name Oneof name
29723 * @param {IOneOf} json Oneof descriptor
29724 * @returns {OneOf} Created oneof
29725 * @throws {TypeError} If arguments are invalid
29726 */
29727OneOf.fromJSON = function fromJSON(name, json) {
29728 return new OneOf(name, json.oneof, json.options, json.comment);
29729};
29730
29731/**
29732 * Converts this oneof to a oneof descriptor.
29733 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
29734 * @returns {IOneOf} Oneof descriptor
29735 */
29736OneOf.prototype.toJSON = function toJSON(toJSONOptions) {
29737 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
29738 return util.toObject([
29739 "options" , this.options,
29740 "oneof" , this.oneof,
29741 "comment" , keepComments ? this.comment : undefined
29742 ]);
29743};
29744
29745/**
29746 * Adds the fields of the specified oneof to the parent if not already done so.
29747 * @param {OneOf} oneof The oneof
29748 * @returns {undefined}
29749 * @inner
29750 * @ignore
29751 */
29752function addFieldsToParent(oneof) {
29753 if (oneof.parent)
29754 for (var i = 0; i < oneof.fieldsArray.length; ++i)
29755 if (!oneof.fieldsArray[i].parent)
29756 oneof.parent.add(oneof.fieldsArray[i]);
29757}
29758
29759/**
29760 * Adds a field to this oneof and removes it from its current parent, if any.
29761 * @param {Field} field Field to add
29762 * @returns {OneOf} `this`
29763 */
29764OneOf.prototype.add = function add(field) {
29765
29766 /* istanbul ignore if */
29767 if (!(field instanceof Field))
29768 throw TypeError("field must be a Field");
29769
29770 if (field.parent && field.parent !== this.parent)
29771 field.parent.remove(field);
29772 this.oneof.push(field.name);
29773 this.fieldsArray.push(field);
29774 field.partOf = this; // field.parent remains null
29775 addFieldsToParent(this);
29776 return this;
29777};
29778
29779/**
29780 * Removes a field from this oneof and puts it back to the oneof's parent.
29781 * @param {Field} field Field to remove
29782 * @returns {OneOf} `this`
29783 */
29784OneOf.prototype.remove = function remove(field) {
29785
29786 /* istanbul ignore if */
29787 if (!(field instanceof Field))
29788 throw TypeError("field must be a Field");
29789
29790 var index = this.fieldsArray.indexOf(field);
29791
29792 /* istanbul ignore if */
29793 if (index < 0)
29794 throw Error(field + " is not a member of " + this);
29795
29796 this.fieldsArray.splice(index, 1);
29797 index = this.oneof.indexOf(field.name);
29798
29799 /* istanbul ignore else */
29800 if (index > -1) // theoretical
29801 this.oneof.splice(index, 1);
29802
29803 field.partOf = null;
29804 return this;
29805};
29806
29807/**
29808 * @override
29809 */
29810OneOf.prototype.onAdd = function onAdd(parent) {
29811 ReflectionObject.prototype.onAdd.call(this, parent);
29812 var self = this;
29813 // Collect present fields
29814 for (var i = 0; i < this.oneof.length; ++i) {
29815 var field = parent.get(this.oneof[i]);
29816 if (field && !field.partOf) {
29817 field.partOf = self;
29818 self.fieldsArray.push(field);
29819 }
29820 }
29821 // Add not yet present fields
29822 addFieldsToParent(this);
29823};
29824
29825/**
29826 * @override
29827 */
29828OneOf.prototype.onRemove = function onRemove(parent) {
29829 for (var i = 0, field; i < this.fieldsArray.length; ++i)
29830 if ((field = this.fieldsArray[i]).parent)
29831 field.parent.remove(field);
29832 ReflectionObject.prototype.onRemove.call(this, parent);
29833};
29834
29835/**
29836 * Decorator function as returned by {@link OneOf.d} (TypeScript).
29837 * @typedef OneOfDecorator
29838 * @type {function}
29839 * @param {Object} prototype Target prototype
29840 * @param {string} oneofName OneOf name
29841 * @returns {undefined}
29842 */
29843
29844/**
29845 * OneOf decorator (TypeScript).
29846 * @function
29847 * @param {...string} fieldNames Field names
29848 * @returns {OneOfDecorator} Decorator function
29849 * @template T extends string
29850 */
29851OneOf.d = function decorateOneOf() {
29852 var fieldNames = new Array(arguments.length),
29853 index = 0;
29854 while (index < arguments.length)
29855 fieldNames[index] = arguments[index++];
29856 return function oneOfDecorator(prototype, oneofName) {
29857 util.decorateType(prototype.constructor)
29858 .add(new OneOf(oneofName, fieldNames));
29859 Object.defineProperty(prototype, oneofName, {
29860 get: util.oneOfGetter(fieldNames),
29861 set: util.oneOfSetter(fieldNames)
29862 });
29863 };
29864};
29865
29866},{"./field":197,"./object":205,"./util":218}],207:[function(require,module,exports){
29867"use strict";
29868module.exports = parse;
29869
29870parse.filename = null;
29871parse.defaults = { keepCase: false };
29872
29873var tokenize = require("./tokenize"),
29874 Root = require("./root"),
29875 Type = require("./type"),
29876 Field = require("./field"),
29877 MapField = require("./mapfield"),
29878 OneOf = require("./oneof"),
29879 Enum = require("./enum"),
29880 Service = require("./service"),
29881 Method = require("./method"),
29882 types = require("./types"),
29883 util = require("./util");
29884
29885var base10Re = /^[1-9][0-9]*$/,
29886 base10NegRe = /^-?[1-9][0-9]*$/,
29887 base16Re = /^0[x][0-9a-fA-F]+$/,
29888 base16NegRe = /^-?0[x][0-9a-fA-F]+$/,
29889 base8Re = /^0[0-7]+$/,
29890 base8NegRe = /^-?0[0-7]+$/,
29891 numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,
29892 nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/,
29893 typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,
29894 fqTypeRefRe = /^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;
29895
29896/**
29897 * Result object returned from {@link parse}.
29898 * @interface IParserResult
29899 * @property {string|undefined} package Package name, if declared
29900 * @property {string[]|undefined} imports Imports, if any
29901 * @property {string[]|undefined} weakImports Weak imports, if any
29902 * @property {string|undefined} syntax Syntax, if specified (either `"proto2"` or `"proto3"`)
29903 * @property {Root} root Populated root instance
29904 */
29905
29906/**
29907 * Options modifying the behavior of {@link parse}.
29908 * @interface IParseOptions
29909 * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case
29910 * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments.
29911 */
29912
29913/**
29914 * Options modifying the behavior of JSON serialization.
29915 * @interface IToJSONOptions
29916 * @property {boolean} [keepComments=false] Serializes comments.
29917 */
29918
29919/**
29920 * Parses the given .proto source and returns an object with the parsed contents.
29921 * @param {string} source Source contents
29922 * @param {Root} root Root to populate
29923 * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
29924 * @returns {IParserResult} Parser result
29925 * @property {string} filename=null Currently processing file name for error reporting, if known
29926 * @property {IParseOptions} defaults Default {@link IParseOptions}
29927 */
29928function parse(source, root, options) {
29929 /* eslint-disable callback-return */
29930 if (!(root instanceof Root)) {
29931 options = root;
29932 root = new Root();
29933 }
29934 if (!options)
29935 options = parse.defaults;
29936
29937 var tn = tokenize(source, options.alternateCommentMode || false),
29938 next = tn.next,
29939 push = tn.push,
29940 peek = tn.peek,
29941 skip = tn.skip,
29942 cmnt = tn.cmnt;
29943
29944 var head = true,
29945 pkg,
29946 imports,
29947 weakImports,
29948 syntax,
29949 isProto3 = false;
29950
29951 var ptr = root;
29952
29953 var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase;
29954
29955 /* istanbul ignore next */
29956 function illegal(token, name, insideTryCatch) {
29957 var filename = parse.filename;
29958 if (!insideTryCatch)
29959 parse.filename = null;
29960 return Error("illegal " + (name || "token") + " '" + token + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")");
29961 }
29962
29963 function readString() {
29964 var values = [],
29965 token;
29966 do {
29967 /* istanbul ignore if */
29968 if ((token = next()) !== "\"" && token !== "'")
29969 throw illegal(token);
29970
29971 values.push(next());
29972 skip(token);
29973 token = peek();
29974 } while (token === "\"" || token === "'");
29975 return values.join("");
29976 }
29977
29978 function readValue(acceptTypeRef) {
29979 var token = next();
29980 switch (token) {
29981 case "'":
29982 case "\"":
29983 push(token);
29984 return readString();
29985 case "true": case "TRUE":
29986 return true;
29987 case "false": case "FALSE":
29988 return false;
29989 }
29990 try {
29991 return parseNumber(token, /* insideTryCatch */ true);
29992 } catch (e) {
29993
29994 /* istanbul ignore else */
29995 if (acceptTypeRef && typeRefRe.test(token))
29996 return token;
29997
29998 /* istanbul ignore next */
29999 throw illegal(token, "value");
30000 }
30001 }
30002
30003 function readRanges(target, acceptStrings) {
30004 var token, start;
30005 do {
30006 if (acceptStrings && ((token = peek()) === "\"" || token === "'"))
30007 target.push(readString());
30008 else
30009 target.push([ start = parseId(next()), skip("to", true) ? parseId(next()) : start ]);
30010 } while (skip(",", true));
30011 skip(";");
30012 }
30013
30014 function parseNumber(token, insideTryCatch) {
30015 var sign = 1;
30016 if (token.charAt(0) === "-") {
30017 sign = -1;
30018 token = token.substring(1);
30019 }
30020 switch (token) {
30021 case "inf": case "INF": case "Inf":
30022 return sign * Infinity;
30023 case "nan": case "NAN": case "Nan": case "NaN":
30024 return NaN;
30025 case "0":
30026 return 0;
30027 }
30028 if (base10Re.test(token))
30029 return sign * parseInt(token, 10);
30030 if (base16Re.test(token))
30031 return sign * parseInt(token, 16);
30032 if (base8Re.test(token))
30033 return sign * parseInt(token, 8);
30034
30035 /* istanbul ignore else */
30036 if (numberRe.test(token))
30037 return sign * parseFloat(token);
30038
30039 /* istanbul ignore next */
30040 throw illegal(token, "number", insideTryCatch);
30041 }
30042
30043 function parseId(token, acceptNegative) {
30044 switch (token) {
30045 case "max": case "MAX": case "Max":
30046 return 536870911;
30047 case "0":
30048 return 0;
30049 }
30050
30051 /* istanbul ignore if */
30052 if (!acceptNegative && token.charAt(0) === "-")
30053 throw illegal(token, "id");
30054
30055 if (base10NegRe.test(token))
30056 return parseInt(token, 10);
30057 if (base16NegRe.test(token))
30058 return parseInt(token, 16);
30059
30060 /* istanbul ignore else */
30061 if (base8NegRe.test(token))
30062 return parseInt(token, 8);
30063
30064 /* istanbul ignore next */
30065 throw illegal(token, "id");
30066 }
30067
30068 function parsePackage() {
30069
30070 /* istanbul ignore if */
30071 if (pkg !== undefined)
30072 throw illegal("package");
30073
30074 pkg = next();
30075
30076 /* istanbul ignore if */
30077 if (!typeRefRe.test(pkg))
30078 throw illegal(pkg, "name");
30079
30080 ptr = ptr.define(pkg);
30081 skip(";");
30082 }
30083
30084 function parseImport() {
30085 var token = peek();
30086 var whichImports;
30087 switch (token) {
30088 case "weak":
30089 whichImports = weakImports || (weakImports = []);
30090 next();
30091 break;
30092 case "public":
30093 next();
30094 // eslint-disable-line no-fallthrough
30095 default:
30096 whichImports = imports || (imports = []);
30097 break;
30098 }
30099 token = readString();
30100 skip(";");
30101 whichImports.push(token);
30102 }
30103
30104 function parseSyntax() {
30105 skip("=");
30106 syntax = readString();
30107 isProto3 = syntax === "proto3";
30108
30109 /* istanbul ignore if */
30110 if (!isProto3 && syntax !== "proto2")
30111 throw illegal(syntax, "syntax");
30112
30113 skip(";");
30114 }
30115
30116 function parseCommon(parent, token) {
30117 switch (token) {
30118
30119 case "option":
30120 parseOption(parent, token);
30121 skip(";");
30122 return true;
30123
30124 case "message":
30125 parseType(parent, token);
30126 return true;
30127
30128 case "enum":
30129 parseEnum(parent, token);
30130 return true;
30131
30132 case "service":
30133 parseService(parent, token);
30134 return true;
30135
30136 case "extend":
30137 parseExtension(parent, token);
30138 return true;
30139 }
30140 return false;
30141 }
30142
30143 function ifBlock(obj, fnIf, fnElse) {
30144 var trailingLine = tn.line;
30145 if (obj) {
30146 obj.comment = cmnt(); // try block-type comment
30147 obj.filename = parse.filename;
30148 }
30149 if (skip("{", true)) {
30150 var token;
30151 while ((token = next()) !== "}")
30152 fnIf(token);
30153 skip(";", true);
30154 } else {
30155 if (fnElse)
30156 fnElse();
30157 skip(";");
30158 if (obj && typeof obj.comment !== "string")
30159 obj.comment = cmnt(trailingLine); // try line-type comment if no block
30160 }
30161 }
30162
30163 function parseType(parent, token) {
30164
30165 /* istanbul ignore if */
30166 if (!nameRe.test(token = next()))
30167 throw illegal(token, "type name");
30168
30169 var type = new Type(token);
30170 ifBlock(type, function parseType_block(token) {
30171 if (parseCommon(type, token))
30172 return;
30173
30174 switch (token) {
30175
30176 case "map":
30177 parseMapField(type, token);
30178 break;
30179
30180 case "required":
30181 case "optional":
30182 case "repeated":
30183 parseField(type, token);
30184 break;
30185
30186 case "oneof":
30187 parseOneOf(type, token);
30188 break;
30189
30190 case "extensions":
30191 readRanges(type.extensions || (type.extensions = []));
30192 break;
30193
30194 case "reserved":
30195 readRanges(type.reserved || (type.reserved = []), true);
30196 break;
30197
30198 default:
30199 /* istanbul ignore if */
30200 if (!isProto3 || !typeRefRe.test(token))
30201 throw illegal(token);
30202
30203 push(token);
30204 parseField(type, "optional");
30205 break;
30206 }
30207 });
30208 parent.add(type);
30209 }
30210
30211 function parseField(parent, rule, extend) {
30212 var type = next();
30213 if (type === "group") {
30214 parseGroup(parent, rule);
30215 return;
30216 }
30217
30218 /* istanbul ignore if */
30219 if (!typeRefRe.test(type))
30220 throw illegal(type, "type");
30221
30222 var name = next();
30223
30224 /* istanbul ignore if */
30225 if (!nameRe.test(name))
30226 throw illegal(name, "name");
30227
30228 name = applyCase(name);
30229 skip("=");
30230
30231 var field = new Field(name, parseId(next()), type, rule, extend);
30232 ifBlock(field, function parseField_block(token) {
30233
30234 /* istanbul ignore else */
30235 if (token === "option") {
30236 parseOption(field, token);
30237 skip(";");
30238 } else
30239 throw illegal(token);
30240
30241 }, function parseField_line() {
30242 parseInlineOptions(field);
30243 });
30244 parent.add(field);
30245
30246 // JSON defaults to packed=true if not set so we have to set packed=false explicity when
30247 // parsing proto2 descriptors without the option, where applicable. This must be done for
30248 // all known packable types and anything that could be an enum (= is not a basic type).
30249 if (!isProto3 && field.repeated && (types.packed[type] !== undefined || types.basic[type] === undefined))
30250 field.setOption("packed", false, /* ifNotSet */ true);
30251 }
30252
30253 function parseGroup(parent, rule) {
30254 var name = next();
30255
30256 /* istanbul ignore if */
30257 if (!nameRe.test(name))
30258 throw illegal(name, "name");
30259
30260 var fieldName = util.lcFirst(name);
30261 if (name === fieldName)
30262 name = util.ucFirst(name);
30263 skip("=");
30264 var id = parseId(next());
30265 var type = new Type(name);
30266 type.group = true;
30267 var field = new Field(fieldName, id, name, rule);
30268 field.filename = parse.filename;
30269 ifBlock(type, function parseGroup_block(token) {
30270 switch (token) {
30271
30272 case "option":
30273 parseOption(type, token);
30274 skip(";");
30275 break;
30276
30277 case "required":
30278 case "optional":
30279 case "repeated":
30280 parseField(type, token);
30281 break;
30282
30283 /* istanbul ignore next */
30284 default:
30285 throw illegal(token); // there are no groups with proto3 semantics
30286 }
30287 });
30288 parent.add(type)
30289 .add(field);
30290 }
30291
30292 function parseMapField(parent) {
30293 skip("<");
30294 var keyType = next();
30295
30296 /* istanbul ignore if */
30297 if (types.mapKey[keyType] === undefined)
30298 throw illegal(keyType, "type");
30299
30300 skip(",");
30301 var valueType = next();
30302
30303 /* istanbul ignore if */
30304 if (!typeRefRe.test(valueType))
30305 throw illegal(valueType, "type");
30306
30307 skip(">");
30308 var name = next();
30309
30310 /* istanbul ignore if */
30311 if (!nameRe.test(name))
30312 throw illegal(name, "name");
30313
30314 skip("=");
30315 var field = new MapField(applyCase(name), parseId(next()), keyType, valueType);
30316 ifBlock(field, function parseMapField_block(token) {
30317
30318 /* istanbul ignore else */
30319 if (token === "option") {
30320 parseOption(field, token);
30321 skip(";");
30322 } else
30323 throw illegal(token);
30324
30325 }, function parseMapField_line() {
30326 parseInlineOptions(field);
30327 });
30328 parent.add(field);
30329 }
30330
30331 function parseOneOf(parent, token) {
30332
30333 /* istanbul ignore if */
30334 if (!nameRe.test(token = next()))
30335 throw illegal(token, "name");
30336
30337 var oneof = new OneOf(applyCase(token));
30338 ifBlock(oneof, function parseOneOf_block(token) {
30339 if (token === "option") {
30340 parseOption(oneof, token);
30341 skip(";");
30342 } else {
30343 push(token);
30344 parseField(oneof, "optional");
30345 }
30346 });
30347 parent.add(oneof);
30348 }
30349
30350 function parseEnum(parent, token) {
30351
30352 /* istanbul ignore if */
30353 if (!nameRe.test(token = next()))
30354 throw illegal(token, "name");
30355
30356 var enm = new Enum(token);
30357 ifBlock(enm, function parseEnum_block(token) {
30358 switch(token) {
30359 case "option":
30360 parseOption(enm, token);
30361 skip(";");
30362 break;
30363
30364 case "reserved":
30365 readRanges(enm.reserved || (enm.reserved = []), true);
30366 break;
30367
30368 default:
30369 parseEnumValue(enm, token);
30370 }
30371 });
30372 parent.add(enm);
30373 }
30374
30375 function parseEnumValue(parent, token) {
30376
30377 /* istanbul ignore if */
30378 if (!nameRe.test(token))
30379 throw illegal(token, "name");
30380
30381 skip("=");
30382 var value = parseId(next(), true),
30383 dummy = {};
30384 ifBlock(dummy, function parseEnumValue_block(token) {
30385
30386 /* istanbul ignore else */
30387 if (token === "option") {
30388 parseOption(dummy, token); // skip
30389 skip(";");
30390 } else
30391 throw illegal(token);
30392
30393 }, function parseEnumValue_line() {
30394 parseInlineOptions(dummy); // skip
30395 });
30396 parent.add(token, value, dummy.comment);
30397 }
30398
30399 function parseOption(parent, token) {
30400 var isCustom = skip("(", true);
30401
30402 /* istanbul ignore if */
30403 if (!typeRefRe.test(token = next()))
30404 throw illegal(token, "name");
30405
30406 var name = token;
30407 if (isCustom) {
30408 skip(")");
30409 name = "(" + name + ")";
30410 token = peek();
30411 if (fqTypeRefRe.test(token)) {
30412 name += token;
30413 next();
30414 }
30415 }
30416 skip("=");
30417 parseOptionValue(parent, name);
30418 }
30419
30420 function parseOptionValue(parent, name) {
30421 if (skip("{", true)) { // { a: "foo" b { c: "bar" } }
30422 do {
30423 /* istanbul ignore if */
30424 if (!nameRe.test(token = next()))
30425 throw illegal(token, "name");
30426
30427 if (peek() === "{")
30428 parseOptionValue(parent, name + "." + token);
30429 else {
30430 skip(":");
30431 if (peek() === "{")
30432 parseOptionValue(parent, name + "." + token);
30433 else
30434 setOption(parent, name + "." + token, readValue(true));
30435 }
30436 } while (!skip("}", true));
30437 } else
30438 setOption(parent, name, readValue(true));
30439 // Does not enforce a delimiter to be universal
30440 }
30441
30442 function setOption(parent, name, value) {
30443 if (parent.setOption)
30444 parent.setOption(name, value);
30445 }
30446
30447 function parseInlineOptions(parent) {
30448 if (skip("[", true)) {
30449 do {
30450 parseOption(parent, "option");
30451 } while (skip(",", true));
30452 skip("]");
30453 }
30454 return parent;
30455 }
30456
30457 function parseService(parent, token) {
30458
30459 /* istanbul ignore if */
30460 if (!nameRe.test(token = next()))
30461 throw illegal(token, "service name");
30462
30463 var service = new Service(token);
30464 ifBlock(service, function parseService_block(token) {
30465 if (parseCommon(service, token))
30466 return;
30467
30468 /* istanbul ignore else */
30469 if (token === "rpc")
30470 parseMethod(service, token);
30471 else
30472 throw illegal(token);
30473 });
30474 parent.add(service);
30475 }
30476
30477 function parseMethod(parent, token) {
30478 var type = token;
30479
30480 /* istanbul ignore if */
30481 if (!nameRe.test(token = next()))
30482 throw illegal(token, "name");
30483
30484 var name = token,
30485 requestType, requestStream,
30486 responseType, responseStream;
30487
30488 skip("(");
30489 if (skip("stream", true))
30490 requestStream = true;
30491
30492 /* istanbul ignore if */
30493 if (!typeRefRe.test(token = next()))
30494 throw illegal(token);
30495
30496 requestType = token;
30497 skip(")"); skip("returns"); skip("(");
30498 if (skip("stream", true))
30499 responseStream = true;
30500
30501 /* istanbul ignore if */
30502 if (!typeRefRe.test(token = next()))
30503 throw illegal(token);
30504
30505 responseType = token;
30506 skip(")");
30507
30508 var method = new Method(name, type, requestType, responseType, requestStream, responseStream);
30509 ifBlock(method, function parseMethod_block(token) {
30510
30511 /* istanbul ignore else */
30512 if (token === "option") {
30513 parseOption(method, token);
30514 skip(";");
30515 } else
30516 throw illegal(token);
30517
30518 });
30519 parent.add(method);
30520 }
30521
30522 function parseExtension(parent, token) {
30523
30524 /* istanbul ignore if */
30525 if (!typeRefRe.test(token = next()))
30526 throw illegal(token, "reference");
30527
30528 var reference = token;
30529 ifBlock(null, function parseExtension_block(token) {
30530 switch (token) {
30531
30532 case "required":
30533 case "repeated":
30534 case "optional":
30535 parseField(parent, token, reference);
30536 break;
30537
30538 default:
30539 /* istanbul ignore if */
30540 if (!isProto3 || !typeRefRe.test(token))
30541 throw illegal(token);
30542 push(token);
30543 parseField(parent, "optional", reference);
30544 break;
30545 }
30546 });
30547 }
30548
30549 var token;
30550 while ((token = next()) !== null) {
30551 switch (token) {
30552
30553 case "package":
30554
30555 /* istanbul ignore if */
30556 if (!head)
30557 throw illegal(token);
30558
30559 parsePackage();
30560 break;
30561
30562 case "import":
30563
30564 /* istanbul ignore if */
30565 if (!head)
30566 throw illegal(token);
30567
30568 parseImport();
30569 break;
30570
30571 case "syntax":
30572
30573 /* istanbul ignore if */
30574 if (!head)
30575 throw illegal(token);
30576
30577 parseSyntax();
30578 break;
30579
30580 case "option":
30581
30582 /* istanbul ignore if */
30583 if (!head)
30584 throw illegal(token);
30585
30586 parseOption(ptr, token);
30587 skip(";");
30588 break;
30589
30590 default:
30591
30592 /* istanbul ignore else */
30593 if (parseCommon(ptr, token)) {
30594 head = false;
30595 continue;
30596 }
30597
30598 /* istanbul ignore next */
30599 throw illegal(token);
30600 }
30601 }
30602
30603 parse.filename = null;
30604 return {
30605 "package" : pkg,
30606 "imports" : imports,
30607 weakImports : weakImports,
30608 syntax : syntax,
30609 root : root
30610 };
30611}
30612
30613/**
30614 * Parses the given .proto source and returns an object with the parsed contents.
30615 * @name parse
30616 * @function
30617 * @param {string} source Source contents
30618 * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
30619 * @returns {IParserResult} Parser result
30620 * @property {string} filename=null Currently processing file name for error reporting, if known
30621 * @property {IParseOptions} defaults Default {@link IParseOptions}
30622 * @variation 2
30623 */
30624
30625},{"./enum":196,"./field":197,"./mapfield":201,"./method":203,"./oneof":206,"./root":210,"./service":214,"./tokenize":215,"./type":216,"./types":217,"./util":218}],208:[function(require,module,exports){
30626"use strict";
30627module.exports = Reader;
30628
30629var util = require("./util/minimal");
30630
30631var BufferReader; // cyclic
30632
30633var LongBits = util.LongBits,
30634 utf8 = util.utf8;
30635
30636/* istanbul ignore next */
30637function indexOutOfRange(reader, writeLength) {
30638 return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len);
30639}
30640
30641/**
30642 * Constructs a new reader instance using the specified buffer.
30643 * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.
30644 * @constructor
30645 * @param {Uint8Array} buffer Buffer to read from
30646 */
30647function Reader(buffer) {
30648
30649 /**
30650 * Read buffer.
30651 * @type {Uint8Array}
30652 */
30653 this.buf = buffer;
30654
30655 /**
30656 * Read buffer position.
30657 * @type {number}
30658 */
30659 this.pos = 0;
30660
30661 /**
30662 * Read buffer length.
30663 * @type {number}
30664 */
30665 this.len = buffer.length;
30666}
30667
30668var create_array = typeof Uint8Array !== "undefined"
30669 ? function create_typed_array(buffer) {
30670 if (buffer instanceof Uint8Array || Array.isArray(buffer))
30671 return new Reader(buffer);
30672 throw Error("illegal buffer");
30673 }
30674 /* istanbul ignore next */
30675 : function create_array(buffer) {
30676 if (Array.isArray(buffer))
30677 return new Reader(buffer);
30678 throw Error("illegal buffer");
30679 };
30680
30681/**
30682 * Creates a new reader using the specified buffer.
30683 * @function
30684 * @param {Uint8Array|Buffer} buffer Buffer to read from
30685 * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}
30686 * @throws {Error} If `buffer` is not a valid buffer
30687 */
30688Reader.create = util.Buffer
30689 ? function create_buffer_setup(buffer) {
30690 return (Reader.create = function create_buffer(buffer) {
30691 return util.Buffer.isBuffer(buffer)
30692 ? new BufferReader(buffer)
30693 /* istanbul ignore next */
30694 : create_array(buffer);
30695 })(buffer);
30696 }
30697 /* istanbul ignore next */
30698 : create_array;
30699
30700Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;
30701
30702/**
30703 * Reads a varint as an unsigned 32 bit value.
30704 * @function
30705 * @returns {number} Value read
30706 */
30707Reader.prototype.uint32 = (function read_uint32_setup() {
30708 var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)
30709 return function read_uint32() {
30710 value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;
30711 value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;
30712 value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;
30713 value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;
30714 value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;
30715
30716 /* istanbul ignore if */
30717 if ((this.pos += 5) > this.len) {
30718 this.pos = this.len;
30719 throw indexOutOfRange(this, 10);
30720 }
30721 return value;
30722 };
30723})();
30724
30725/**
30726 * Reads a varint as a signed 32 bit value.
30727 * @returns {number} Value read
30728 */
30729Reader.prototype.int32 = function read_int32() {
30730 return this.uint32() | 0;
30731};
30732
30733/**
30734 * Reads a zig-zag encoded varint as a signed 32 bit value.
30735 * @returns {number} Value read
30736 */
30737Reader.prototype.sint32 = function read_sint32() {
30738 var value = this.uint32();
30739 return value >>> 1 ^ -(value & 1) | 0;
30740};
30741
30742/* eslint-disable no-invalid-this */
30743
30744function readLongVarint() {
30745 // tends to deopt with local vars for octet etc.
30746 var bits = new LongBits(0, 0);
30747 var i = 0;
30748 if (this.len - this.pos > 4) { // fast route (lo)
30749 for (; i < 4; ++i) {
30750 // 1st..4th
30751 bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
30752 if (this.buf[this.pos++] < 128)
30753 return bits;
30754 }
30755 // 5th
30756 bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;
30757 bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;
30758 if (this.buf[this.pos++] < 128)
30759 return bits;
30760 i = 0;
30761 } else {
30762 for (; i < 3; ++i) {
30763 /* istanbul ignore if */
30764 if (this.pos >= this.len)
30765 throw indexOutOfRange(this);
30766 // 1st..3th
30767 bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;
30768 if (this.buf[this.pos++] < 128)
30769 return bits;
30770 }
30771 // 4th
30772 bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;
30773 return bits;
30774 }
30775 if (this.len - this.pos > 4) { // fast route (hi)
30776 for (; i < 5; ++i) {
30777 // 6th..10th
30778 bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
30779 if (this.buf[this.pos++] < 128)
30780 return bits;
30781 }
30782 } else {
30783 for (; i < 5; ++i) {
30784 /* istanbul ignore if */
30785 if (this.pos >= this.len)
30786 throw indexOutOfRange(this);
30787 // 6th..10th
30788 bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;
30789 if (this.buf[this.pos++] < 128)
30790 return bits;
30791 }
30792 }
30793 /* istanbul ignore next */
30794 throw Error("invalid varint encoding");
30795}
30796
30797/* eslint-enable no-invalid-this */
30798
30799/**
30800 * Reads a varint as a signed 64 bit value.
30801 * @name Reader#int64
30802 * @function
30803 * @returns {Long} Value read
30804 */
30805
30806/**
30807 * Reads a varint as an unsigned 64 bit value.
30808 * @name Reader#uint64
30809 * @function
30810 * @returns {Long} Value read
30811 */
30812
30813/**
30814 * Reads a zig-zag encoded varint as a signed 64 bit value.
30815 * @name Reader#sint64
30816 * @function
30817 * @returns {Long} Value read
30818 */
30819
30820/**
30821 * Reads a varint as a boolean.
30822 * @returns {boolean} Value read
30823 */
30824Reader.prototype.bool = function read_bool() {
30825 return this.uint32() !== 0;
30826};
30827
30828function readFixed32_end(buf, end) { // note that this uses `end`, not `pos`
30829 return (buf[end - 4]
30830 | buf[end - 3] << 8
30831 | buf[end - 2] << 16
30832 | buf[end - 1] << 24) >>> 0;
30833}
30834
30835/**
30836 * Reads fixed 32 bits as an unsigned 32 bit integer.
30837 * @returns {number} Value read
30838 */
30839Reader.prototype.fixed32 = function read_fixed32() {
30840
30841 /* istanbul ignore if */
30842 if (this.pos + 4 > this.len)
30843 throw indexOutOfRange(this, 4);
30844
30845 return readFixed32_end(this.buf, this.pos += 4);
30846};
30847
30848/**
30849 * Reads fixed 32 bits as a signed 32 bit integer.
30850 * @returns {number} Value read
30851 */
30852Reader.prototype.sfixed32 = function read_sfixed32() {
30853
30854 /* istanbul ignore if */
30855 if (this.pos + 4 > this.len)
30856 throw indexOutOfRange(this, 4);
30857
30858 return readFixed32_end(this.buf, this.pos += 4) | 0;
30859};
30860
30861/* eslint-disable no-invalid-this */
30862
30863function readFixed64(/* this: Reader */) {
30864
30865 /* istanbul ignore if */
30866 if (this.pos + 8 > this.len)
30867 throw indexOutOfRange(this, 8);
30868
30869 return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));
30870}
30871
30872/* eslint-enable no-invalid-this */
30873
30874/**
30875 * Reads fixed 64 bits.
30876 * @name Reader#fixed64
30877 * @function
30878 * @returns {Long} Value read
30879 */
30880
30881/**
30882 * Reads zig-zag encoded fixed 64 bits.
30883 * @name Reader#sfixed64
30884 * @function
30885 * @returns {Long} Value read
30886 */
30887
30888/**
30889 * Reads a float (32 bit) as a number.
30890 * @function
30891 * @returns {number} Value read
30892 */
30893Reader.prototype.float = function read_float() {
30894
30895 /* istanbul ignore if */
30896 if (this.pos + 4 > this.len)
30897 throw indexOutOfRange(this, 4);
30898
30899 var value = util.float.readFloatLE(this.buf, this.pos);
30900 this.pos += 4;
30901 return value;
30902};
30903
30904/**
30905 * Reads a double (64 bit float) as a number.
30906 * @function
30907 * @returns {number} Value read
30908 */
30909Reader.prototype.double = function read_double() {
30910
30911 /* istanbul ignore if */
30912 if (this.pos + 8 > this.len)
30913 throw indexOutOfRange(this, 4);
30914
30915 var value = util.float.readDoubleLE(this.buf, this.pos);
30916 this.pos += 8;
30917 return value;
30918};
30919
30920/**
30921 * Reads a sequence of bytes preceeded by its length as a varint.
30922 * @returns {Uint8Array} Value read
30923 */
30924Reader.prototype.bytes = function read_bytes() {
30925 var length = this.uint32(),
30926 start = this.pos,
30927 end = this.pos + length;
30928
30929 /* istanbul ignore if */
30930 if (end > this.len)
30931 throw indexOutOfRange(this, length);
30932
30933 this.pos += length;
30934 if (Array.isArray(this.buf)) // plain array
30935 return this.buf.slice(start, end);
30936 return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1
30937 ? new this.buf.constructor(0)
30938 : this._slice.call(this.buf, start, end);
30939};
30940
30941/**
30942 * Reads a string preceeded by its byte length as a varint.
30943 * @returns {string} Value read
30944 */
30945Reader.prototype.string = function read_string() {
30946 var bytes = this.bytes();
30947 return utf8.read(bytes, 0, bytes.length);
30948};
30949
30950/**
30951 * Skips the specified number of bytes if specified, otherwise skips a varint.
30952 * @param {number} [length] Length if known, otherwise a varint is assumed
30953 * @returns {Reader} `this`
30954 */
30955Reader.prototype.skip = function skip(length) {
30956 if (typeof length === "number") {
30957 /* istanbul ignore if */
30958 if (this.pos + length > this.len)
30959 throw indexOutOfRange(this, length);
30960 this.pos += length;
30961 } else {
30962 do {
30963 /* istanbul ignore if */
30964 if (this.pos >= this.len)
30965 throw indexOutOfRange(this);
30966 } while (this.buf[this.pos++] & 128);
30967 }
30968 return this;
30969};
30970
30971/**
30972 * Skips the next element of the specified wire type.
30973 * @param {number} wireType Wire type received
30974 * @returns {Reader} `this`
30975 */
30976Reader.prototype.skipType = function(wireType) {
30977 switch (wireType) {
30978 case 0:
30979 this.skip();
30980 break;
30981 case 1:
30982 this.skip(8);
30983 break;
30984 case 2:
30985 this.skip(this.uint32());
30986 break;
30987 case 3:
30988 do { // eslint-disable-line no-constant-condition
30989 if ((wireType = this.uint32() & 7) === 4)
30990 break;
30991 this.skipType(wireType);
30992 } while (true);
30993 break;
30994 case 5:
30995 this.skip(4);
30996 break;
30997
30998 /* istanbul ignore next */
30999 default:
31000 throw Error("invalid wire type " + wireType + " at offset " + this.pos);
31001 }
31002 return this;
31003};
31004
31005Reader._configure = function(BufferReader_) {
31006 BufferReader = BufferReader_;
31007
31008 var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber";
31009 util.merge(Reader.prototype, {
31010
31011 int64: function read_int64() {
31012 return readLongVarint.call(this)[fn](false);
31013 },
31014
31015 uint64: function read_uint64() {
31016 return readLongVarint.call(this)[fn](true);
31017 },
31018
31019 sint64: function read_sint64() {
31020 return readLongVarint.call(this).zzDecode()[fn](false);
31021 },
31022
31023 fixed64: function read_fixed64() {
31024 return readFixed64.call(this)[fn](true);
31025 },
31026
31027 sfixed64: function read_sfixed64() {
31028 return readFixed64.call(this)[fn](false);
31029 }
31030
31031 });
31032};
31033
31034},{"./util/minimal":220}],209:[function(require,module,exports){
31035"use strict";
31036module.exports = BufferReader;
31037
31038// extends Reader
31039var Reader = require("./reader");
31040(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;
31041
31042var util = require("./util/minimal");
31043
31044/**
31045 * Constructs a new buffer reader instance.
31046 * @classdesc Wire format reader using node buffers.
31047 * @extends Reader
31048 * @constructor
31049 * @param {Buffer} buffer Buffer to read from
31050 */
31051function BufferReader(buffer) {
31052 Reader.call(this, buffer);
31053
31054 /**
31055 * Read buffer.
31056 * @name BufferReader#buf
31057 * @type {Buffer}
31058 */
31059}
31060
31061/* istanbul ignore else */
31062if (util.Buffer)
31063 BufferReader.prototype._slice = util.Buffer.prototype.slice;
31064
31065/**
31066 * @override
31067 */
31068BufferReader.prototype.string = function read_string_buffer() {
31069 var len = this.uint32(); // modifies pos
31070 return this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len));
31071};
31072
31073/**
31074 * Reads a sequence of bytes preceeded by its length as a varint.
31075 * @name BufferReader#bytes
31076 * @function
31077 * @returns {Buffer} Value read
31078 */
31079
31080},{"./reader":208,"./util/minimal":220}],210:[function(require,module,exports){
31081"use strict";
31082module.exports = Root;
31083
31084// extends Namespace
31085var Namespace = require("./namespace");
31086((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root";
31087
31088var Field = require("./field"),
31089 Enum = require("./enum"),
31090 OneOf = require("./oneof"),
31091 util = require("./util");
31092
31093var Type, // cyclic
31094 parse, // might be excluded
31095 common; // "
31096
31097/**
31098 * Constructs a new root namespace instance.
31099 * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.
31100 * @extends NamespaceBase
31101 * @constructor
31102 * @param {Object.<string,*>} [options] Top level options
31103 */
31104function Root(options) {
31105 Namespace.call(this, "", options);
31106
31107 /**
31108 * Deferred extension fields.
31109 * @type {Field[]}
31110 */
31111 this.deferred = [];
31112
31113 /**
31114 * Resolved file names of loaded files.
31115 * @type {string[]}
31116 */
31117 this.files = [];
31118}
31119
31120/**
31121 * Loads a namespace descriptor into a root namespace.
31122 * @param {INamespace} json Nameespace descriptor
31123 * @param {Root} [root] Root namespace, defaults to create a new one if omitted
31124 * @returns {Root} Root namespace
31125 */
31126Root.fromJSON = function fromJSON(json, root) {
31127 if (!root)
31128 root = new Root();
31129 if (json.options)
31130 root.setOptions(json.options);
31131 return root.addJSON(json.nested);
31132};
31133
31134/**
31135 * Resolves the path of an imported file, relative to the importing origin.
31136 * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.
31137 * @function
31138 * @param {string} origin The file name of the importing file
31139 * @param {string} target The file name being imported
31140 * @returns {string|null} Resolved path to `target` or `null` to skip the file
31141 */
31142Root.prototype.resolvePath = util.path.resolve;
31143
31144// A symbol-like function to safely signal synchronous loading
31145/* istanbul ignore next */
31146function SYNC() {} // eslint-disable-line no-empty-function
31147
31148/**
31149 * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.
31150 * @param {string|string[]} filename Names of one or multiple files to load
31151 * @param {IParseOptions} options Parse options
31152 * @param {LoadCallback} callback Callback function
31153 * @returns {undefined}
31154 */
31155Root.prototype.load = function load(filename, options, callback) {
31156 if (typeof options === "function") {
31157 callback = options;
31158 options = undefined;
31159 }
31160 var self = this;
31161 if (!callback)
31162 return util.asPromise(load, self, filename, options);
31163
31164 var sync = callback === SYNC; // undocumented
31165
31166 // Finishes loading by calling the callback (exactly once)
31167 function finish(err, root) {
31168 /* istanbul ignore if */
31169 if (!callback)
31170 return;
31171 var cb = callback;
31172 callback = null;
31173 if (sync)
31174 throw err;
31175 cb(err, root);
31176 }
31177
31178 // Processes a single file
31179 function process(filename, source) {
31180 try {
31181 if (util.isString(source) && source.charAt(0) === "{")
31182 source = JSON.parse(source);
31183 if (!util.isString(source))
31184 self.setOptions(source.options).addJSON(source.nested);
31185 else {
31186 parse.filename = filename;
31187 var parsed = parse(source, self, options),
31188 resolved,
31189 i = 0;
31190 if (parsed.imports)
31191 for (; i < parsed.imports.length; ++i)
31192 if (resolved = self.resolvePath(filename, parsed.imports[i]))
31193 fetch(resolved);
31194 if (parsed.weakImports)
31195 for (i = 0; i < parsed.weakImports.length; ++i)
31196 if (resolved = self.resolvePath(filename, parsed.weakImports[i]))
31197 fetch(resolved, true);
31198 }
31199 } catch (err) {
31200 finish(err);
31201 }
31202 if (!sync && !queued)
31203 finish(null, self); // only once anyway
31204 }
31205
31206 // Fetches a single file
31207 function fetch(filename, weak) {
31208
31209 // Strip path if this file references a bundled definition
31210 var idx = filename.lastIndexOf("google/protobuf/");
31211 if (idx > -1) {
31212 var altname = filename.substring(idx);
31213 if (altname in common)
31214 filename = altname;
31215 }
31216
31217 // Skip if already loaded / attempted
31218 if (self.files.indexOf(filename) > -1)
31219 return;
31220 self.files.push(filename);
31221
31222 // Shortcut bundled definitions
31223 if (filename in common) {
31224 if (sync)
31225 process(filename, common[filename]);
31226 else {
31227 ++queued;
31228 setTimeout(function() {
31229 --queued;
31230 process(filename, common[filename]);
31231 });
31232 }
31233 return;
31234 }
31235
31236 // Otherwise fetch from disk or network
31237 if (sync) {
31238 var source;
31239 try {
31240 source = util.fs.readFileSync(filename).toString("utf8");
31241 } catch (err) {
31242 if (!weak)
31243 finish(err);
31244 return;
31245 }
31246 process(filename, source);
31247 } else {
31248 ++queued;
31249 util.fetch(filename, function(err, source) {
31250 --queued;
31251 /* istanbul ignore if */
31252 if (!callback)
31253 return; // terminated meanwhile
31254 if (err) {
31255 /* istanbul ignore else */
31256 if (!weak)
31257 finish(err);
31258 else if (!queued) // can't be covered reliably
31259 finish(null, self);
31260 return;
31261 }
31262 process(filename, source);
31263 });
31264 }
31265 }
31266 var queued = 0;
31267
31268 // Assembling the root namespace doesn't require working type
31269 // references anymore, so we can load everything in parallel
31270 if (util.isString(filename))
31271 filename = [ filename ];
31272 for (var i = 0, resolved; i < filename.length; ++i)
31273 if (resolved = self.resolvePath("", filename[i]))
31274 fetch(resolved);
31275
31276 if (sync)
31277 return self;
31278 if (!queued)
31279 finish(null, self);
31280 return undefined;
31281};
31282// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined
31283
31284/**
31285 * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.
31286 * @function Root#load
31287 * @param {string|string[]} filename Names of one or multiple files to load
31288 * @param {LoadCallback} callback Callback function
31289 * @returns {undefined}
31290 * @variation 2
31291 */
31292// function load(filename:string, callback:LoadCallback):undefined
31293
31294/**
31295 * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.
31296 * @function Root#load
31297 * @param {string|string[]} filename Names of one or multiple files to load
31298 * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
31299 * @returns {Promise<Root>} Promise
31300 * @variation 3
31301 */
31302// function load(filename:string, [options:IParseOptions]):Promise<Root>
31303
31304/**
31305 * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).
31306 * @function Root#loadSync
31307 * @param {string|string[]} filename Names of one or multiple files to load
31308 * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
31309 * @returns {Root} Root namespace
31310 * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid
31311 */
31312Root.prototype.loadSync = function loadSync(filename, options) {
31313 if (!util.isNode)
31314 throw Error("not supported");
31315 return this.load(filename, options, SYNC);
31316};
31317
31318/**
31319 * @override
31320 */
31321Root.prototype.resolveAll = function resolveAll() {
31322 if (this.deferred.length)
31323 throw Error("unresolvable extensions: " + this.deferred.map(function(field) {
31324 return "'extend " + field.extend + "' in " + field.parent.fullName;
31325 }).join(", "));
31326 return Namespace.prototype.resolveAll.call(this);
31327};
31328
31329// only uppercased (and thus conflict-free) children are exposed, see below
31330var exposeRe = /^[A-Z]/;
31331
31332/**
31333 * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.
31334 * @param {Root} root Root instance
31335 * @param {Field} field Declaring extension field witin the declaring type
31336 * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise
31337 * @inner
31338 * @ignore
31339 */
31340function tryHandleExtension(root, field) {
31341 var extendedType = field.parent.lookup(field.extend);
31342 if (extendedType) {
31343 var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);
31344 sisterField.declaringField = field;
31345 field.extensionField = sisterField;
31346 extendedType.add(sisterField);
31347 return true;
31348 }
31349 return false;
31350}
31351
31352/**
31353 * Called when any object is added to this root or its sub-namespaces.
31354 * @param {ReflectionObject} object Object added
31355 * @returns {undefined}
31356 * @private
31357 */
31358Root.prototype._handleAdd = function _handleAdd(object) {
31359 if (object instanceof Field) {
31360
31361 if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)
31362 if (!tryHandleExtension(this, object))
31363 this.deferred.push(object);
31364
31365 } else if (object instanceof Enum) {
31366
31367 if (exposeRe.test(object.name))
31368 object.parent[object.name] = object.values; // expose enum values as property of its parent
31369
31370 } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {
31371
31372 if (object instanceof Type) // Try to handle any deferred extensions
31373 for (var i = 0; i < this.deferred.length;)
31374 if (tryHandleExtension(this, this.deferred[i]))
31375 this.deferred.splice(i, 1);
31376 else
31377 ++i;
31378 for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace
31379 this._handleAdd(object._nestedArray[j]);
31380 if (exposeRe.test(object.name))
31381 object.parent[object.name] = object; // expose namespace as property of its parent
31382 }
31383
31384 // The above also adds uppercased (and thus conflict-free) nested types, services and enums as
31385 // properties of namespaces just like static code does. This allows using a .d.ts generated for
31386 // a static module with reflection-based solutions where the condition is met.
31387};
31388
31389/**
31390 * Called when any object is removed from this root or its sub-namespaces.
31391 * @param {ReflectionObject} object Object removed
31392 * @returns {undefined}
31393 * @private
31394 */
31395Root.prototype._handleRemove = function _handleRemove(object) {
31396 if (object instanceof Field) {
31397
31398 if (/* an extension field */ object.extend !== undefined) {
31399 if (/* already handled */ object.extensionField) { // remove its sister field
31400 object.extensionField.parent.remove(object.extensionField);
31401 object.extensionField = null;
31402 } else { // cancel the extension
31403 var index = this.deferred.indexOf(object);
31404 /* istanbul ignore else */
31405 if (index > -1)
31406 this.deferred.splice(index, 1);
31407 }
31408 }
31409
31410 } else if (object instanceof Enum) {
31411
31412 if (exposeRe.test(object.name))
31413 delete object.parent[object.name]; // unexpose enum values
31414
31415 } else if (object instanceof Namespace) {
31416
31417 for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace
31418 this._handleRemove(object._nestedArray[i]);
31419
31420 if (exposeRe.test(object.name))
31421 delete object.parent[object.name]; // unexpose namespaces
31422
31423 }
31424};
31425
31426Root._configure = function(Type_, parse_, common_) {
31427 Type = Type_;
31428 parse = parse_;
31429 common = common_;
31430};
31431
31432},{"./enum":196,"./field":197,"./namespace":204,"./oneof":206,"./util":218}],211:[function(require,module,exports){
31433"use strict";
31434module.exports = {};
31435
31436/**
31437 * Named roots.
31438 * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).
31439 * Can also be used manually to make roots available accross modules.
31440 * @name roots
31441 * @type {Object.<string,Root>}
31442 * @example
31443 * // pbjs -r myroot -o compiled.js ...
31444 *
31445 * // in another module:
31446 * require("./compiled.js");
31447 *
31448 * // in any subsequent module:
31449 * var root = protobuf.roots["myroot"];
31450 */
31451
31452},{}],212:[function(require,module,exports){
31453"use strict";
31454
31455/**
31456 * Streaming RPC helpers.
31457 * @namespace
31458 */
31459var rpc = exports;
31460
31461/**
31462 * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.
31463 * @typedef RPCImpl
31464 * @type {function}
31465 * @param {Method|rpc.ServiceMethod<Message<{}>,Message<{}>>} method Reflected or static method being called
31466 * @param {Uint8Array} requestData Request data
31467 * @param {RPCImplCallback} callback Callback function
31468 * @returns {undefined}
31469 * @example
31470 * function rpcImpl(method, requestData, callback) {
31471 * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code
31472 * throw Error("no such method");
31473 * asynchronouslyObtainAResponse(requestData, function(err, responseData) {
31474 * callback(err, responseData);
31475 * });
31476 * }
31477 */
31478
31479/**
31480 * Node-style callback as used by {@link RPCImpl}.
31481 * @typedef RPCImplCallback
31482 * @type {function}
31483 * @param {Error|null} error Error, if any, otherwise `null`
31484 * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error
31485 * @returns {undefined}
31486 */
31487
31488rpc.Service = require("./rpc/service");
31489
31490},{"./rpc/service":213}],213:[function(require,module,exports){
31491"use strict";
31492module.exports = Service;
31493
31494var util = require("../util/minimal");
31495
31496// Extends EventEmitter
31497(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;
31498
31499/**
31500 * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.
31501 *
31502 * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.
31503 * @typedef rpc.ServiceMethodCallback
31504 * @template TRes extends Message<TRes>
31505 * @type {function}
31506 * @param {Error|null} error Error, if any
31507 * @param {TRes} [response] Response message
31508 * @returns {undefined}
31509 */
31510
31511/**
31512 * A service method part of a {@link rpc.Service} as created by {@link Service.create}.
31513 * @typedef rpc.ServiceMethod
31514 * @template TReq extends Message<TReq>
31515 * @template TRes extends Message<TRes>
31516 * @type {function}
31517 * @param {TReq|Properties<TReq>} request Request message or plain object
31518 * @param {rpc.ServiceMethodCallback<TRes>} [callback] Node-style callback called with the error, if any, and the response message
31519 * @returns {Promise<Message<TRes>>} Promise if `callback` has been omitted, otherwise `undefined`
31520 */
31521
31522/**
31523 * Constructs a new RPC service instance.
31524 * @classdesc An RPC service as returned by {@link Service#create}.
31525 * @exports rpc.Service
31526 * @extends util.EventEmitter
31527 * @constructor
31528 * @param {RPCImpl} rpcImpl RPC implementation
31529 * @param {boolean} [requestDelimited=false] Whether requests are length-delimited
31530 * @param {boolean} [responseDelimited=false] Whether responses are length-delimited
31531 */
31532function Service(rpcImpl, requestDelimited, responseDelimited) {
31533
31534 if (typeof rpcImpl !== "function")
31535 throw TypeError("rpcImpl must be a function");
31536
31537 util.EventEmitter.call(this);
31538
31539 /**
31540 * RPC implementation. Becomes `null` once the service is ended.
31541 * @type {RPCImpl|null}
31542 */
31543 this.rpcImpl = rpcImpl;
31544
31545 /**
31546 * Whether requests are length-delimited.
31547 * @type {boolean}
31548 */
31549 this.requestDelimited = Boolean(requestDelimited);
31550
31551 /**
31552 * Whether responses are length-delimited.
31553 * @type {boolean}
31554 */
31555 this.responseDelimited = Boolean(responseDelimited);
31556}
31557
31558/**
31559 * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.
31560 * @param {Method|rpc.ServiceMethod<TReq,TRes>} method Reflected or static method
31561 * @param {Constructor<TReq>} requestCtor Request constructor
31562 * @param {Constructor<TRes>} responseCtor Response constructor
31563 * @param {TReq|Properties<TReq>} request Request message or plain object
31564 * @param {rpc.ServiceMethodCallback<TRes>} callback Service callback
31565 * @returns {undefined}
31566 * @template TReq extends Message<TReq>
31567 * @template TRes extends Message<TRes>
31568 */
31569Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {
31570
31571 if (!request)
31572 throw TypeError("request must be specified");
31573
31574 var self = this;
31575 if (!callback)
31576 return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);
31577
31578 if (!self.rpcImpl) {
31579 setTimeout(function() { callback(Error("already ended")); }, 0);
31580 return undefined;
31581 }
31582
31583 try {
31584 return self.rpcImpl(
31585 method,
31586 requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(),
31587 function rpcCallback(err, response) {
31588
31589 if (err) {
31590 self.emit("error", err, method);
31591 return callback(err);
31592 }
31593
31594 if (response === null) {
31595 self.end(/* endedByRPC */ true);
31596 return undefined;
31597 }
31598
31599 if (!(response instanceof responseCtor)) {
31600 try {
31601 response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response);
31602 } catch (err) {
31603 self.emit("error", err, method);
31604 return callback(err);
31605 }
31606 }
31607
31608 self.emit("data", response, method);
31609 return callback(null, response);
31610 }
31611 );
31612 } catch (err) {
31613 self.emit("error", err, method);
31614 setTimeout(function() { callback(err); }, 0);
31615 return undefined;
31616 }
31617};
31618
31619/**
31620 * Ends this service and emits the `end` event.
31621 * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.
31622 * @returns {rpc.Service} `this`
31623 */
31624Service.prototype.end = function end(endedByRPC) {
31625 if (this.rpcImpl) {
31626 if (!endedByRPC) // signal end to rpcImpl
31627 this.rpcImpl(null, null, null);
31628 this.rpcImpl = null;
31629 this.emit("end").off();
31630 }
31631 return this;
31632};
31633
31634},{"../util/minimal":220}],214:[function(require,module,exports){
31635"use strict";
31636module.exports = Service;
31637
31638// extends Namespace
31639var Namespace = require("./namespace");
31640((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service";
31641
31642var Method = require("./method"),
31643 util = require("./util"),
31644 rpc = require("./rpc");
31645
31646/**
31647 * Constructs a new service instance.
31648 * @classdesc Reflected service.
31649 * @extends NamespaceBase
31650 * @constructor
31651 * @param {string} name Service name
31652 * @param {Object.<string,*>} [options] Service options
31653 * @throws {TypeError} If arguments are invalid
31654 */
31655function Service(name, options) {
31656 Namespace.call(this, name, options);
31657
31658 /**
31659 * Service methods.
31660 * @type {Object.<string,Method>}
31661 */
31662 this.methods = {}; // toJSON, marker
31663
31664 /**
31665 * Cached methods as an array.
31666 * @type {Method[]|null}
31667 * @private
31668 */
31669 this._methodsArray = null;
31670}
31671
31672/**
31673 * Service descriptor.
31674 * @interface IService
31675 * @extends INamespace
31676 * @property {Object.<string,IMethod>} methods Method descriptors
31677 */
31678
31679/**
31680 * Constructs a service from a service descriptor.
31681 * @param {string} name Service name
31682 * @param {IService} json Service descriptor
31683 * @returns {Service} Created service
31684 * @throws {TypeError} If arguments are invalid
31685 */
31686Service.fromJSON = function fromJSON(name, json) {
31687 var service = new Service(name, json.options);
31688 /* istanbul ignore else */
31689 if (json.methods)
31690 for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)
31691 service.add(Method.fromJSON(names[i], json.methods[names[i]]));
31692 if (json.nested)
31693 service.addJSON(json.nested);
31694 service.comment = json.comment;
31695 return service;
31696};
31697
31698/**
31699 * Converts this service to a service descriptor.
31700 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
31701 * @returns {IService} Service descriptor
31702 */
31703Service.prototype.toJSON = function toJSON(toJSONOptions) {
31704 var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);
31705 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
31706 return util.toObject([
31707 "options" , inherited && inherited.options || undefined,
31708 "methods" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},
31709 "nested" , inherited && inherited.nested || undefined,
31710 "comment" , keepComments ? this.comment : undefined
31711 ]);
31712};
31713
31714/**
31715 * Methods of this service as an array for iteration.
31716 * @name Service#methodsArray
31717 * @type {Method[]}
31718 * @readonly
31719 */
31720Object.defineProperty(Service.prototype, "methodsArray", {
31721 get: function() {
31722 return this._methodsArray || (this._methodsArray = util.toArray(this.methods));
31723 }
31724});
31725
31726function clearCache(service) {
31727 service._methodsArray = null;
31728 return service;
31729}
31730
31731/**
31732 * @override
31733 */
31734Service.prototype.get = function get(name) {
31735 return this.methods[name]
31736 || Namespace.prototype.get.call(this, name);
31737};
31738
31739/**
31740 * @override
31741 */
31742Service.prototype.resolveAll = function resolveAll() {
31743 var methods = this.methodsArray;
31744 for (var i = 0; i < methods.length; ++i)
31745 methods[i].resolve();
31746 return Namespace.prototype.resolve.call(this);
31747};
31748
31749/**
31750 * @override
31751 */
31752Service.prototype.add = function add(object) {
31753
31754 /* istanbul ignore if */
31755 if (this.get(object.name))
31756 throw Error("duplicate name '" + object.name + "' in " + this);
31757
31758 if (object instanceof Method) {
31759 this.methods[object.name] = object;
31760 object.parent = this;
31761 return clearCache(this);
31762 }
31763 return Namespace.prototype.add.call(this, object);
31764};
31765
31766/**
31767 * @override
31768 */
31769Service.prototype.remove = function remove(object) {
31770 if (object instanceof Method) {
31771
31772 /* istanbul ignore if */
31773 if (this.methods[object.name] !== object)
31774 throw Error(object + " is not a member of " + this);
31775
31776 delete this.methods[object.name];
31777 object.parent = null;
31778 return clearCache(this);
31779 }
31780 return Namespace.prototype.remove.call(this, object);
31781};
31782
31783/**
31784 * Creates a runtime service using the specified rpc implementation.
31785 * @param {RPCImpl} rpcImpl RPC implementation
31786 * @param {boolean} [requestDelimited=false] Whether requests are length-delimited
31787 * @param {boolean} [responseDelimited=false] Whether responses are length-delimited
31788 * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.
31789 */
31790Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {
31791 var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);
31792 for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {
31793 var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, "");
31794 rpcService[methodName] = util.codegen(["r","c"], util.isReserved(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({
31795 m: method,
31796 q: method.resolvedRequestType.ctor,
31797 s: method.resolvedResponseType.ctor
31798 });
31799 }
31800 return rpcService;
31801};
31802
31803},{"./method":203,"./namespace":204,"./rpc":212,"./util":218}],215:[function(require,module,exports){
31804"use strict";
31805module.exports = tokenize;
31806
31807var delimRe = /[\s{}=;:[\],'"()<>]/g,
31808 stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,
31809 stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g;
31810
31811var setCommentRe = /^ *[*/]+ */,
31812 setCommentAltRe = /^\s*\*?\/*/,
31813 setCommentSplitRe = /\n/g,
31814 whitespaceRe = /\s/,
31815 unescapeRe = /\\(.?)/g;
31816
31817var unescapeMap = {
31818 "0": "\0",
31819 "r": "\r",
31820 "n": "\n",
31821 "t": "\t"
31822};
31823
31824/**
31825 * Unescapes a string.
31826 * @param {string} str String to unescape
31827 * @returns {string} Unescaped string
31828 * @property {Object.<string,string>} map Special characters map
31829 * @memberof tokenize
31830 */
31831function unescape(str) {
31832 return str.replace(unescapeRe, function($0, $1) {
31833 switch ($1) {
31834 case "\\":
31835 case "":
31836 return $1;
31837 default:
31838 return unescapeMap[$1] || "";
31839 }
31840 });
31841}
31842
31843tokenize.unescape = unescape;
31844
31845/**
31846 * Gets the next token and advances.
31847 * @typedef TokenizerHandleNext
31848 * @type {function}
31849 * @returns {string|null} Next token or `null` on eof
31850 */
31851
31852/**
31853 * Peeks for the next token.
31854 * @typedef TokenizerHandlePeek
31855 * @type {function}
31856 * @returns {string|null} Next token or `null` on eof
31857 */
31858
31859/**
31860 * Pushes a token back to the stack.
31861 * @typedef TokenizerHandlePush
31862 * @type {function}
31863 * @param {string} token Token
31864 * @returns {undefined}
31865 */
31866
31867/**
31868 * Skips the next token.
31869 * @typedef TokenizerHandleSkip
31870 * @type {function}
31871 * @param {string} expected Expected token
31872 * @param {boolean} [optional=false] If optional
31873 * @returns {boolean} Whether the token matched
31874 * @throws {Error} If the token didn't match and is not optional
31875 */
31876
31877/**
31878 * Gets the comment on the previous line or, alternatively, the line comment on the specified line.
31879 * @typedef TokenizerHandleCmnt
31880 * @type {function}
31881 * @param {number} [line] Line number
31882 * @returns {string|null} Comment text or `null` if none
31883 */
31884
31885/**
31886 * Handle object returned from {@link tokenize}.
31887 * @interface ITokenizerHandle
31888 * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof)
31889 * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof)
31890 * @property {TokenizerHandlePush} push Pushes a token back to the stack
31891 * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws
31892 * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any
31893 * @property {number} line Current line number
31894 */
31895
31896/**
31897 * Tokenizes the given .proto source and returns an object with useful utility functions.
31898 * @param {string} source Source contents
31899 * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode.
31900 * @returns {ITokenizerHandle} Tokenizer handle
31901 */
31902function tokenize(source, alternateCommentMode) {
31903 /* eslint-disable callback-return */
31904 source = source.toString();
31905
31906 var offset = 0,
31907 length = source.length,
31908 line = 1,
31909 commentType = null,
31910 commentText = null,
31911 commentLine = 0,
31912 commentLineEmpty = false;
31913
31914 var stack = [];
31915
31916 var stringDelim = null;
31917
31918 /* istanbul ignore next */
31919 /**
31920 * Creates an error for illegal syntax.
31921 * @param {string} subject Subject
31922 * @returns {Error} Error created
31923 * @inner
31924 */
31925 function illegal(subject) {
31926 return Error("illegal " + subject + " (line " + line + ")");
31927 }
31928
31929 /**
31930 * Reads a string till its end.
31931 * @returns {string} String read
31932 * @inner
31933 */
31934 function readString() {
31935 var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe;
31936 re.lastIndex = offset - 1;
31937 var match = re.exec(source);
31938 if (!match)
31939 throw illegal("string");
31940 offset = re.lastIndex;
31941 push(stringDelim);
31942 stringDelim = null;
31943 return unescape(match[1]);
31944 }
31945
31946 /**
31947 * Gets the character at `pos` within the source.
31948 * @param {number} pos Position
31949 * @returns {string} Character
31950 * @inner
31951 */
31952 function charAt(pos) {
31953 return source.charAt(pos);
31954 }
31955
31956 /**
31957 * Sets the current comment text.
31958 * @param {number} start Start offset
31959 * @param {number} end End offset
31960 * @returns {undefined}
31961 * @inner
31962 */
31963 function setComment(start, end) {
31964 commentType = source.charAt(start++);
31965 commentLine = line;
31966 commentLineEmpty = false;
31967 var lookback;
31968 if (alternateCommentMode) {
31969 lookback = 2; // alternate comment parsing: "//" or "/*"
31970 } else {
31971 lookback = 3; // "///" or "/**"
31972 }
31973 var commentOffset = start - lookback,
31974 c;
31975 do {
31976 if (--commentOffset < 0 ||
31977 (c = source.charAt(commentOffset)) === "\n") {
31978 commentLineEmpty = true;
31979 break;
31980 }
31981 } while (c === " " || c === "\t");
31982 var lines = source
31983 .substring(start, end)
31984 .split(setCommentSplitRe);
31985 for (var i = 0; i < lines.length; ++i)
31986 lines[i] = lines[i]
31987 .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "")
31988 .trim();
31989 commentText = lines
31990 .join("\n")
31991 .trim();
31992 }
31993
31994 function isDoubleSlashCommentLine(startOffset) {
31995 var endOffset = findEndOfLine(startOffset);
31996
31997 // see if remaining line matches comment pattern
31998 var lineText = source.substring(startOffset, endOffset);
31999 // look for 1 or 2 slashes since startOffset would already point past
32000 // the first slash that started the comment.
32001 var isComment = /^\s*\/{1,2}/.test(lineText);
32002 return isComment;
32003 }
32004
32005 function findEndOfLine(cursor) {
32006 // find end of cursor's line
32007 var endOffset = cursor;
32008 while (endOffset < length && charAt(endOffset) !== "\n") {
32009 endOffset++;
32010 }
32011 return endOffset;
32012 }
32013
32014 /**
32015 * Obtains the next token.
32016 * @returns {string|null} Next token or `null` on eof
32017 * @inner
32018 */
32019 function next() {
32020 if (stack.length > 0)
32021 return stack.shift();
32022 if (stringDelim)
32023 return readString();
32024 var repeat,
32025 prev,
32026 curr,
32027 start,
32028 isDoc;
32029 do {
32030 if (offset === length)
32031 return null;
32032 repeat = false;
32033 while (whitespaceRe.test(curr = charAt(offset))) {
32034 if (curr === "\n")
32035 ++line;
32036 if (++offset === length)
32037 return null;
32038 }
32039
32040 if (charAt(offset) === "/") {
32041 if (++offset === length) {
32042 throw illegal("comment");
32043 }
32044 if (charAt(offset) === "/") { // Line
32045 if (!alternateCommentMode) {
32046 // check for triple-slash comment
32047 isDoc = charAt(start = offset + 1) === "/";
32048
32049 while (charAt(++offset) !== "\n") {
32050 if (offset === length) {
32051 return null;
32052 }
32053 }
32054 ++offset;
32055 if (isDoc) {
32056 setComment(start, offset - 1);
32057 }
32058 ++line;
32059 repeat = true;
32060 } else {
32061 // check for double-slash comments, consolidating consecutive lines
32062 start = offset;
32063 isDoc = false;
32064 if (isDoubleSlashCommentLine(offset)) {
32065 isDoc = true;
32066 do {
32067 offset = findEndOfLine(offset);
32068 if (offset === length) {
32069 break;
32070 }
32071 offset++;
32072 } while (isDoubleSlashCommentLine(offset));
32073 } else {
32074 offset = Math.min(length, findEndOfLine(offset) + 1);
32075 }
32076 if (isDoc) {
32077 setComment(start, offset);
32078 }
32079 line++;
32080 repeat = true;
32081 }
32082 } else if ((curr = charAt(offset)) === "*") { /* Block */
32083 // check for /** (regular comment mode) or /* (alternate comment mode)
32084 start = offset + 1;
32085 isDoc = alternateCommentMode || charAt(start) === "*";
32086 do {
32087 if (curr === "\n") {
32088 ++line;
32089 }
32090 if (++offset === length) {
32091 throw illegal("comment");
32092 }
32093 prev = curr;
32094 curr = charAt(offset);
32095 } while (prev !== "*" || curr !== "/");
32096 ++offset;
32097 if (isDoc) {
32098 setComment(start, offset - 2);
32099 }
32100 repeat = true;
32101 } else {
32102 return "/";
32103 }
32104 }
32105 } while (repeat);
32106
32107 // offset !== length if we got here
32108
32109 var end = offset;
32110 delimRe.lastIndex = 0;
32111 var delim = delimRe.test(charAt(end++));
32112 if (!delim)
32113 while (end < length && !delimRe.test(charAt(end)))
32114 ++end;
32115 var token = source.substring(offset, offset = end);
32116 if (token === "\"" || token === "'")
32117 stringDelim = token;
32118 return token;
32119 }
32120
32121 /**
32122 * Pushes a token back to the stack.
32123 * @param {string} token Token
32124 * @returns {undefined}
32125 * @inner
32126 */
32127 function push(token) {
32128 stack.push(token);
32129 }
32130
32131 /**
32132 * Peeks for the next token.
32133 * @returns {string|null} Token or `null` on eof
32134 * @inner
32135 */
32136 function peek() {
32137 if (!stack.length) {
32138 var token = next();
32139 if (token === null)
32140 return null;
32141 push(token);
32142 }
32143 return stack[0];
32144 }
32145
32146 /**
32147 * Skips a token.
32148 * @param {string} expected Expected token
32149 * @param {boolean} [optional=false] Whether the token is optional
32150 * @returns {boolean} `true` when skipped, `false` if not
32151 * @throws {Error} When a required token is not present
32152 * @inner
32153 */
32154 function skip(expected, optional) {
32155 var actual = peek(),
32156 equals = actual === expected;
32157 if (equals) {
32158 next();
32159 return true;
32160 }
32161 if (!optional)
32162 throw illegal("token '" + actual + "', '" + expected + "' expected");
32163 return false;
32164 }
32165
32166 /**
32167 * Gets a comment.
32168 * @param {number} [trailingLine] Line number if looking for a trailing comment
32169 * @returns {string|null} Comment text
32170 * @inner
32171 */
32172 function cmnt(trailingLine) {
32173 var ret = null;
32174 if (trailingLine === undefined) {
32175 if (commentLine === line - 1 && (alternateCommentMode || commentType === "*" || commentLineEmpty)) {
32176 ret = commentText;
32177 }
32178 } else {
32179 /* istanbul ignore else */
32180 if (commentLine < trailingLine) {
32181 peek();
32182 }
32183 if (commentLine === trailingLine && !commentLineEmpty && (alternateCommentMode || commentType === "/")) {
32184 ret = commentText;
32185 }
32186 }
32187 return ret;
32188 }
32189
32190 return Object.defineProperty({
32191 next: next,
32192 peek: peek,
32193 push: push,
32194 skip: skip,
32195 cmnt: cmnt
32196 }, "line", {
32197 get: function() { return line; }
32198 });
32199 /* eslint-enable callback-return */
32200}
32201
32202},{}],216:[function(require,module,exports){
32203"use strict";
32204module.exports = Type;
32205
32206// extends Namespace
32207var Namespace = require("./namespace");
32208((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type";
32209
32210var Enum = require("./enum"),
32211 OneOf = require("./oneof"),
32212 Field = require("./field"),
32213 MapField = require("./mapfield"),
32214 Service = require("./service"),
32215 Message = require("./message"),
32216 Reader = require("./reader"),
32217 Writer = require("./writer"),
32218 util = require("./util"),
32219 encoder = require("./encoder"),
32220 decoder = require("./decoder"),
32221 verifier = require("./verifier"),
32222 converter = require("./converter"),
32223 wrappers = require("./wrappers");
32224
32225/**
32226 * Constructs a new reflected message type instance.
32227 * @classdesc Reflected message type.
32228 * @extends NamespaceBase
32229 * @constructor
32230 * @param {string} name Message name
32231 * @param {Object.<string,*>} [options] Declared options
32232 */
32233function Type(name, options) {
32234 Namespace.call(this, name, options);
32235
32236 /**
32237 * Message fields.
32238 * @type {Object.<string,Field>}
32239 */
32240 this.fields = {}; // toJSON, marker
32241
32242 /**
32243 * Oneofs declared within this namespace, if any.
32244 * @type {Object.<string,OneOf>}
32245 */
32246 this.oneofs = undefined; // toJSON
32247
32248 /**
32249 * Extension ranges, if any.
32250 * @type {number[][]}
32251 */
32252 this.extensions = undefined; // toJSON
32253
32254 /**
32255 * Reserved ranges, if any.
32256 * @type {Array.<number[]|string>}
32257 */
32258 this.reserved = undefined; // toJSON
32259
32260 /*?
32261 * Whether this type is a legacy group.
32262 * @type {boolean|undefined}
32263 */
32264 this.group = undefined; // toJSON
32265
32266 /**
32267 * Cached fields by id.
32268 * @type {Object.<number,Field>|null}
32269 * @private
32270 */
32271 this._fieldsById = null;
32272
32273 /**
32274 * Cached fields as an array.
32275 * @type {Field[]|null}
32276 * @private
32277 */
32278 this._fieldsArray = null;
32279
32280 /**
32281 * Cached oneofs as an array.
32282 * @type {OneOf[]|null}
32283 * @private
32284 */
32285 this._oneofsArray = null;
32286
32287 /**
32288 * Cached constructor.
32289 * @type {Constructor<{}>}
32290 * @private
32291 */
32292 this._ctor = null;
32293}
32294
32295Object.defineProperties(Type.prototype, {
32296
32297 /**
32298 * Message fields by id.
32299 * @name Type#fieldsById
32300 * @type {Object.<number,Field>}
32301 * @readonly
32302 */
32303 fieldsById: {
32304 get: function() {
32305
32306 /* istanbul ignore if */
32307 if (this._fieldsById)
32308 return this._fieldsById;
32309
32310 this._fieldsById = {};
32311 for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {
32312 var field = this.fields[names[i]],
32313 id = field.id;
32314
32315 /* istanbul ignore if */
32316 if (this._fieldsById[id])
32317 throw Error("duplicate id " + id + " in " + this);
32318
32319 this._fieldsById[id] = field;
32320 }
32321 return this._fieldsById;
32322 }
32323 },
32324
32325 /**
32326 * Fields of this message as an array for iteration.
32327 * @name Type#fieldsArray
32328 * @type {Field[]}
32329 * @readonly
32330 */
32331 fieldsArray: {
32332 get: function() {
32333 return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));
32334 }
32335 },
32336
32337 /**
32338 * Oneofs of this message as an array for iteration.
32339 * @name Type#oneofsArray
32340 * @type {OneOf[]}
32341 * @readonly
32342 */
32343 oneofsArray: {
32344 get: function() {
32345 return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));
32346 }
32347 },
32348
32349 /**
32350 * The registered constructor, if any registered, otherwise a generic constructor.
32351 * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.
32352 * @name Type#ctor
32353 * @type {Constructor<{}>}
32354 */
32355 ctor: {
32356 get: function() {
32357 return this._ctor || (this.ctor = Type.generateConstructor(this)());
32358 },
32359 set: function(ctor) {
32360
32361 // Ensure proper prototype
32362 var prototype = ctor.prototype;
32363 if (!(prototype instanceof Message)) {
32364 (ctor.prototype = new Message()).constructor = ctor;
32365 util.merge(ctor.prototype, prototype);
32366 }
32367
32368 // Classes and messages reference their reflected type
32369 ctor.$type = ctor.prototype.$type = this;
32370
32371 // Mix in static methods
32372 util.merge(ctor, Message, true);
32373
32374 this._ctor = ctor;
32375
32376 // Messages have non-enumerable default values on their prototype
32377 var i = 0;
32378 for (; i < /* initializes */ this.fieldsArray.length; ++i)
32379 this._fieldsArray[i].resolve(); // ensures a proper value
32380
32381 // Messages have non-enumerable getters and setters for each virtual oneof field
32382 var ctorProperties = {};
32383 for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)
32384 ctorProperties[this._oneofsArray[i].resolve().name] = {
32385 get: util.oneOfGetter(this._oneofsArray[i].oneof),
32386 set: util.oneOfSetter(this._oneofsArray[i].oneof)
32387 };
32388 if (i)
32389 Object.defineProperties(ctor.prototype, ctorProperties);
32390 }
32391 }
32392});
32393
32394/**
32395 * Generates a constructor function for the specified type.
32396 * @param {Type} mtype Message type
32397 * @returns {Codegen} Codegen instance
32398 */
32399Type.generateConstructor = function generateConstructor(mtype) {
32400 /* eslint-disable no-unexpected-multiline */
32401 var gen = util.codegen(["p"], mtype.name);
32402 // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype
32403 for (var i = 0, field; i < mtype.fieldsArray.length; ++i)
32404 if ((field = mtype._fieldsArray[i]).map) gen
32405 ("this%s={}", util.safeProp(field.name));
32406 else if (field.repeated) gen
32407 ("this%s=[]", util.safeProp(field.name));
32408 return gen
32409 ("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)") // omit undefined or null
32410 ("this[ks[i]]=p[ks[i]]");
32411 /* eslint-enable no-unexpected-multiline */
32412};
32413
32414function clearCache(type) {
32415 type._fieldsById = type._fieldsArray = type._oneofsArray = null;
32416 delete type.encode;
32417 delete type.decode;
32418 delete type.verify;
32419 return type;
32420}
32421
32422/**
32423 * Message type descriptor.
32424 * @interface IType
32425 * @extends INamespace
32426 * @property {Object.<string,IOneOf>} [oneofs] Oneof descriptors
32427 * @property {Object.<string,IField>} fields Field descriptors
32428 * @property {number[][]} [extensions] Extension ranges
32429 * @property {number[][]} [reserved] Reserved ranges
32430 * @property {boolean} [group=false] Whether a legacy group or not
32431 */
32432
32433/**
32434 * Creates a message type from a message type descriptor.
32435 * @param {string} name Message name
32436 * @param {IType} json Message type descriptor
32437 * @returns {Type} Created message type
32438 */
32439Type.fromJSON = function fromJSON(name, json) {
32440 var type = new Type(name, json.options);
32441 type.extensions = json.extensions;
32442 type.reserved = json.reserved;
32443 var names = Object.keys(json.fields),
32444 i = 0;
32445 for (; i < names.length; ++i)
32446 type.add(
32447 ( typeof json.fields[names[i]].keyType !== "undefined"
32448 ? MapField.fromJSON
32449 : Field.fromJSON )(names[i], json.fields[names[i]])
32450 );
32451 if (json.oneofs)
32452 for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)
32453 type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));
32454 if (json.nested)
32455 for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {
32456 var nested = json.nested[names[i]];
32457 type.add( // most to least likely
32458 ( nested.id !== undefined
32459 ? Field.fromJSON
32460 : nested.fields !== undefined
32461 ? Type.fromJSON
32462 : nested.values !== undefined
32463 ? Enum.fromJSON
32464 : nested.methods !== undefined
32465 ? Service.fromJSON
32466 : Namespace.fromJSON )(names[i], nested)
32467 );
32468 }
32469 if (json.extensions && json.extensions.length)
32470 type.extensions = json.extensions;
32471 if (json.reserved && json.reserved.length)
32472 type.reserved = json.reserved;
32473 if (json.group)
32474 type.group = true;
32475 if (json.comment)
32476 type.comment = json.comment;
32477 return type;
32478};
32479
32480/**
32481 * Converts this message type to a message type descriptor.
32482 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
32483 * @returns {IType} Message type descriptor
32484 */
32485Type.prototype.toJSON = function toJSON(toJSONOptions) {
32486 var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);
32487 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;
32488 return util.toObject([
32489 "options" , inherited && inherited.options || undefined,
32490 "oneofs" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),
32491 "fields" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},
32492 "extensions" , this.extensions && this.extensions.length ? this.extensions : undefined,
32493 "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined,
32494 "group" , this.group || undefined,
32495 "nested" , inherited && inherited.nested || undefined,
32496 "comment" , keepComments ? this.comment : undefined
32497 ]);
32498};
32499
32500/**
32501 * @override
32502 */
32503Type.prototype.resolveAll = function resolveAll() {
32504 var fields = this.fieldsArray, i = 0;
32505 while (i < fields.length)
32506 fields[i++].resolve();
32507 var oneofs = this.oneofsArray; i = 0;
32508 while (i < oneofs.length)
32509 oneofs[i++].resolve();
32510 return Namespace.prototype.resolveAll.call(this);
32511};
32512
32513/**
32514 * @override
32515 */
32516Type.prototype.get = function get(name) {
32517 return this.fields[name]
32518 || this.oneofs && this.oneofs[name]
32519 || this.nested && this.nested[name]
32520 || null;
32521};
32522
32523/**
32524 * Adds a nested object to this type.
32525 * @param {ReflectionObject} object Nested object to add
32526 * @returns {Type} `this`
32527 * @throws {TypeError} If arguments are invalid
32528 * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id
32529 */
32530Type.prototype.add = function add(object) {
32531
32532 if (this.get(object.name))
32533 throw Error("duplicate name '" + object.name + "' in " + this);
32534
32535 if (object instanceof Field && object.extend === undefined) {
32536 // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.
32537 // The root object takes care of adding distinct sister-fields to the respective extended
32538 // type instead.
32539
32540 // avoids calling the getter if not absolutely necessary because it's called quite frequently
32541 if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])
32542 throw Error("duplicate id " + object.id + " in " + this);
32543 if (this.isReservedId(object.id))
32544 throw Error("id " + object.id + " is reserved in " + this);
32545 if (this.isReservedName(object.name))
32546 throw Error("name '" + object.name + "' is reserved in " + this);
32547
32548 if (object.parent)
32549 object.parent.remove(object);
32550 this.fields[object.name] = object;
32551 object.message = this;
32552 object.onAdd(this);
32553 return clearCache(this);
32554 }
32555 if (object instanceof OneOf) {
32556 if (!this.oneofs)
32557 this.oneofs = {};
32558 this.oneofs[object.name] = object;
32559 object.onAdd(this);
32560 return clearCache(this);
32561 }
32562 return Namespace.prototype.add.call(this, object);
32563};
32564
32565/**
32566 * Removes a nested object from this type.
32567 * @param {ReflectionObject} object Nested object to remove
32568 * @returns {Type} `this`
32569 * @throws {TypeError} If arguments are invalid
32570 * @throws {Error} If `object` is not a member of this type
32571 */
32572Type.prototype.remove = function remove(object) {
32573 if (object instanceof Field && object.extend === undefined) {
32574 // See Type#add for the reason why extension fields are excluded here.
32575
32576 /* istanbul ignore if */
32577 if (!this.fields || this.fields[object.name] !== object)
32578 throw Error(object + " is not a member of " + this);
32579
32580 delete this.fields[object.name];
32581 object.parent = null;
32582 object.onRemove(this);
32583 return clearCache(this);
32584 }
32585 if (object instanceof OneOf) {
32586
32587 /* istanbul ignore if */
32588 if (!this.oneofs || this.oneofs[object.name] !== object)
32589 throw Error(object + " is not a member of " + this);
32590
32591 delete this.oneofs[object.name];
32592 object.parent = null;
32593 object.onRemove(this);
32594 return clearCache(this);
32595 }
32596 return Namespace.prototype.remove.call(this, object);
32597};
32598
32599/**
32600 * Tests if the specified id is reserved.
32601 * @param {number} id Id to test
32602 * @returns {boolean} `true` if reserved, otherwise `false`
32603 */
32604Type.prototype.isReservedId = function isReservedId(id) {
32605 return Namespace.isReservedId(this.reserved, id);
32606};
32607
32608/**
32609 * Tests if the specified name is reserved.
32610 * @param {string} name Name to test
32611 * @returns {boolean} `true` if reserved, otherwise `false`
32612 */
32613Type.prototype.isReservedName = function isReservedName(name) {
32614 return Namespace.isReservedName(this.reserved, name);
32615};
32616
32617/**
32618 * Creates a new message of this type using the specified properties.
32619 * @param {Object.<string,*>} [properties] Properties to set
32620 * @returns {Message<{}>} Message instance
32621 */
32622Type.prototype.create = function create(properties) {
32623 return new this.ctor(properties);
32624};
32625
32626/**
32627 * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.
32628 * @returns {Type} `this`
32629 */
32630Type.prototype.setup = function setup() {
32631 // Sets up everything at once so that the prototype chain does not have to be re-evaluated
32632 // multiple times (V8, soft-deopt prototype-check).
32633
32634 var fullName = this.fullName,
32635 types = [];
32636 for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)
32637 types.push(this._fieldsArray[i].resolve().resolvedType);
32638
32639 // Replace setup methods with type-specific generated functions
32640 this.encode = encoder(this)({
32641 Writer : Writer,
32642 types : types,
32643 util : util
32644 });
32645 this.decode = decoder(this)({
32646 Reader : Reader,
32647 types : types,
32648 util : util
32649 });
32650 this.verify = verifier(this)({
32651 types : types,
32652 util : util
32653 });
32654 this.fromObject = converter.fromObject(this)({
32655 types : types,
32656 util : util
32657 });
32658 this.toObject = converter.toObject(this)({
32659 types : types,
32660 util : util
32661 });
32662
32663 // Inject custom wrappers for common types
32664 var wrapper = wrappers[fullName];
32665 if (wrapper) {
32666 var originalThis = Object.create(this);
32667 // if (wrapper.fromObject) {
32668 originalThis.fromObject = this.fromObject;
32669 this.fromObject = wrapper.fromObject.bind(originalThis);
32670 // }
32671 // if (wrapper.toObject) {
32672 originalThis.toObject = this.toObject;
32673 this.toObject = wrapper.toObject.bind(originalThis);
32674 // }
32675 }
32676
32677 return this;
32678};
32679
32680/**
32681 * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.
32682 * @param {Message<{}>|Object.<string,*>} message Message instance or plain object
32683 * @param {Writer} [writer] Writer to encode to
32684 * @returns {Writer} writer
32685 */
32686Type.prototype.encode = function encode_setup(message, writer) {
32687 return this.setup().encode(message, writer); // overrides this method
32688};
32689
32690/**
32691 * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.
32692 * @param {Message<{}>|Object.<string,*>} message Message instance or plain object
32693 * @param {Writer} [writer] Writer to encode to
32694 * @returns {Writer} writer
32695 */
32696Type.prototype.encodeDelimited = function encodeDelimited(message, writer) {
32697 return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();
32698};
32699
32700/**
32701 * Decodes a message of this type.
32702 * @param {Reader|Uint8Array} reader Reader or buffer to decode from
32703 * @param {number} [length] Length of the message, if known beforehand
32704 * @returns {Message<{}>} Decoded message
32705 * @throws {Error} If the payload is not a reader or valid buffer
32706 * @throws {util.ProtocolError<{}>} If required fields are missing
32707 */
32708Type.prototype.decode = function decode_setup(reader, length) {
32709 return this.setup().decode(reader, length); // overrides this method
32710};
32711
32712/**
32713 * Decodes a message of this type preceeded by its byte length as a varint.
32714 * @param {Reader|Uint8Array} reader Reader or buffer to decode from
32715 * @returns {Message<{}>} Decoded message
32716 * @throws {Error} If the payload is not a reader or valid buffer
32717 * @throws {util.ProtocolError} If required fields are missing
32718 */
32719Type.prototype.decodeDelimited = function decodeDelimited(reader) {
32720 if (!(reader instanceof Reader))
32721 reader = Reader.create(reader);
32722 return this.decode(reader, reader.uint32());
32723};
32724
32725/**
32726 * Verifies that field values are valid and that required fields are present.
32727 * @param {Object.<string,*>} message Plain object to verify
32728 * @returns {null|string} `null` if valid, otherwise the reason why it is not
32729 */
32730Type.prototype.verify = function verify_setup(message) {
32731 return this.setup().verify(message); // overrides this method
32732};
32733
32734/**
32735 * Creates a new message of this type from a plain object. Also converts values to their respective internal types.
32736 * @param {Object.<string,*>} object Plain object to convert
32737 * @returns {Message<{}>} Message instance
32738 */
32739Type.prototype.fromObject = function fromObject(object) {
32740 return this.setup().fromObject(object);
32741};
32742
32743/**
32744 * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.
32745 * @interface IConversionOptions
32746 * @property {Function} [longs] Long conversion type.
32747 * Valid values are `String` and `Number` (the global types).
32748 * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.
32749 * @property {Function} [enums] Enum value conversion type.
32750 * Only valid value is `String` (the global type).
32751 * Defaults to copy the present value, which is the numeric id.
32752 * @property {Function} [bytes] Bytes value conversion type.
32753 * Valid values are `Array` and (a base64 encoded) `String` (the global types).
32754 * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.
32755 * @property {boolean} [defaults=false] Also sets default values on the resulting object
32756 * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`
32757 * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`
32758 * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any
32759 * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings
32760 */
32761
32762/**
32763 * Creates a plain object from a message of this type. Also converts values to other types if specified.
32764 * @param {Message<{}>} message Message instance
32765 * @param {IConversionOptions} [options] Conversion options
32766 * @returns {Object.<string,*>} Plain object
32767 */
32768Type.prototype.toObject = function toObject(message, options) {
32769 return this.setup().toObject(message, options);
32770};
32771
32772/**
32773 * Decorator function as returned by {@link Type.d} (TypeScript).
32774 * @typedef TypeDecorator
32775 * @type {function}
32776 * @param {Constructor<T>} target Target constructor
32777 * @returns {undefined}
32778 * @template T extends Message<T>
32779 */
32780
32781/**
32782 * Type decorator (TypeScript).
32783 * @param {string} [typeName] Type name, defaults to the constructor's name
32784 * @returns {TypeDecorator<T>} Decorator function
32785 * @template T extends Message<T>
32786 */
32787Type.d = function decorateType(typeName) {
32788 return function typeDecorator(target) {
32789 util.decorateType(target, typeName);
32790 };
32791};
32792
32793},{"./converter":193,"./decoder":194,"./encoder":195,"./enum":196,"./field":197,"./mapfield":201,"./message":202,"./namespace":204,"./oneof":206,"./reader":208,"./service":214,"./util":218,"./verifier":221,"./wrappers":222,"./writer":223}],217:[function(require,module,exports){
32794"use strict";
32795
32796/**
32797 * Common type constants.
32798 * @namespace
32799 */
32800var types = exports;
32801
32802var util = require("./util");
32803
32804var s = [
32805 "double", // 0
32806 "float", // 1
32807 "int32", // 2
32808 "uint32", // 3
32809 "sint32", // 4
32810 "fixed32", // 5
32811 "sfixed32", // 6
32812 "int64", // 7
32813 "uint64", // 8
32814 "sint64", // 9
32815 "fixed64", // 10
32816 "sfixed64", // 11
32817 "bool", // 12
32818 "string", // 13
32819 "bytes" // 14
32820];
32821
32822function bake(values, offset) {
32823 var i = 0, o = {};
32824 offset |= 0;
32825 while (i < values.length) o[s[i + offset]] = values[i++];
32826 return o;
32827}
32828
32829/**
32830 * Basic type wire types.
32831 * @type {Object.<string,number>}
32832 * @const
32833 * @property {number} double=1 Fixed64 wire type
32834 * @property {number} float=5 Fixed32 wire type
32835 * @property {number} int32=0 Varint wire type
32836 * @property {number} uint32=0 Varint wire type
32837 * @property {number} sint32=0 Varint wire type
32838 * @property {number} fixed32=5 Fixed32 wire type
32839 * @property {number} sfixed32=5 Fixed32 wire type
32840 * @property {number} int64=0 Varint wire type
32841 * @property {number} uint64=0 Varint wire type
32842 * @property {number} sint64=0 Varint wire type
32843 * @property {number} fixed64=1 Fixed64 wire type
32844 * @property {number} sfixed64=1 Fixed64 wire type
32845 * @property {number} bool=0 Varint wire type
32846 * @property {number} string=2 Ldelim wire type
32847 * @property {number} bytes=2 Ldelim wire type
32848 */
32849types.basic = bake([
32850 /* double */ 1,
32851 /* float */ 5,
32852 /* int32 */ 0,
32853 /* uint32 */ 0,
32854 /* sint32 */ 0,
32855 /* fixed32 */ 5,
32856 /* sfixed32 */ 5,
32857 /* int64 */ 0,
32858 /* uint64 */ 0,
32859 /* sint64 */ 0,
32860 /* fixed64 */ 1,
32861 /* sfixed64 */ 1,
32862 /* bool */ 0,
32863 /* string */ 2,
32864 /* bytes */ 2
32865]);
32866
32867/**
32868 * Basic type defaults.
32869 * @type {Object.<string,*>}
32870 * @const
32871 * @property {number} double=0 Double default
32872 * @property {number} float=0 Float default
32873 * @property {number} int32=0 Int32 default
32874 * @property {number} uint32=0 Uint32 default
32875 * @property {number} sint32=0 Sint32 default
32876 * @property {number} fixed32=0 Fixed32 default
32877 * @property {number} sfixed32=0 Sfixed32 default
32878 * @property {number} int64=0 Int64 default
32879 * @property {number} uint64=0 Uint64 default
32880 * @property {number} sint64=0 Sint32 default
32881 * @property {number} fixed64=0 Fixed64 default
32882 * @property {number} sfixed64=0 Sfixed64 default
32883 * @property {boolean} bool=false Bool default
32884 * @property {string} string="" String default
32885 * @property {Array.<number>} bytes=Array(0) Bytes default
32886 * @property {null} message=null Message default
32887 */
32888types.defaults = bake([
32889 /* double */ 0,
32890 /* float */ 0,
32891 /* int32 */ 0,
32892 /* uint32 */ 0,
32893 /* sint32 */ 0,
32894 /* fixed32 */ 0,
32895 /* sfixed32 */ 0,
32896 /* int64 */ 0,
32897 /* uint64 */ 0,
32898 /* sint64 */ 0,
32899 /* fixed64 */ 0,
32900 /* sfixed64 */ 0,
32901 /* bool */ false,
32902 /* string */ "",
32903 /* bytes */ util.emptyArray,
32904 /* message */ null
32905]);
32906
32907/**
32908 * Basic long type wire types.
32909 * @type {Object.<string,number>}
32910 * @const
32911 * @property {number} int64=0 Varint wire type
32912 * @property {number} uint64=0 Varint wire type
32913 * @property {number} sint64=0 Varint wire type
32914 * @property {number} fixed64=1 Fixed64 wire type
32915 * @property {number} sfixed64=1 Fixed64 wire type
32916 */
32917types.long = bake([
32918 /* int64 */ 0,
32919 /* uint64 */ 0,
32920 /* sint64 */ 0,
32921 /* fixed64 */ 1,
32922 /* sfixed64 */ 1
32923], 7);
32924
32925/**
32926 * Allowed types for map keys with their associated wire type.
32927 * @type {Object.<string,number>}
32928 * @const
32929 * @property {number} int32=0 Varint wire type
32930 * @property {number} uint32=0 Varint wire type
32931 * @property {number} sint32=0 Varint wire type
32932 * @property {number} fixed32=5 Fixed32 wire type
32933 * @property {number} sfixed32=5 Fixed32 wire type
32934 * @property {number} int64=0 Varint wire type
32935 * @property {number} uint64=0 Varint wire type
32936 * @property {number} sint64=0 Varint wire type
32937 * @property {number} fixed64=1 Fixed64 wire type
32938 * @property {number} sfixed64=1 Fixed64 wire type
32939 * @property {number} bool=0 Varint wire type
32940 * @property {number} string=2 Ldelim wire type
32941 */
32942types.mapKey = bake([
32943 /* int32 */ 0,
32944 /* uint32 */ 0,
32945 /* sint32 */ 0,
32946 /* fixed32 */ 5,
32947 /* sfixed32 */ 5,
32948 /* int64 */ 0,
32949 /* uint64 */ 0,
32950 /* sint64 */ 0,
32951 /* fixed64 */ 1,
32952 /* sfixed64 */ 1,
32953 /* bool */ 0,
32954 /* string */ 2
32955], 2);
32956
32957/**
32958 * Allowed types for packed repeated fields with their associated wire type.
32959 * @type {Object.<string,number>}
32960 * @const
32961 * @property {number} double=1 Fixed64 wire type
32962 * @property {number} float=5 Fixed32 wire type
32963 * @property {number} int32=0 Varint wire type
32964 * @property {number} uint32=0 Varint wire type
32965 * @property {number} sint32=0 Varint wire type
32966 * @property {number} fixed32=5 Fixed32 wire type
32967 * @property {number} sfixed32=5 Fixed32 wire type
32968 * @property {number} int64=0 Varint wire type
32969 * @property {number} uint64=0 Varint wire type
32970 * @property {number} sint64=0 Varint wire type
32971 * @property {number} fixed64=1 Fixed64 wire type
32972 * @property {number} sfixed64=1 Fixed64 wire type
32973 * @property {number} bool=0 Varint wire type
32974 */
32975types.packed = bake([
32976 /* double */ 1,
32977 /* float */ 5,
32978 /* int32 */ 0,
32979 /* uint32 */ 0,
32980 /* sint32 */ 0,
32981 /* fixed32 */ 5,
32982 /* sfixed32 */ 5,
32983 /* int64 */ 0,
32984 /* uint64 */ 0,
32985 /* sint64 */ 0,
32986 /* fixed64 */ 1,
32987 /* sfixed64 */ 1,
32988 /* bool */ 0
32989]);
32990
32991},{"./util":218}],218:[function(require,module,exports){
32992"use strict";
32993
32994/**
32995 * Various utility functions.
32996 * @namespace
32997 */
32998var util = module.exports = require("./util/minimal");
32999
33000var roots = require("./roots");
33001
33002var Type, // cyclic
33003 Enum;
33004
33005util.codegen = require("@protobufjs/codegen");
33006util.fetch = require("@protobufjs/fetch");
33007util.path = require("@protobufjs/path");
33008
33009/**
33010 * Node's fs module if available.
33011 * @type {Object.<string,*>}
33012 */
33013util.fs = util.inquire("fs");
33014
33015/**
33016 * Converts an object's values to an array.
33017 * @param {Object.<string,*>} object Object to convert
33018 * @returns {Array.<*>} Converted array
33019 */
33020util.toArray = function toArray(object) {
33021 if (object) {
33022 var keys = Object.keys(object),
33023 array = new Array(keys.length),
33024 index = 0;
33025 while (index < keys.length)
33026 array[index] = object[keys[index++]];
33027 return array;
33028 }
33029 return [];
33030};
33031
33032/**
33033 * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.
33034 * @param {Array.<*>} array Array to convert
33035 * @returns {Object.<string,*>} Converted object
33036 */
33037util.toObject = function toObject(array) {
33038 var object = {},
33039 index = 0;
33040 while (index < array.length) {
33041 var key = array[index++],
33042 val = array[index++];
33043 if (val !== undefined)
33044 object[key] = val;
33045 }
33046 return object;
33047};
33048
33049var safePropBackslashRe = /\\/g,
33050 safePropQuoteRe = /"/g;
33051
33052/**
33053 * Tests whether the specified name is a reserved word in JS.
33054 * @param {string} name Name to test
33055 * @returns {boolean} `true` if reserved, otherwise `false`
33056 */
33057util.isReserved = function isReserved(name) {
33058 return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name);
33059};
33060
33061/**
33062 * Returns a safe property accessor for the specified property name.
33063 * @param {string} prop Property name
33064 * @returns {string} Safe accessor
33065 */
33066util.safeProp = function safeProp(prop) {
33067 if (!/^[$\w_]+$/.test(prop) || util.isReserved(prop))
33068 return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]";
33069 return "." + prop;
33070};
33071
33072/**
33073 * Converts the first character of a string to upper case.
33074 * @param {string} str String to convert
33075 * @returns {string} Converted string
33076 */
33077util.ucFirst = function ucFirst(str) {
33078 return str.charAt(0).toUpperCase() + str.substring(1);
33079};
33080
33081var camelCaseRe = /_([a-z])/g;
33082
33083/**
33084 * Converts a string to camel case.
33085 * @param {string} str String to convert
33086 * @returns {string} Converted string
33087 */
33088util.camelCase = function camelCase(str) {
33089 return str.substring(0, 1)
33090 + str.substring(1)
33091 .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });
33092};
33093
33094/**
33095 * Compares reflected fields by id.
33096 * @param {Field} a First field
33097 * @param {Field} b Second field
33098 * @returns {number} Comparison value
33099 */
33100util.compareFieldsById = function compareFieldsById(a, b) {
33101 return a.id - b.id;
33102};
33103
33104/**
33105 * Decorator helper for types (TypeScript).
33106 * @param {Constructor<T>} ctor Constructor function
33107 * @param {string} [typeName] Type name, defaults to the constructor's name
33108 * @returns {Type} Reflected type
33109 * @template T extends Message<T>
33110 * @property {Root} root Decorators root
33111 */
33112util.decorateType = function decorateType(ctor, typeName) {
33113
33114 /* istanbul ignore if */
33115 if (ctor.$type) {
33116 if (typeName && ctor.$type.name !== typeName) {
33117 util.decorateRoot.remove(ctor.$type);
33118 ctor.$type.name = typeName;
33119 util.decorateRoot.add(ctor.$type);
33120 }
33121 return ctor.$type;
33122 }
33123
33124 /* istanbul ignore next */
33125 if (!Type)
33126 Type = require("./type");
33127
33128 var type = new Type(typeName || ctor.name);
33129 util.decorateRoot.add(type);
33130 type.ctor = ctor; // sets up .encode, .decode etc.
33131 Object.defineProperty(ctor, "$type", { value: type, enumerable: false });
33132 Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false });
33133 return type;
33134};
33135
33136var decorateEnumIndex = 0;
33137
33138/**
33139 * Decorator helper for enums (TypeScript).
33140 * @param {Object} object Enum object
33141 * @returns {Enum} Reflected enum
33142 */
33143util.decorateEnum = function decorateEnum(object) {
33144
33145 /* istanbul ignore if */
33146 if (object.$type)
33147 return object.$type;
33148
33149 /* istanbul ignore next */
33150 if (!Enum)
33151 Enum = require("./enum");
33152
33153 var enm = new Enum("Enum" + decorateEnumIndex++, object);
33154 util.decorateRoot.add(enm);
33155 Object.defineProperty(object, "$type", { value: enm, enumerable: false });
33156 return enm;
33157};
33158
33159/**
33160 * Decorator root (TypeScript).
33161 * @name util.decorateRoot
33162 * @type {Root}
33163 * @readonly
33164 */
33165Object.defineProperty(util, "decorateRoot", {
33166 get: function() {
33167 return roots["decorated"] || (roots["decorated"] = new (require("./root"))());
33168 }
33169});
33170
33171},{"./enum":196,"./root":210,"./roots":211,"./type":216,"./util/minimal":220,"@protobufjs/codegen":24,"@protobufjs/fetch":26,"@protobufjs/path":29}],219:[function(require,module,exports){
33172"use strict";
33173module.exports = LongBits;
33174
33175var util = require("../util/minimal");
33176
33177/**
33178 * Constructs new long bits.
33179 * @classdesc Helper class for working with the low and high bits of a 64 bit value.
33180 * @memberof util
33181 * @constructor
33182 * @param {number} lo Low 32 bits, unsigned
33183 * @param {number} hi High 32 bits, unsigned
33184 */
33185function LongBits(lo, hi) {
33186
33187 // note that the casts below are theoretically unnecessary as of today, but older statically
33188 // generated converter code might still call the ctor with signed 32bits. kept for compat.
33189
33190 /**
33191 * Low bits.
33192 * @type {number}
33193 */
33194 this.lo = lo >>> 0;
33195
33196 /**
33197 * High bits.
33198 * @type {number}
33199 */
33200 this.hi = hi >>> 0;
33201}
33202
33203/**
33204 * Zero bits.
33205 * @memberof util.LongBits
33206 * @type {util.LongBits}
33207 */
33208var zero = LongBits.zero = new LongBits(0, 0);
33209
33210zero.toNumber = function() { return 0; };
33211zero.zzEncode = zero.zzDecode = function() { return this; };
33212zero.length = function() { return 1; };
33213
33214/**
33215 * Zero hash.
33216 * @memberof util.LongBits
33217 * @type {string}
33218 */
33219var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0";
33220
33221/**
33222 * Constructs new long bits from the specified number.
33223 * @param {number} value Value
33224 * @returns {util.LongBits} Instance
33225 */
33226LongBits.fromNumber = function fromNumber(value) {
33227 if (value === 0)
33228 return zero;
33229 var sign = value < 0;
33230 if (sign)
33231 value = -value;
33232 var lo = value >>> 0,
33233 hi = (value - lo) / 4294967296 >>> 0;
33234 if (sign) {
33235 hi = ~hi >>> 0;
33236 lo = ~lo >>> 0;
33237 if (++lo > 4294967295) {
33238 lo = 0;
33239 if (++hi > 4294967295)
33240 hi = 0;
33241 }
33242 }
33243 return new LongBits(lo, hi);
33244};
33245
33246/**
33247 * Constructs new long bits from a number, long or string.
33248 * @param {Long|number|string} value Value
33249 * @returns {util.LongBits} Instance
33250 */
33251LongBits.from = function from(value) {
33252 if (typeof value === "number")
33253 return LongBits.fromNumber(value);
33254 if (util.isString(value)) {
33255 /* istanbul ignore else */
33256 if (util.Long)
33257 value = util.Long.fromString(value);
33258 else
33259 return LongBits.fromNumber(parseInt(value, 10));
33260 }
33261 return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;
33262};
33263
33264/**
33265 * Converts this long bits to a possibly unsafe JavaScript number.
33266 * @param {boolean} [unsigned=false] Whether unsigned or not
33267 * @returns {number} Possibly unsafe number
33268 */
33269LongBits.prototype.toNumber = function toNumber(unsigned) {
33270 if (!unsigned && this.hi >>> 31) {
33271 var lo = ~this.lo + 1 >>> 0,
33272 hi = ~this.hi >>> 0;
33273 if (!lo)
33274 hi = hi + 1 >>> 0;
33275 return -(lo + hi * 4294967296);
33276 }
33277 return this.lo + this.hi * 4294967296;
33278};
33279
33280/**
33281 * Converts this long bits to a long.
33282 * @param {boolean} [unsigned=false] Whether unsigned or not
33283 * @returns {Long} Long
33284 */
33285LongBits.prototype.toLong = function toLong(unsigned) {
33286 return util.Long
33287 ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))
33288 /* istanbul ignore next */
33289 : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };
33290};
33291
33292var charCodeAt = String.prototype.charCodeAt;
33293
33294/**
33295 * Constructs new long bits from the specified 8 characters long hash.
33296 * @param {string} hash Hash
33297 * @returns {util.LongBits} Bits
33298 */
33299LongBits.fromHash = function fromHash(hash) {
33300 if (hash === zeroHash)
33301 return zero;
33302 return new LongBits(
33303 ( charCodeAt.call(hash, 0)
33304 | charCodeAt.call(hash, 1) << 8
33305 | charCodeAt.call(hash, 2) << 16
33306 | charCodeAt.call(hash, 3) << 24) >>> 0
33307 ,
33308 ( charCodeAt.call(hash, 4)
33309 | charCodeAt.call(hash, 5) << 8
33310 | charCodeAt.call(hash, 6) << 16
33311 | charCodeAt.call(hash, 7) << 24) >>> 0
33312 );
33313};
33314
33315/**
33316 * Converts this long bits to a 8 characters long hash.
33317 * @returns {string} Hash
33318 */
33319LongBits.prototype.toHash = function toHash() {
33320 return String.fromCharCode(
33321 this.lo & 255,
33322 this.lo >>> 8 & 255,
33323 this.lo >>> 16 & 255,
33324 this.lo >>> 24 ,
33325 this.hi & 255,
33326 this.hi >>> 8 & 255,
33327 this.hi >>> 16 & 255,
33328 this.hi >>> 24
33329 );
33330};
33331
33332/**
33333 * Zig-zag encodes this long bits.
33334 * @returns {util.LongBits} `this`
33335 */
33336LongBits.prototype.zzEncode = function zzEncode() {
33337 var mask = this.hi >> 31;
33338 this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;
33339 this.lo = ( this.lo << 1 ^ mask) >>> 0;
33340 return this;
33341};
33342
33343/**
33344 * Zig-zag decodes this long bits.
33345 * @returns {util.LongBits} `this`
33346 */
33347LongBits.prototype.zzDecode = function zzDecode() {
33348 var mask = -(this.lo & 1);
33349 this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;
33350 this.hi = ( this.hi >>> 1 ^ mask) >>> 0;
33351 return this;
33352};
33353
33354/**
33355 * Calculates the length of this longbits when encoded as a varint.
33356 * @returns {number} Length
33357 */
33358LongBits.prototype.length = function length() {
33359 var part0 = this.lo,
33360 part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,
33361 part2 = this.hi >>> 24;
33362 return part2 === 0
33363 ? part1 === 0
33364 ? part0 < 16384
33365 ? part0 < 128 ? 1 : 2
33366 : part0 < 2097152 ? 3 : 4
33367 : part1 < 16384
33368 ? part1 < 128 ? 5 : 6
33369 : part1 < 2097152 ? 7 : 8
33370 : part2 < 128 ? 9 : 10;
33371};
33372
33373},{"../util/minimal":220}],220:[function(require,module,exports){
33374(function (global){
33375"use strict";
33376var util = exports;
33377
33378// used to return a Promise where callback is omitted
33379util.asPromise = require("@protobufjs/aspromise");
33380
33381// converts to / from base64 encoded strings
33382util.base64 = require("@protobufjs/base64");
33383
33384// base class of rpc.Service
33385util.EventEmitter = require("@protobufjs/eventemitter");
33386
33387// float handling accross browsers
33388util.float = require("@protobufjs/float");
33389
33390// requires modules optionally and hides the call from bundlers
33391util.inquire = require("@protobufjs/inquire");
33392
33393// converts to / from utf8 encoded strings
33394util.utf8 = require("@protobufjs/utf8");
33395
33396// provides a node-like buffer pool in the browser
33397util.pool = require("@protobufjs/pool");
33398
33399// utility to work with the low and high bits of a 64 bit value
33400util.LongBits = require("./longbits");
33401
33402/**
33403 * An immuable empty array.
33404 * @memberof util
33405 * @type {Array.<*>}
33406 * @const
33407 */
33408util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes
33409
33410/**
33411 * An immutable empty object.
33412 * @type {Object}
33413 * @const
33414 */
33415util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes
33416
33417/**
33418 * Whether running within node or not.
33419 * @memberof util
33420 * @type {boolean}
33421 * @const
33422 */
33423util.isNode = Boolean(global.process && global.process.versions && global.process.versions.node);
33424
33425/**
33426 * Tests if the specified value is an integer.
33427 * @function
33428 * @param {*} value Value to test
33429 * @returns {boolean} `true` if the value is an integer
33430 */
33431util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {
33432 return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
33433};
33434
33435/**
33436 * Tests if the specified value is a string.
33437 * @param {*} value Value to test
33438 * @returns {boolean} `true` if the value is a string
33439 */
33440util.isString = function isString(value) {
33441 return typeof value === "string" || value instanceof String;
33442};
33443
33444/**
33445 * Tests if the specified value is a non-null object.
33446 * @param {*} value Value to test
33447 * @returns {boolean} `true` if the value is a non-null object
33448 */
33449util.isObject = function isObject(value) {
33450 return value && typeof value === "object";
33451};
33452
33453/**
33454 * Checks if a property on a message is considered to be present.
33455 * This is an alias of {@link util.isSet}.
33456 * @function
33457 * @param {Object} obj Plain object or message instance
33458 * @param {string} prop Property name
33459 * @returns {boolean} `true` if considered to be present, otherwise `false`
33460 */
33461util.isset =
33462
33463/**
33464 * Checks if a property on a message is considered to be present.
33465 * @param {Object} obj Plain object or message instance
33466 * @param {string} prop Property name
33467 * @returns {boolean} `true` if considered to be present, otherwise `false`
33468 */
33469util.isSet = function isSet(obj, prop) {
33470 var value = obj[prop];
33471 if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins
33472 return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;
33473 return false;
33474};
33475
33476/**
33477 * Any compatible Buffer instance.
33478 * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.
33479 * @interface Buffer
33480 * @extends Uint8Array
33481 */
33482
33483/**
33484 * Node's Buffer class if available.
33485 * @type {Constructor<Buffer>}
33486 */
33487util.Buffer = (function() {
33488 try {
33489 var Buffer = util.inquire("buffer").Buffer;
33490 // refuse to use non-node buffers if not explicitly assigned (perf reasons):
33491 return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;
33492 } catch (e) {
33493 /* istanbul ignore next */
33494 return null;
33495 }
33496})();
33497
33498// Internal alias of or polyfull for Buffer.from.
33499util._Buffer_from = null;
33500
33501// Internal alias of or polyfill for Buffer.allocUnsafe.
33502util._Buffer_allocUnsafe = null;
33503
33504/**
33505 * Creates a new buffer of whatever type supported by the environment.
33506 * @param {number|number[]} [sizeOrArray=0] Buffer size or number array
33507 * @returns {Uint8Array|Buffer} Buffer
33508 */
33509util.newBuffer = function newBuffer(sizeOrArray) {
33510 /* istanbul ignore next */
33511 return typeof sizeOrArray === "number"
33512 ? util.Buffer
33513 ? util._Buffer_allocUnsafe(sizeOrArray)
33514 : new util.Array(sizeOrArray)
33515 : util.Buffer
33516 ? util._Buffer_from(sizeOrArray)
33517 : typeof Uint8Array === "undefined"
33518 ? sizeOrArray
33519 : new Uint8Array(sizeOrArray);
33520};
33521
33522/**
33523 * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.
33524 * @type {Constructor<Uint8Array>}
33525 */
33526util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array;
33527
33528/**
33529 * Any compatible Long instance.
33530 * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.
33531 * @interface Long
33532 * @property {number} low Low bits
33533 * @property {number} high High bits
33534 * @property {boolean} unsigned Whether unsigned or not
33535 */
33536
33537/**
33538 * Long.js's Long class if available.
33539 * @type {Constructor<Long>}
33540 */
33541util.Long = /* istanbul ignore next */ global.dcodeIO && /* istanbul ignore next */ global.dcodeIO.Long || util.inquire("long");
33542
33543/**
33544 * Regular expression used to verify 2 bit (`bool`) map keys.
33545 * @type {RegExp}
33546 * @const
33547 */
33548util.key2Re = /^true|false|0|1$/;
33549
33550/**
33551 * Regular expression used to verify 32 bit (`int32` etc.) map keys.
33552 * @type {RegExp}
33553 * @const
33554 */
33555util.key32Re = /^-?(?:0|[1-9][0-9]*)$/;
33556
33557/**
33558 * Regular expression used to verify 64 bit (`int64` etc.) map keys.
33559 * @type {RegExp}
33560 * @const
33561 */
33562util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;
33563
33564/**
33565 * Converts a number or long to an 8 characters long hash string.
33566 * @param {Long|number} value Value to convert
33567 * @returns {string} Hash
33568 */
33569util.longToHash = function longToHash(value) {
33570 return value
33571 ? util.LongBits.from(value).toHash()
33572 : util.LongBits.zeroHash;
33573};
33574
33575/**
33576 * Converts an 8 characters long hash string to a long or number.
33577 * @param {string} hash Hash
33578 * @param {boolean} [unsigned=false] Whether unsigned or not
33579 * @returns {Long|number} Original value
33580 */
33581util.longFromHash = function longFromHash(hash, unsigned) {
33582 var bits = util.LongBits.fromHash(hash);
33583 if (util.Long)
33584 return util.Long.fromBits(bits.lo, bits.hi, unsigned);
33585 return bits.toNumber(Boolean(unsigned));
33586};
33587
33588/**
33589 * Merges the properties of the source object into the destination object.
33590 * @memberof util
33591 * @param {Object.<string,*>} dst Destination object
33592 * @param {Object.<string,*>} src Source object
33593 * @param {boolean} [ifNotSet=false] Merges only if the key is not already set
33594 * @returns {Object.<string,*>} Destination object
33595 */
33596function merge(dst, src, ifNotSet) { // used by converters
33597 for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)
33598 if (dst[keys[i]] === undefined || !ifNotSet)
33599 dst[keys[i]] = src[keys[i]];
33600 return dst;
33601}
33602
33603util.merge = merge;
33604
33605/**
33606 * Converts the first character of a string to lower case.
33607 * @param {string} str String to convert
33608 * @returns {string} Converted string
33609 */
33610util.lcFirst = function lcFirst(str) {
33611 return str.charAt(0).toLowerCase() + str.substring(1);
33612};
33613
33614/**
33615 * Creates a custom error constructor.
33616 * @memberof util
33617 * @param {string} name Error name
33618 * @returns {Constructor<Error>} Custom error constructor
33619 */
33620function newError(name) {
33621
33622 function CustomError(message, properties) {
33623
33624 if (!(this instanceof CustomError))
33625 return new CustomError(message, properties);
33626
33627 // Error.call(this, message);
33628 // ^ just returns a new error instance because the ctor can be called as a function
33629
33630 Object.defineProperty(this, "message", { get: function() { return message; } });
33631
33632 /* istanbul ignore next */
33633 if (Error.captureStackTrace) // node
33634 Error.captureStackTrace(this, CustomError);
33635 else
33636 Object.defineProperty(this, "stack", { value: (new Error()).stack || "" });
33637
33638 if (properties)
33639 merge(this, properties);
33640 }
33641
33642 (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError;
33643
33644 Object.defineProperty(CustomError.prototype, "name", { get: function() { return name; } });
33645
33646 CustomError.prototype.toString = function toString() {
33647 return this.name + ": " + this.message;
33648 };
33649
33650 return CustomError;
33651}
33652
33653util.newError = newError;
33654
33655/**
33656 * Constructs a new protocol error.
33657 * @classdesc Error subclass indicating a protocol specifc error.
33658 * @memberof util
33659 * @extends Error
33660 * @template T extends Message<T>
33661 * @constructor
33662 * @param {string} message Error message
33663 * @param {Object.<string,*>} [properties] Additional properties
33664 * @example
33665 * try {
33666 * MyMessage.decode(someBuffer); // throws if required fields are missing
33667 * } catch (e) {
33668 * if (e instanceof ProtocolError && e.instance)
33669 * console.log("decoded so far: " + JSON.stringify(e.instance));
33670 * }
33671 */
33672util.ProtocolError = newError("ProtocolError");
33673
33674/**
33675 * So far decoded message instance.
33676 * @name util.ProtocolError#instance
33677 * @type {Message<T>}
33678 */
33679
33680/**
33681 * A OneOf getter as returned by {@link util.oneOfGetter}.
33682 * @typedef OneOfGetter
33683 * @type {function}
33684 * @returns {string|undefined} Set field name, if any
33685 */
33686
33687/**
33688 * Builds a getter for a oneof's present field name.
33689 * @param {string[]} fieldNames Field names
33690 * @returns {OneOfGetter} Unbound getter
33691 */
33692util.oneOfGetter = function getOneOf(fieldNames) {
33693 var fieldMap = {};
33694 for (var i = 0; i < fieldNames.length; ++i)
33695 fieldMap[fieldNames[i]] = 1;
33696
33697 /**
33698 * @returns {string|undefined} Set field name, if any
33699 * @this Object
33700 * @ignore
33701 */
33702 return function() { // eslint-disable-line consistent-return
33703 for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)
33704 if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)
33705 return keys[i];
33706 };
33707};
33708
33709/**
33710 * A OneOf setter as returned by {@link util.oneOfSetter}.
33711 * @typedef OneOfSetter
33712 * @type {function}
33713 * @param {string|undefined} value Field name
33714 * @returns {undefined}
33715 */
33716
33717/**
33718 * Builds a setter for a oneof's present field name.
33719 * @param {string[]} fieldNames Field names
33720 * @returns {OneOfSetter} Unbound setter
33721 */
33722util.oneOfSetter = function setOneOf(fieldNames) {
33723
33724 /**
33725 * @param {string} name Field name
33726 * @returns {undefined}
33727 * @this Object
33728 * @ignore
33729 */
33730 return function(name) {
33731 for (var i = 0; i < fieldNames.length; ++i)
33732 if (fieldNames[i] !== name)
33733 delete this[fieldNames[i]];
33734 };
33735};
33736
33737/**
33738 * Default conversion options used for {@link Message#toJSON} implementations.
33739 *
33740 * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:
33741 *
33742 * - Longs become strings
33743 * - Enums become string keys
33744 * - Bytes become base64 encoded strings
33745 * - (Sub-)Messages become plain objects
33746 * - Maps become plain objects with all string keys
33747 * - Repeated fields become arrays
33748 * - NaN and Infinity for float and double fields become strings
33749 *
33750 * @type {IConversionOptions}
33751 * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json
33752 */
33753util.toJSONOptions = {
33754 longs: String,
33755 enums: String,
33756 bytes: String,
33757 json: true
33758};
33759
33760util._configure = function() {
33761 var Buffer = util.Buffer;
33762 /* istanbul ignore if */
33763 if (!Buffer) {
33764 util._Buffer_from = util._Buffer_allocUnsafe = null;
33765 return;
33766 }
33767 // because node 4.x buffers are incompatible & immutable
33768 // see: https://github.com/dcodeIO/protobuf.js/pull/665
33769 util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||
33770 /* istanbul ignore next */
33771 function Buffer_from(value, encoding) {
33772 return new Buffer(value, encoding);
33773 };
33774 util._Buffer_allocUnsafe = Buffer.allocUnsafe ||
33775 /* istanbul ignore next */
33776 function Buffer_allocUnsafe(size) {
33777 return new Buffer(size);
33778 };
33779};
33780
33781}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
33782},{"./longbits":219,"@protobufjs/aspromise":22,"@protobufjs/base64":23,"@protobufjs/eventemitter":25,"@protobufjs/float":27,"@protobufjs/inquire":28,"@protobufjs/pool":30,"@protobufjs/utf8":31}],221:[function(require,module,exports){
33783"use strict";
33784module.exports = verifier;
33785
33786var Enum = require("./enum"),
33787 util = require("./util");
33788
33789function invalid(field, expected) {
33790 return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected";
33791}
33792
33793/**
33794 * Generates a partial value verifier.
33795 * @param {Codegen} gen Codegen instance
33796 * @param {Field} field Reflected field
33797 * @param {number} fieldIndex Field index
33798 * @param {string} ref Variable reference
33799 * @returns {Codegen} Codegen instance
33800 * @ignore
33801 */
33802function genVerifyValue(gen, field, fieldIndex, ref) {
33803 /* eslint-disable no-unexpected-multiline */
33804 if (field.resolvedType) {
33805 if (field.resolvedType instanceof Enum) { gen
33806 ("switch(%s){", ref)
33807 ("default:")
33808 ("return%j", invalid(field, "enum value"));
33809 for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen
33810 ("case %i:", field.resolvedType.values[keys[j]]);
33811 gen
33812 ("break")
33813 ("}");
33814 } else {
33815 gen
33816 ("{")
33817 ("var e=types[%i].verify(%s);", fieldIndex, ref)
33818 ("if(e)")
33819 ("return%j+e", field.name + ".")
33820 ("}");
33821 }
33822 } else {
33823 switch (field.type) {
33824 case "int32":
33825 case "uint32":
33826 case "sint32":
33827 case "fixed32":
33828 case "sfixed32": gen
33829 ("if(!util.isInteger(%s))", ref)
33830 ("return%j", invalid(field, "integer"));
33831 break;
33832 case "int64":
33833 case "uint64":
33834 case "sint64":
33835 case "fixed64":
33836 case "sfixed64": gen
33837 ("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref)
33838 ("return%j", invalid(field, "integer|Long"));
33839 break;
33840 case "float":
33841 case "double": gen
33842 ("if(typeof %s!==\"number\")", ref)
33843 ("return%j", invalid(field, "number"));
33844 break;
33845 case "bool": gen
33846 ("if(typeof %s!==\"boolean\")", ref)
33847 ("return%j", invalid(field, "boolean"));
33848 break;
33849 case "string": gen
33850 ("if(!util.isString(%s))", ref)
33851 ("return%j", invalid(field, "string"));
33852 break;
33853 case "bytes": gen
33854 ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref)
33855 ("return%j", invalid(field, "buffer"));
33856 break;
33857 }
33858 }
33859 return gen;
33860 /* eslint-enable no-unexpected-multiline */
33861}
33862
33863/**
33864 * Generates a partial key verifier.
33865 * @param {Codegen} gen Codegen instance
33866 * @param {Field} field Reflected field
33867 * @param {string} ref Variable reference
33868 * @returns {Codegen} Codegen instance
33869 * @ignore
33870 */
33871function genVerifyKey(gen, field, ref) {
33872 /* eslint-disable no-unexpected-multiline */
33873 switch (field.keyType) {
33874 case "int32":
33875 case "uint32":
33876 case "sint32":
33877 case "fixed32":
33878 case "sfixed32": gen
33879 ("if(!util.key32Re.test(%s))", ref)
33880 ("return%j", invalid(field, "integer key"));
33881 break;
33882 case "int64":
33883 case "uint64":
33884 case "sint64":
33885 case "fixed64":
33886 case "sfixed64": gen
33887 ("if(!util.key64Re.test(%s))", ref) // see comment above: x is ok, d is not
33888 ("return%j", invalid(field, "integer|Long key"));
33889 break;
33890 case "bool": gen
33891 ("if(!util.key2Re.test(%s))", ref)
33892 ("return%j", invalid(field, "boolean key"));
33893 break;
33894 }
33895 return gen;
33896 /* eslint-enable no-unexpected-multiline */
33897}
33898
33899/**
33900 * Generates a verifier specific to the specified message type.
33901 * @param {Type} mtype Message type
33902 * @returns {Codegen} Codegen instance
33903 */
33904function verifier(mtype) {
33905 /* eslint-disable no-unexpected-multiline */
33906
33907 var gen = util.codegen(["m"], mtype.name + "$verify")
33908 ("if(typeof m!==\"object\"||m===null)")
33909 ("return%j", "object expected");
33910 var oneofs = mtype.oneofsArray,
33911 seenFirstField = {};
33912 if (oneofs.length) gen
33913 ("var p={}");
33914
33915 for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {
33916 var field = mtype._fieldsArray[i].resolve(),
33917 ref = "m" + util.safeProp(field.name);
33918
33919 if (field.optional) gen
33920 ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); // !== undefined && !== null
33921
33922 // map fields
33923 if (field.map) { gen
33924 ("if(!util.isObject(%s))", ref)
33925 ("return%j", invalid(field, "object"))
33926 ("var k=Object.keys(%s)", ref)
33927 ("for(var i=0;i<k.length;++i){");
33928 genVerifyKey(gen, field, "k[i]");
33929 genVerifyValue(gen, field, i, ref + "[k[i]]")
33930 ("}");
33931
33932 // repeated fields
33933 } else if (field.repeated) { gen
33934 ("if(!Array.isArray(%s))", ref)
33935 ("return%j", invalid(field, "array"))
33936 ("for(var i=0;i<%s.length;++i){", ref);
33937 genVerifyValue(gen, field, i, ref + "[i]")
33938 ("}");
33939
33940 // required or present fields
33941 } else {
33942 if (field.partOf) {
33943 var oneofProp = util.safeProp(field.partOf.name);
33944 if (seenFirstField[field.partOf.name] === 1) gen
33945 ("if(p%s===1)", oneofProp)
33946 ("return%j", field.partOf.name + ": multiple values");
33947 seenFirstField[field.partOf.name] = 1;
33948 gen
33949 ("p%s=1", oneofProp);
33950 }
33951 genVerifyValue(gen, field, i, ref);
33952 }
33953 if (field.optional) gen
33954 ("}");
33955 }
33956 return gen
33957 ("return null");
33958 /* eslint-enable no-unexpected-multiline */
33959}
33960},{"./enum":196,"./util":218}],222:[function(require,module,exports){
33961"use strict";
33962
33963/**
33964 * Wrappers for common types.
33965 * @type {Object.<string,IWrapper>}
33966 * @const
33967 */
33968var wrappers = exports;
33969
33970var Message = require("./message");
33971
33972/**
33973 * From object converter part of an {@link IWrapper}.
33974 * @typedef WrapperFromObjectConverter
33975 * @type {function}
33976 * @param {Object.<string,*>} object Plain object
33977 * @returns {Message<{}>} Message instance
33978 * @this Type
33979 */
33980
33981/**
33982 * To object converter part of an {@link IWrapper}.
33983 * @typedef WrapperToObjectConverter
33984 * @type {function}
33985 * @param {Message<{}>} message Message instance
33986 * @param {IConversionOptions} [options] Conversion options
33987 * @returns {Object.<string,*>} Plain object
33988 * @this Type
33989 */
33990
33991/**
33992 * Common type wrapper part of {@link wrappers}.
33993 * @interface IWrapper
33994 * @property {WrapperFromObjectConverter} [fromObject] From object converter
33995 * @property {WrapperToObjectConverter} [toObject] To object converter
33996 */
33997
33998// Custom wrapper for Any
33999wrappers[".google.protobuf.Any"] = {
34000
34001 fromObject: function(object) {
34002
34003 // unwrap value type if mapped
34004 if (object && object["@type"]) {
34005 var type = this.lookup(object["@type"]);
34006 /* istanbul ignore else */
34007 if (type) {
34008 // type_url does not accept leading "."
34009 var type_url = object["@type"].charAt(0) === "." ?
34010 object["@type"].substr(1) : object["@type"];
34011 // type_url prefix is optional, but path seperator is required
34012 return this.create({
34013 type_url: "/" + type_url,
34014 value: type.encode(type.fromObject(object)).finish()
34015 });
34016 }
34017 }
34018
34019 return this.fromObject(object);
34020 },
34021
34022 toObject: function(message, options) {
34023
34024 // decode value if requested and unmapped
34025 if (options && options.json && message.type_url && message.value) {
34026 // Only use fully qualified type name after the last '/'
34027 var name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1);
34028 var type = this.lookup(name);
34029 /* istanbul ignore else */
34030 if (type)
34031 message = type.decode(message.value);
34032 }
34033
34034 // wrap value if unmapped
34035 if (!(message instanceof this.ctor) && message instanceof Message) {
34036 var object = message.$type.toObject(message, options);
34037 object["@type"] = message.$type.fullName;
34038 return object;
34039 }
34040
34041 return this.toObject(message, options);
34042 }
34043};
34044
34045},{"./message":202}],223:[function(require,module,exports){
34046"use strict";
34047module.exports = Writer;
34048
34049var util = require("./util/minimal");
34050
34051var BufferWriter; // cyclic
34052
34053var LongBits = util.LongBits,
34054 base64 = util.base64,
34055 utf8 = util.utf8;
34056
34057/**
34058 * Constructs a new writer operation instance.
34059 * @classdesc Scheduled writer operation.
34060 * @constructor
34061 * @param {function(*, Uint8Array, number)} fn Function to call
34062 * @param {number} len Value byte length
34063 * @param {*} val Value to write
34064 * @ignore
34065 */
34066function Op(fn, len, val) {
34067
34068 /**
34069 * Function to call.
34070 * @type {function(Uint8Array, number, *)}
34071 */
34072 this.fn = fn;
34073
34074 /**
34075 * Value byte length.
34076 * @type {number}
34077 */
34078 this.len = len;
34079
34080 /**
34081 * Next operation.
34082 * @type {Writer.Op|undefined}
34083 */
34084 this.next = undefined;
34085
34086 /**
34087 * Value to write.
34088 * @type {*}
34089 */
34090 this.val = val; // type varies
34091}
34092
34093/* istanbul ignore next */
34094function noop() {} // eslint-disable-line no-empty-function
34095
34096/**
34097 * Constructs a new writer state instance.
34098 * @classdesc Copied writer state.
34099 * @memberof Writer
34100 * @constructor
34101 * @param {Writer} writer Writer to copy state from
34102 * @ignore
34103 */
34104function State(writer) {
34105
34106 /**
34107 * Current head.
34108 * @type {Writer.Op}
34109 */
34110 this.head = writer.head;
34111
34112 /**
34113 * Current tail.
34114 * @type {Writer.Op}
34115 */
34116 this.tail = writer.tail;
34117
34118 /**
34119 * Current buffer length.
34120 * @type {number}
34121 */
34122 this.len = writer.len;
34123
34124 /**
34125 * Next state.
34126 * @type {State|null}
34127 */
34128 this.next = writer.states;
34129}
34130
34131/**
34132 * Constructs a new writer instance.
34133 * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.
34134 * @constructor
34135 */
34136function Writer() {
34137
34138 /**
34139 * Current length.
34140 * @type {number}
34141 */
34142 this.len = 0;
34143
34144 /**
34145 * Operations head.
34146 * @type {Object}
34147 */
34148 this.head = new Op(noop, 0, 0);
34149
34150 /**
34151 * Operations tail
34152 * @type {Object}
34153 */
34154 this.tail = this.head;
34155
34156 /**
34157 * Linked forked states.
34158 * @type {Object|null}
34159 */
34160 this.states = null;
34161
34162 // When a value is written, the writer calculates its byte length and puts it into a linked
34163 // list of operations to perform when finish() is called. This both allows us to allocate
34164 // buffers of the exact required size and reduces the amount of work we have to do compared
34165 // to first calculating over objects and then encoding over objects. In our case, the encoding
34166 // part is just a linked list walk calling operations with already prepared values.
34167}
34168
34169/**
34170 * Creates a new writer.
34171 * @function
34172 * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}
34173 */
34174Writer.create = util.Buffer
34175 ? function create_buffer_setup() {
34176 return (Writer.create = function create_buffer() {
34177 return new BufferWriter();
34178 })();
34179 }
34180 /* istanbul ignore next */
34181 : function create_array() {
34182 return new Writer();
34183 };
34184
34185/**
34186 * Allocates a buffer of the specified size.
34187 * @param {number} size Buffer size
34188 * @returns {Uint8Array} Buffer
34189 */
34190Writer.alloc = function alloc(size) {
34191 return new util.Array(size);
34192};
34193
34194// Use Uint8Array buffer pool in the browser, just like node does with buffers
34195/* istanbul ignore else */
34196if (util.Array !== Array)
34197 Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);
34198
34199/**
34200 * Pushes a new operation to the queue.
34201 * @param {function(Uint8Array, number, *)} fn Function to call
34202 * @param {number} len Value byte length
34203 * @param {number} val Value to write
34204 * @returns {Writer} `this`
34205 * @private
34206 */
34207Writer.prototype._push = function push(fn, len, val) {
34208 this.tail = this.tail.next = new Op(fn, len, val);
34209 this.len += len;
34210 return this;
34211};
34212
34213function writeByte(val, buf, pos) {
34214 buf[pos] = val & 255;
34215}
34216
34217function writeVarint32(val, buf, pos) {
34218 while (val > 127) {
34219 buf[pos++] = val & 127 | 128;
34220 val >>>= 7;
34221 }
34222 buf[pos] = val;
34223}
34224
34225/**
34226 * Constructs a new varint writer operation instance.
34227 * @classdesc Scheduled varint writer operation.
34228 * @extends Op
34229 * @constructor
34230 * @param {number} len Value byte length
34231 * @param {number} val Value to write
34232 * @ignore
34233 */
34234function VarintOp(len, val) {
34235 this.len = len;
34236 this.next = undefined;
34237 this.val = val;
34238}
34239
34240VarintOp.prototype = Object.create(Op.prototype);
34241VarintOp.prototype.fn = writeVarint32;
34242
34243/**
34244 * Writes an unsigned 32 bit value as a varint.
34245 * @param {number} value Value to write
34246 * @returns {Writer} `this`
34247 */
34248Writer.prototype.uint32 = function write_uint32(value) {
34249 // here, the call to this.push has been inlined and a varint specific Op subclass is used.
34250 // uint32 is by far the most frequently used operation and benefits significantly from this.
34251 this.len += (this.tail = this.tail.next = new VarintOp(
34252 (value = value >>> 0)
34253 < 128 ? 1
34254 : value < 16384 ? 2
34255 : value < 2097152 ? 3
34256 : value < 268435456 ? 4
34257 : 5,
34258 value)).len;
34259 return this;
34260};
34261
34262/**
34263 * Writes a signed 32 bit value as a varint.
34264 * @function
34265 * @param {number} value Value to write
34266 * @returns {Writer} `this`
34267 */
34268Writer.prototype.int32 = function write_int32(value) {
34269 return value < 0
34270 ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec
34271 : this.uint32(value);
34272};
34273
34274/**
34275 * Writes a 32 bit value as a varint, zig-zag encoded.
34276 * @param {number} value Value to write
34277 * @returns {Writer} `this`
34278 */
34279Writer.prototype.sint32 = function write_sint32(value) {
34280 return this.uint32((value << 1 ^ value >> 31) >>> 0);
34281};
34282
34283function writeVarint64(val, buf, pos) {
34284 while (val.hi) {
34285 buf[pos++] = val.lo & 127 | 128;
34286 val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;
34287 val.hi >>>= 7;
34288 }
34289 while (val.lo > 127) {
34290 buf[pos++] = val.lo & 127 | 128;
34291 val.lo = val.lo >>> 7;
34292 }
34293 buf[pos++] = val.lo;
34294}
34295
34296/**
34297 * Writes an unsigned 64 bit value as a varint.
34298 * @param {Long|number|string} value Value to write
34299 * @returns {Writer} `this`
34300 * @throws {TypeError} If `value` is a string and no long library is present.
34301 */
34302Writer.prototype.uint64 = function write_uint64(value) {
34303 var bits = LongBits.from(value);
34304 return this._push(writeVarint64, bits.length(), bits);
34305};
34306
34307/**
34308 * Writes a signed 64 bit value as a varint.
34309 * @function
34310 * @param {Long|number|string} value Value to write
34311 * @returns {Writer} `this`
34312 * @throws {TypeError} If `value` is a string and no long library is present.
34313 */
34314Writer.prototype.int64 = Writer.prototype.uint64;
34315
34316/**
34317 * Writes a signed 64 bit value as a varint, zig-zag encoded.
34318 * @param {Long|number|string} value Value to write
34319 * @returns {Writer} `this`
34320 * @throws {TypeError} If `value` is a string and no long library is present.
34321 */
34322Writer.prototype.sint64 = function write_sint64(value) {
34323 var bits = LongBits.from(value).zzEncode();
34324 return this._push(writeVarint64, bits.length(), bits);
34325};
34326
34327/**
34328 * Writes a boolish value as a varint.
34329 * @param {boolean} value Value to write
34330 * @returns {Writer} `this`
34331 */
34332Writer.prototype.bool = function write_bool(value) {
34333 return this._push(writeByte, 1, value ? 1 : 0);
34334};
34335
34336function writeFixed32(val, buf, pos) {
34337 buf[pos ] = val & 255;
34338 buf[pos + 1] = val >>> 8 & 255;
34339 buf[pos + 2] = val >>> 16 & 255;
34340 buf[pos + 3] = val >>> 24;
34341}
34342
34343/**
34344 * Writes an unsigned 32 bit value as fixed 32 bits.
34345 * @param {number} value Value to write
34346 * @returns {Writer} `this`
34347 */
34348Writer.prototype.fixed32 = function write_fixed32(value) {
34349 return this._push(writeFixed32, 4, value >>> 0);
34350};
34351
34352/**
34353 * Writes a signed 32 bit value as fixed 32 bits.
34354 * @function
34355 * @param {number} value Value to write
34356 * @returns {Writer} `this`
34357 */
34358Writer.prototype.sfixed32 = Writer.prototype.fixed32;
34359
34360/**
34361 * Writes an unsigned 64 bit value as fixed 64 bits.
34362 * @param {Long|number|string} value Value to write
34363 * @returns {Writer} `this`
34364 * @throws {TypeError} If `value` is a string and no long library is present.
34365 */
34366Writer.prototype.fixed64 = function write_fixed64(value) {
34367 var bits = LongBits.from(value);
34368 return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);
34369};
34370
34371/**
34372 * Writes a signed 64 bit value as fixed 64 bits.
34373 * @function
34374 * @param {Long|number|string} value Value to write
34375 * @returns {Writer} `this`
34376 * @throws {TypeError} If `value` is a string and no long library is present.
34377 */
34378Writer.prototype.sfixed64 = Writer.prototype.fixed64;
34379
34380/**
34381 * Writes a float (32 bit).
34382 * @function
34383 * @param {number} value Value to write
34384 * @returns {Writer} `this`
34385 */
34386Writer.prototype.float = function write_float(value) {
34387 return this._push(util.float.writeFloatLE, 4, value);
34388};
34389
34390/**
34391 * Writes a double (64 bit float).
34392 * @function
34393 * @param {number} value Value to write
34394 * @returns {Writer} `this`
34395 */
34396Writer.prototype.double = function write_double(value) {
34397 return this._push(util.float.writeDoubleLE, 8, value);
34398};
34399
34400var writeBytes = util.Array.prototype.set
34401 ? function writeBytes_set(val, buf, pos) {
34402 buf.set(val, pos); // also works for plain array values
34403 }
34404 /* istanbul ignore next */
34405 : function writeBytes_for(val, buf, pos) {
34406 for (var i = 0; i < val.length; ++i)
34407 buf[pos + i] = val[i];
34408 };
34409
34410/**
34411 * Writes a sequence of bytes.
34412 * @param {Uint8Array|string} value Buffer or base64 encoded string to write
34413 * @returns {Writer} `this`
34414 */
34415Writer.prototype.bytes = function write_bytes(value) {
34416 var len = value.length >>> 0;
34417 if (!len)
34418 return this._push(writeByte, 1, 0);
34419 if (util.isString(value)) {
34420 var buf = Writer.alloc(len = base64.length(value));
34421 base64.decode(value, buf, 0);
34422 value = buf;
34423 }
34424 return this.uint32(len)._push(writeBytes, len, value);
34425};
34426
34427/**
34428 * Writes a string.
34429 * @param {string} value Value to write
34430 * @returns {Writer} `this`
34431 */
34432Writer.prototype.string = function write_string(value) {
34433 var len = utf8.length(value);
34434 return len
34435 ? this.uint32(len)._push(utf8.write, len, value)
34436 : this._push(writeByte, 1, 0);
34437};
34438
34439/**
34440 * Forks this writer's state by pushing it to a stack.
34441 * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.
34442 * @returns {Writer} `this`
34443 */
34444Writer.prototype.fork = function fork() {
34445 this.states = new State(this);
34446 this.head = this.tail = new Op(noop, 0, 0);
34447 this.len = 0;
34448 return this;
34449};
34450
34451/**
34452 * Resets this instance to the last state.
34453 * @returns {Writer} `this`
34454 */
34455Writer.prototype.reset = function reset() {
34456 if (this.states) {
34457 this.head = this.states.head;
34458 this.tail = this.states.tail;
34459 this.len = this.states.len;
34460 this.states = this.states.next;
34461 } else {
34462 this.head = this.tail = new Op(noop, 0, 0);
34463 this.len = 0;
34464 }
34465 return this;
34466};
34467
34468/**
34469 * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.
34470 * @returns {Writer} `this`
34471 */
34472Writer.prototype.ldelim = function ldelim() {
34473 var head = this.head,
34474 tail = this.tail,
34475 len = this.len;
34476 this.reset().uint32(len);
34477 if (len) {
34478 this.tail.next = head.next; // skip noop
34479 this.tail = tail;
34480 this.len += len;
34481 }
34482 return this;
34483};
34484
34485/**
34486 * Finishes the write operation.
34487 * @returns {Uint8Array} Finished buffer
34488 */
34489Writer.prototype.finish = function finish() {
34490 var head = this.head.next, // skip noop
34491 buf = this.constructor.alloc(this.len),
34492 pos = 0;
34493 while (head) {
34494 head.fn(head.val, buf, pos);
34495 pos += head.len;
34496 head = head.next;
34497 }
34498 // this.head = this.tail = null;
34499 return buf;
34500};
34501
34502Writer._configure = function(BufferWriter_) {
34503 BufferWriter = BufferWriter_;
34504};
34505
34506},{"./util/minimal":220}],224:[function(require,module,exports){
34507"use strict";
34508module.exports = BufferWriter;
34509
34510// extends Writer
34511var Writer = require("./writer");
34512(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;
34513
34514var util = require("./util/minimal");
34515
34516var Buffer = util.Buffer;
34517
34518/**
34519 * Constructs a new buffer writer instance.
34520 * @classdesc Wire format writer using node buffers.
34521 * @extends Writer
34522 * @constructor
34523 */
34524function BufferWriter() {
34525 Writer.call(this);
34526}
34527
34528/**
34529 * Allocates a buffer of the specified size.
34530 * @param {number} size Buffer size
34531 * @returns {Buffer} Buffer
34532 */
34533BufferWriter.alloc = function alloc_buffer(size) {
34534 return (BufferWriter.alloc = util._Buffer_allocUnsafe)(size);
34535};
34536
34537var writeBytesBuffer = Buffer && Buffer.prototype instanceof Uint8Array && Buffer.prototype.set.name === "set"
34538 ? function writeBytesBuffer_set(val, buf, pos) {
34539 buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)
34540 // also works for plain array values
34541 }
34542 /* istanbul ignore next */
34543 : function writeBytesBuffer_copy(val, buf, pos) {
34544 if (val.copy) // Buffer values
34545 val.copy(buf, pos, 0, val.length);
34546 else for (var i = 0; i < val.length;) // plain array values
34547 buf[pos++] = val[i++];
34548 };
34549
34550/**
34551 * @override
34552 */
34553BufferWriter.prototype.bytes = function write_bytes_buffer(value) {
34554 if (util.isString(value))
34555 value = util._Buffer_from(value, "base64");
34556 var len = value.length >>> 0;
34557 this.uint32(len);
34558 if (len)
34559 this._push(writeBytesBuffer, len, value);
34560 return this;
34561};
34562
34563function writeStringBuffer(val, buf, pos) {
34564 if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)
34565 util.utf8.write(val, buf, pos);
34566 else
34567 buf.utf8Write(val, pos);
34568}
34569
34570/**
34571 * @override
34572 */
34573BufferWriter.prototype.string = function write_string_buffer(value) {
34574 var len = Buffer.byteLength(value);
34575 this.uint32(len);
34576 if (len)
34577 this._push(writeStringBuffer, len, value);
34578 return this;
34579};
34580
34581
34582/**
34583 * Finishes the write operation.
34584 * @name BufferWriter#finish
34585 * @function
34586 * @returns {Buffer} Finished buffer
34587 */
34588
34589},{"./util/minimal":220,"./writer":223}],225:[function(require,module,exports){
34590exports.publicEncrypt = require('./publicEncrypt'); 21665exports.publicEncrypt = require('./publicEncrypt');
34591exports.privateDecrypt = require('./privateDecrypt'); 21666exports.privateDecrypt = require('./privateDecrypt');
34592 21667
@@ -34597,7 +21672,7 @@ exports.privateEncrypt = function privateEncrypt(key, buf) {
34597exports.publicDecrypt = function publicDecrypt(key, buf) { 21672exports.publicDecrypt = function publicDecrypt(key, buf) {
34598 return exports.privateDecrypt(key, buf, true); 21673 return exports.privateDecrypt(key, buf, true);
34599}; 21674};
34600},{"./privateDecrypt":227,"./publicEncrypt":228}],226:[function(require,module,exports){ 21675},{"./privateDecrypt":136,"./publicEncrypt":137}],135:[function(require,module,exports){
34601(function (Buffer){ 21676(function (Buffer){
34602var createHash = require('create-hash'); 21677var createHash = require('create-hash');
34603module.exports = function (seed, len) { 21678module.exports = function (seed, len) {
@@ -34616,7 +21691,7 @@ function i2ops(c) {
34616 return out; 21691 return out;
34617} 21692}
34618}).call(this,require("buffer").Buffer) 21693}).call(this,require("buffer").Buffer)
34619},{"buffer":107,"create-hash":111}],227:[function(require,module,exports){ 21694},{"buffer":53,"create-hash":57}],136:[function(require,module,exports){
34620(function (Buffer){ 21695(function (Buffer){
34621var parseKeys = require('parse-asn1'); 21696var parseKeys = require('parse-asn1');
34622var mgf = require('./mgf'); 21697var mgf = require('./mgf');
@@ -34727,7 +21802,7 @@ function compare(a, b){
34727 return dif; 21802 return dif;
34728} 21803}
34729}).call(this,require("buffer").Buffer) 21804}).call(this,require("buffer").Buffer)
34730},{"./mgf":226,"./withPublic":229,"./xor":230,"bn.js":75,"browserify-rsa":98,"buffer":107,"create-hash":111,"parse-asn1":182}],228:[function(require,module,exports){ 21805},{"./mgf":135,"./withPublic":138,"./xor":139,"bn.js":21,"browserify-rsa":44,"buffer":53,"create-hash":57,"parse-asn1":126}],137:[function(require,module,exports){
34731(function (Buffer){ 21806(function (Buffer){
34732var parseKeys = require('parse-asn1'); 21807var parseKeys = require('parse-asn1');
34733var randomBytes = require('randombytes'); 21808var randomBytes = require('randombytes');
@@ -34825,7 +21900,7 @@ function nonZero(len, crypto) {
34825 return out; 21900 return out;
34826} 21901}
34827}).call(this,require("buffer").Buffer) 21902}).call(this,require("buffer").Buffer)
34828},{"./mgf":226,"./withPublic":229,"./xor":230,"bn.js":75,"browserify-rsa":98,"buffer":107,"create-hash":111,"parse-asn1":182,"randombytes":231}],229:[function(require,module,exports){ 21903},{"./mgf":135,"./withPublic":138,"./xor":139,"bn.js":21,"browserify-rsa":44,"buffer":53,"create-hash":57,"parse-asn1":126,"randombytes":140}],138:[function(require,module,exports){
34829(function (Buffer){ 21904(function (Buffer){
34830var bn = require('bn.js'); 21905var bn = require('bn.js');
34831function withPublic(paddedMsg, key) { 21906function withPublic(paddedMsg, key) {
@@ -34838,7 +21913,7 @@ function withPublic(paddedMsg, key) {
34838 21913
34839module.exports = withPublic; 21914module.exports = withPublic;
34840}).call(this,require("buffer").Buffer) 21915}).call(this,require("buffer").Buffer)
34841},{"bn.js":75,"buffer":107}],230:[function(require,module,exports){ 21916},{"bn.js":21,"buffer":53}],139:[function(require,module,exports){
34842module.exports = function xor(a, b) { 21917module.exports = function xor(a, b) {
34843 var len = a.length; 21918 var len = a.length;
34844 var i = -1; 21919 var i = -1;
@@ -34847,7 +21922,7 @@ module.exports = function xor(a, b) {
34847 } 21922 }
34848 return a 21923 return a
34849}; 21924};
34850},{}],231:[function(require,module,exports){ 21925},{}],140:[function(require,module,exports){
34851(function (process,global){ 21926(function (process,global){
34852'use strict' 21927'use strict'
34853 21928
@@ -34889,7 +21964,7 @@ function randomBytes (size, cb) {
34889} 21964}
34890 21965
34891}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 21966}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
34892},{"_process":190,"safe-buffer":247}],232:[function(require,module,exports){ 21967},{"_process":133,"safe-buffer":156}],141:[function(require,module,exports){
34893(function (process,global){ 21968(function (process,global){
34894'use strict' 21969'use strict'
34895 21970
@@ -35001,10 +22076,10 @@ function randomFillSync (buf, offset, size) {
35001} 22076}
35002 22077
35003}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 22078}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
35004},{"_process":190,"randombytes":231,"safe-buffer":247}],233:[function(require,module,exports){ 22079},{"_process":133,"randombytes":140,"safe-buffer":156}],142:[function(require,module,exports){
35005module.exports = require('./lib/_stream_duplex.js'); 22080module.exports = require('./lib/_stream_duplex.js');
35006 22081
35007},{"./lib/_stream_duplex.js":234}],234:[function(require,module,exports){ 22082},{"./lib/_stream_duplex.js":143}],143:[function(require,module,exports){
35008// Copyright Joyent, Inc. and other Node contributors. 22083// Copyright Joyent, Inc. and other Node contributors.
35009// 22084//
35010// Permission is hereby granted, free of charge, to any person obtaining a 22085// Permission is hereby granted, free of charge, to any person obtaining a
@@ -35129,7 +22204,7 @@ function forEach(xs, f) {
35129 f(xs[i], i); 22204 f(xs[i], i);
35130 } 22205 }
35131} 22206}
35132},{"./_stream_readable":236,"./_stream_writable":238,"core-util-is":109,"inherits":163,"process-nextick-args":189}],235:[function(require,module,exports){ 22207},{"./_stream_readable":145,"./_stream_writable":147,"core-util-is":55,"inherits":107,"process-nextick-args":132}],144:[function(require,module,exports){
35133// Copyright Joyent, Inc. and other Node contributors. 22208// Copyright Joyent, Inc. and other Node contributors.
35134// 22209//
35135// Permission is hereby granted, free of charge, to any person obtaining a 22210// Permission is hereby granted, free of charge, to any person obtaining a
@@ -35177,7 +22252,7 @@ function PassThrough(options) {
35177PassThrough.prototype._transform = function (chunk, encoding, cb) { 22252PassThrough.prototype._transform = function (chunk, encoding, cb) {
35178 cb(null, chunk); 22253 cb(null, chunk);
35179}; 22254};
35180},{"./_stream_transform":237,"core-util-is":109,"inherits":163}],236:[function(require,module,exports){ 22255},{"./_stream_transform":146,"core-util-is":55,"inherits":107}],145:[function(require,module,exports){
35181(function (process,global){ 22256(function (process,global){
35182// Copyright Joyent, Inc. and other Node contributors. 22257// Copyright Joyent, Inc. and other Node contributors.
35183// 22258//
@@ -36187,7 +23262,7 @@ function indexOf(xs, x) {
36187 return -1; 23262 return -1;
36188} 23263}
36189}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 23264}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
36190},{"./_stream_duplex":234,"./internal/streams/BufferList":239,"./internal/streams/destroy":240,"./internal/streams/stream":241,"_process":190,"core-util-is":109,"events":143,"inherits":163,"isarray":165,"process-nextick-args":189,"safe-buffer":247,"string_decoder/":264,"util":77}],237:[function(require,module,exports){ 23265},{"./_stream_duplex":143,"./internal/streams/BufferList":148,"./internal/streams/destroy":149,"./internal/streams/stream":150,"_process":133,"core-util-is":55,"events":89,"inherits":107,"isarray":109,"process-nextick-args":132,"safe-buffer":156,"string_decoder/":173,"util":23}],146:[function(require,module,exports){
36191// Copyright Joyent, Inc. and other Node contributors. 23266// Copyright Joyent, Inc. and other Node contributors.
36192// 23267//
36193// Permission is hereby granted, free of charge, to any person obtaining a 23268// Permission is hereby granted, free of charge, to any person obtaining a
@@ -36402,7 +23477,7 @@ function done(stream, er, data) {
36402 23477
36403 return stream.push(null); 23478 return stream.push(null);
36404} 23479}
36405},{"./_stream_duplex":234,"core-util-is":109,"inherits":163}],238:[function(require,module,exports){ 23480},{"./_stream_duplex":143,"core-util-is":55,"inherits":107}],147:[function(require,module,exports){
36406(function (process,global){ 23481(function (process,global){
36407// Copyright Joyent, Inc. and other Node contributors. 23482// Copyright Joyent, Inc. and other Node contributors.
36408// 23483//
@@ -37069,7 +24144,7 @@ Writable.prototype._destroy = function (err, cb) {
37069 cb(err); 24144 cb(err);
37070}; 24145};
37071}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 24146}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
37072},{"./_stream_duplex":234,"./internal/streams/destroy":240,"./internal/streams/stream":241,"_process":190,"core-util-is":109,"inherits":163,"process-nextick-args":189,"safe-buffer":247,"util-deprecate":265}],239:[function(require,module,exports){ 24147},{"./_stream_duplex":143,"./internal/streams/destroy":149,"./internal/streams/stream":150,"_process":133,"core-util-is":55,"inherits":107,"process-nextick-args":132,"safe-buffer":156,"util-deprecate":174}],148:[function(require,module,exports){
37073'use strict'; 24148'use strict';
37074 24149
37075/*<replacement>*/ 24150/*<replacement>*/
@@ -37144,7 +24219,7 @@ module.exports = function () {
37144 24219
37145 return BufferList; 24220 return BufferList;
37146}(); 24221}();
37147},{"safe-buffer":247}],240:[function(require,module,exports){ 24222},{"safe-buffer":156}],149:[function(require,module,exports){
37148'use strict'; 24223'use strict';
37149 24224
37150/*<replacement>*/ 24225/*<replacement>*/
@@ -37217,13 +24292,13 @@ module.exports = {
37217 destroy: destroy, 24292 destroy: destroy,
37218 undestroy: undestroy 24293 undestroy: undestroy
37219}; 24294};
37220},{"process-nextick-args":189}],241:[function(require,module,exports){ 24295},{"process-nextick-args":132}],150:[function(require,module,exports){
37221module.exports = require('events').EventEmitter; 24296module.exports = require('events').EventEmitter;
37222 24297
37223},{"events":143}],242:[function(require,module,exports){ 24298},{"events":89}],151:[function(require,module,exports){
37224module.exports = require('./readable').PassThrough 24299module.exports = require('./readable').PassThrough
37225 24300
37226},{"./readable":243}],243:[function(require,module,exports){ 24301},{"./readable":152}],152:[function(require,module,exports){
37227exports = module.exports = require('./lib/_stream_readable.js'); 24302exports = module.exports = require('./lib/_stream_readable.js');
37228exports.Stream = exports; 24303exports.Stream = exports;
37229exports.Readable = exports; 24304exports.Readable = exports;
@@ -37232,13 +24307,13 @@ exports.Duplex = require('./lib/_stream_duplex.js');
37232exports.Transform = require('./lib/_stream_transform.js'); 24307exports.Transform = require('./lib/_stream_transform.js');
37233exports.PassThrough = require('./lib/_stream_passthrough.js'); 24308exports.PassThrough = require('./lib/_stream_passthrough.js');
37234 24309
37235},{"./lib/_stream_duplex.js":234,"./lib/_stream_passthrough.js":235,"./lib/_stream_readable.js":236,"./lib/_stream_transform.js":237,"./lib/_stream_writable.js":238}],244:[function(require,module,exports){ 24310},{"./lib/_stream_duplex.js":143,"./lib/_stream_passthrough.js":144,"./lib/_stream_readable.js":145,"./lib/_stream_transform.js":146,"./lib/_stream_writable.js":147}],153:[function(require,module,exports){
37236module.exports = require('./readable').Transform 24311module.exports = require('./readable').Transform
37237 24312
37238},{"./readable":243}],245:[function(require,module,exports){ 24313},{"./readable":152}],154:[function(require,module,exports){
37239module.exports = require('./lib/_stream_writable.js'); 24314module.exports = require('./lib/_stream_writable.js');
37240 24315
37241},{"./lib/_stream_writable.js":238}],246:[function(require,module,exports){ 24316},{"./lib/_stream_writable.js":147}],155:[function(require,module,exports){
37242(function (Buffer){ 24317(function (Buffer){
37243'use strict' 24318'use strict'
37244var inherits = require('inherits') 24319var inherits = require('inherits')
@@ -37533,7 +24608,7 @@ function fn5 (a, b, c, d, e, m, k, s) {
37533module.exports = RIPEMD160 24608module.exports = RIPEMD160
37534 24609
37535}).call(this,require("buffer").Buffer) 24610}).call(this,require("buffer").Buffer)
37536},{"buffer":107,"hash-base":146,"inherits":163}],247:[function(require,module,exports){ 24611},{"buffer":53,"hash-base":91,"inherits":107}],156:[function(require,module,exports){
37537/* eslint-disable node/no-deprecated-api */ 24612/* eslint-disable node/no-deprecated-api */
37538var buffer = require('buffer') 24613var buffer = require('buffer')
37539var Buffer = buffer.Buffer 24614var Buffer = buffer.Buffer
@@ -37597,7 +24672,7 @@ SafeBuffer.allocUnsafeSlow = function (size) {
37597 return buffer.SlowBuffer(size) 24672 return buffer.SlowBuffer(size)
37598} 24673}
37599 24674
37600},{"buffer":107}],248:[function(require,module,exports){ 24675},{"buffer":53}],157:[function(require,module,exports){
37601(function (Buffer){ 24676(function (Buffer){
37602var crypto = require('crypto') 24677var crypto = require('crypto')
37603/* eslint-disable camelcase */ 24678/* eslint-disable camelcase */
@@ -37781,11 +24856,11 @@ function arraycopy (src, srcPos, dest, destPos, length) {
37781module.exports = scrypt 24856module.exports = scrypt
37782 24857
37783}).call(this,require("buffer").Buffer) 24858}).call(this,require("buffer").Buffer)
37784},{"buffer":107,"crypto":116}],249:[function(require,module,exports){ 24859},{"buffer":53,"crypto":62}],158:[function(require,module,exports){
37785'use strict' 24860'use strict'
37786module.exports = require('./lib')(require('./lib/elliptic')) 24861module.exports = require('./lib')(require('./lib/elliptic'))
37787 24862
37788},{"./lib":253,"./lib/elliptic":252}],250:[function(require,module,exports){ 24863},{"./lib":162,"./lib/elliptic":161}],159:[function(require,module,exports){
37789(function (Buffer){ 24864(function (Buffer){
37790'use strict' 24865'use strict'
37791var toString = Object.prototype.toString 24866var toString = Object.prototype.toString
@@ -37833,7 +24908,7 @@ exports.isNumberInInterval = function (number, x, y, message) {
37833} 24908}
37834 24909
37835}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) 24910}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
37836},{"../../is-buffer/index.js":164}],251:[function(require,module,exports){ 24911},{"../../is-buffer/index.js":108}],160:[function(require,module,exports){
37837'use strict' 24912'use strict'
37838var Buffer = require('safe-buffer').Buffer 24913var Buffer = require('safe-buffer').Buffer
37839var bip66 = require('bip66') 24914var bip66 = require('bip66')
@@ -38028,7 +25103,7 @@ exports.signatureImportLax = function (sig) {
38028 return { r: r, s: s } 25103 return { r: r, s: s }
38029} 25104}
38030 25105
38031},{"bip66":74,"safe-buffer":247}],252:[function(require,module,exports){ 25106},{"bip66":20,"safe-buffer":156}],161:[function(require,module,exports){
38032'use strict' 25107'use strict'
38033var Buffer = require('safe-buffer').Buffer 25108var Buffer = require('safe-buffer').Buffer
38034var createHash = require('create-hash') 25109var createHash = require('create-hash')
@@ -38290,7 +25365,7 @@ exports.ecdhUnsafe = function (publicKey, privateKey, compressed) {
38290 return Buffer.from(pair.pub.mul(scalar).encode(true, compressed)) 25365 return Buffer.from(pair.pub.mul(scalar).encode(true, compressed))
38291} 25366}
38292 25367
38293},{"../messages.json":254,"bn.js":75,"create-hash":111,"elliptic":127,"safe-buffer":247}],253:[function(require,module,exports){ 25368},{"../messages.json":163,"bn.js":21,"create-hash":57,"elliptic":73,"safe-buffer":156}],162:[function(require,module,exports){
38294'use strict' 25369'use strict'
38295var assert = require('./assert') 25370var assert = require('./assert')
38296var der = require('./der') 25371var der = require('./der')
@@ -38537,7 +25612,7 @@ module.exports = function (secp256k1) {
38537 } 25612 }
38538} 25613}
38539 25614
38540},{"./assert":250,"./der":251,"./messages.json":254}],254:[function(require,module,exports){ 25615},{"./assert":159,"./der":160,"./messages.json":163}],163:[function(require,module,exports){
38541module.exports={ 25616module.exports={
38542 "COMPRESSED_TYPE_INVALID": "compressed should be a boolean", 25617 "COMPRESSED_TYPE_INVALID": "compressed should be a boolean",
38543 "EC_PRIVATE_KEY_TYPE_INVALID": "private key should be a Buffer", 25618 "EC_PRIVATE_KEY_TYPE_INVALID": "private key should be a Buffer",
@@ -38576,7 +25651,7 @@ module.exports={
38576 "TWEAK_LENGTH_INVALID": "tweak length is invalid" 25651 "TWEAK_LENGTH_INVALID": "tweak length is invalid"
38577} 25652}
38578 25653
38579},{}],255:[function(require,module,exports){ 25654},{}],164:[function(require,module,exports){
38580var Buffer = require('safe-buffer').Buffer 25655var Buffer = require('safe-buffer').Buffer
38581 25656
38582// prototype class for hash functions 25657// prototype class for hash functions
@@ -38659,7 +25734,7 @@ Hash.prototype._update = function () {
38659 25734
38660module.exports = Hash 25735module.exports = Hash
38661 25736
38662},{"safe-buffer":247}],256:[function(require,module,exports){ 25737},{"safe-buffer":156}],165:[function(require,module,exports){
38663var exports = module.exports = function SHA (algorithm) { 25738var exports = module.exports = function SHA (algorithm) {
38664 algorithm = algorithm.toLowerCase() 25739 algorithm = algorithm.toLowerCase()
38665 25740
@@ -38676,7 +25751,7 @@ exports.sha256 = require('./sha256')
38676exports.sha384 = require('./sha384') 25751exports.sha384 = require('./sha384')
38677exports.sha512 = require('./sha512') 25752exports.sha512 = require('./sha512')
38678 25753
38679},{"./sha":257,"./sha1":258,"./sha224":259,"./sha256":260,"./sha384":261,"./sha512":262}],257:[function(require,module,exports){ 25754},{"./sha":166,"./sha1":167,"./sha224":168,"./sha256":169,"./sha384":170,"./sha512":171}],166:[function(require,module,exports){
38680/* 25755/*
38681 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined 25756 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
38682 * in FIPS PUB 180-1 25757 * in FIPS PUB 180-1
@@ -38772,7 +25847,7 @@ Sha.prototype._hash = function () {
38772 25847
38773module.exports = Sha 25848module.exports = Sha
38774 25849
38775},{"./hash":255,"inherits":163,"safe-buffer":247}],258:[function(require,module,exports){ 25850},{"./hash":164,"inherits":107,"safe-buffer":156}],167:[function(require,module,exports){
38776/* 25851/*
38777 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined 25852 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
38778 * in FIPS PUB 180-1 25853 * in FIPS PUB 180-1
@@ -38873,7 +25948,7 @@ Sha1.prototype._hash = function () {
38873 25948
38874module.exports = Sha1 25949module.exports = Sha1
38875 25950
38876},{"./hash":255,"inherits":163,"safe-buffer":247}],259:[function(require,module,exports){ 25951},{"./hash":164,"inherits":107,"safe-buffer":156}],168:[function(require,module,exports){
38877/** 25952/**
38878 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined 25953 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
38879 * in FIPS 180-2 25954 * in FIPS 180-2
@@ -38928,7 +26003,7 @@ Sha224.prototype._hash = function () {
38928 26003
38929module.exports = Sha224 26004module.exports = Sha224
38930 26005
38931},{"./hash":255,"./sha256":260,"inherits":163,"safe-buffer":247}],260:[function(require,module,exports){ 26006},{"./hash":164,"./sha256":169,"inherits":107,"safe-buffer":156}],169:[function(require,module,exports){
38932/** 26007/**
38933 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined 26008 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
38934 * in FIPS 180-2 26009 * in FIPS 180-2
@@ -39065,7 +26140,7 @@ Sha256.prototype._hash = function () {
39065 26140
39066module.exports = Sha256 26141module.exports = Sha256
39067 26142
39068},{"./hash":255,"inherits":163,"safe-buffer":247}],261:[function(require,module,exports){ 26143},{"./hash":164,"inherits":107,"safe-buffer":156}],170:[function(require,module,exports){
39069var inherits = require('inherits') 26144var inherits = require('inherits')
39070var SHA512 = require('./sha512') 26145var SHA512 = require('./sha512')
39071var Hash = require('./hash') 26146var Hash = require('./hash')
@@ -39124,7 +26199,7 @@ Sha384.prototype._hash = function () {
39124 26199
39125module.exports = Sha384 26200module.exports = Sha384
39126 26201
39127},{"./hash":255,"./sha512":262,"inherits":163,"safe-buffer":247}],262:[function(require,module,exports){ 26202},{"./hash":164,"./sha512":171,"inherits":107,"safe-buffer":156}],171:[function(require,module,exports){
39128var inherits = require('inherits') 26203var inherits = require('inherits')
39129var Hash = require('./hash') 26204var Hash = require('./hash')
39130var Buffer = require('safe-buffer').Buffer 26205var Buffer = require('safe-buffer').Buffer
@@ -39386,7 +26461,7 @@ Sha512.prototype._hash = function () {
39386 26461
39387module.exports = Sha512 26462module.exports = Sha512
39388 26463
39389},{"./hash":255,"inherits":163,"safe-buffer":247}],263:[function(require,module,exports){ 26464},{"./hash":164,"inherits":107,"safe-buffer":156}],172:[function(require,module,exports){
39390// Copyright Joyent, Inc. and other Node contributors. 26465// Copyright Joyent, Inc. and other Node contributors.
39391// 26466//
39392// Permission is hereby granted, free of charge, to any person obtaining a 26467// Permission is hereby granted, free of charge, to any person obtaining a
@@ -39515,7 +26590,7 @@ Stream.prototype.pipe = function(dest, options) {
39515 return dest; 26590 return dest;
39516}; 26591};
39517 26592
39518},{"events":143,"inherits":163,"readable-stream/duplex.js":233,"readable-stream/passthrough.js":242,"readable-stream/readable.js":243,"readable-stream/transform.js":244,"readable-stream/writable.js":245}],264:[function(require,module,exports){ 26593},{"events":89,"inherits":107,"readable-stream/duplex.js":142,"readable-stream/passthrough.js":151,"readable-stream/readable.js":152,"readable-stream/transform.js":153,"readable-stream/writable.js":154}],173:[function(require,module,exports){
39519'use strict'; 26594'use strict';
39520 26595
39521var Buffer = require('safe-buffer').Buffer; 26596var Buffer = require('safe-buffer').Buffer;
@@ -39788,7 +26863,7 @@ function simpleWrite(buf) {
39788function simpleEnd(buf) { 26863function simpleEnd(buf) {
39789 return buf && buf.length ? this.write(buf) : ''; 26864 return buf && buf.length ? this.write(buf) : '';
39790} 26865}
39791},{"safe-buffer":247}],265:[function(require,module,exports){ 26866},{"safe-buffer":156}],174:[function(require,module,exports){
39792(function (global){ 26867(function (global){
39793 26868
39794/** 26869/**
@@ -39859,7 +26934,7 @@ function config (name) {
39859} 26934}
39860 26935
39861}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 26936}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
39862},{}],266:[function(require,module,exports){ 26937},{}],175:[function(require,module,exports){
39863var v1 = require('./v1'); 26938var v1 = require('./v1');
39864var v4 = require('./v4'); 26939var v4 = require('./v4');
39865 26940
@@ -39869,7 +26944,7 @@ uuid.v4 = v4;
39869 26944
39870module.exports = uuid; 26945module.exports = uuid;
39871 26946
39872},{"./v1":269,"./v4":270}],267:[function(require,module,exports){ 26947},{"./v1":178,"./v4":179}],176:[function(require,module,exports){
39873/** 26948/**
39874 * Convert array of 16 byte values to UUID string format of the form: 26949 * Convert array of 16 byte values to UUID string format of the form:
39875 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX 26950 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
@@ -39894,7 +26969,7 @@ function bytesToUuid(buf, offset) {
39894 26969
39895module.exports = bytesToUuid; 26970module.exports = bytesToUuid;
39896 26971
39897},{}],268:[function(require,module,exports){ 26972},{}],177:[function(require,module,exports){
39898(function (global){ 26973(function (global){
39899// Unique ID creation requires a high quality random # generator. In the 26974// Unique ID creation requires a high quality random # generator. In the
39900// browser this is a little complicated due to unknown quality of Math.random() 26975// browser this is a little complicated due to unknown quality of Math.random()
@@ -39931,7 +27006,7 @@ if (!rng) {
39931module.exports = rng; 27006module.exports = rng;
39932 27007
39933}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 27008}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
39934},{}],269:[function(require,module,exports){ 27009},{}],178:[function(require,module,exports){
39935var rng = require('./lib/rng'); 27010var rng = require('./lib/rng');
39936var bytesToUuid = require('./lib/bytesToUuid'); 27011var bytesToUuid = require('./lib/bytesToUuid');
39937 27012
@@ -40033,7 +27108,7 @@ function v1(options, buf, offset) {
40033 27108
40034module.exports = v1; 27109module.exports = v1;
40035 27110
40036},{"./lib/bytesToUuid":267,"./lib/rng":268}],270:[function(require,module,exports){ 27111},{"./lib/bytesToUuid":176,"./lib/rng":177}],179:[function(require,module,exports){
40037var rng = require('./lib/rng'); 27112var rng = require('./lib/rng');
40038var bytesToUuid = require('./lib/bytesToUuid'); 27113var bytesToUuid = require('./lib/bytesToUuid');
40039 27114
@@ -40064,7 +27139,7 @@ function v4(options, buf, offset) {
40064 27139
40065module.exports = v4; 27140module.exports = v4;
40066 27141
40067},{"./lib/bytesToUuid":267,"./lib/rng":268}],271:[function(require,module,exports){ 27142},{"./lib/bytesToUuid":176,"./lib/rng":177}],180:[function(require,module,exports){
40068var indexOf = require('indexof'); 27143var indexOf = require('indexof');
40069 27144
40070var Object_keys = function (obj) { 27145var Object_keys = function (obj) {
@@ -40204,41 +27279,419 @@ exports.createContext = Script.createContext = function (context) {
40204 return copy; 27279 return copy;
40205}; 27280};
40206 27281
40207},{"indexof":162}],"nebulas":[function(require,module,exports){ 27282},{"indexof":106}],"nebulas-account":[function(require,module,exports){
40208var HttpRequest = require("./lib/httprequest"); 27283"use strict";
40209var Neb = require('./lib/neb');
40210var Account = require('./lib/account');
40211var Transaction = require('./lib/transaction');
40212var Utils = require('./lib/utils/utils');
40213var CryptoUtils = require('./lib/utils/crypto-utils');
40214var Unit = require('./lib/utils/unit');
40215var NVM = require('./lib/nvm/nvm');
40216 27284
40217// dont override global variable 27285var Buffer = require('safe-buffer').Buffer;
40218if (typeof window !== 'undefined' && typeof window.Neb === 'undefined') { 27286var Base58 = require('bs58');
40219 window.Neb = Neb; 27287var cryptoUtils = require('./utils/crypto-utils.js');
40220} 27288var utils = require('./utils/utils.js');
40221 27289
40222module.exports = { 27290var AddressLength = 26;
40223 HttpRequest: HttpRequest, 27291var AddressPrefix = 25;
40224 Neb: Neb, 27292var NormalType = 87;
40225 Account: Account, 27293var ContractType = 88;
40226 Transaction: Transaction, 27294
40227 Utils: Utils, 27295var KeyVersion3 = 3;
40228 CryptoUtils: CryptoUtils, 27296var KeyCurrentVersion = 4;
40229 Unit: Unit, 27297
40230 NVM: NVM 27298/**
27299 * @typedef {Object} KeyOptions
27300 * @property {Buffer} salt
27301 * @property {Buffer} iv
27302 * @property {String} kdf
27303 * @property {Number} dklen
27304 * @property {Number} c
27305 * @property {Number} n
27306 * @property {Number} r
27307 * @property {Number} p
27308 * @property {String} cipher
27309 * @property {Buffer} uuid
27310 * @global
27311 */
27312
27313/**
27314 * Key Object.
27315 * @typedef {Object} Key
27316 * @property {Number} version
27317 * @property {Buffer} id
27318 * @property {HexString} address
27319 * @property {Object} crypto
27320 * @global
27321 */
27322
27323/**
27324 * Account constructor.
27325 * Class encapsulate main operation with account entity.
27326 * @constructor
27327 *
27328 * @param {Hash} priv Account private key.
27329 * @param {String} path
27330 *
27331 * @example var account = new Account(new Buffer("ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6", "hex") );
27332 *
27333 */
27334var Account = function (priv, path) {
27335 priv = priv || cryptoUtils.crypto.randomBytes(32);
27336 this.setPrivateKey(priv);
27337 this.path = path;
40231}; 27338};
40232 27339
40233},{"./lib/account":1,"./lib/httprequest":4,"./lib/neb":5,"./lib/nvm/nvm":16,"./lib/transaction":18,"./lib/utils/crypto-utils":19,"./lib/utils/unit":20,"./lib/utils/utils":21}],"node-localstorage.js":[function(require,module,exports){ 27340/**
40234'use strict'; 27341 * Account factory method.
27342 * Create random account.
27343 * @static
27344 *
27345 * @return {Account} Instance of Account constructor.
27346 *
27347 * @example var account = Account.NewAccount();
27348 */
27349Account.NewAccount = function () {
27350 return new Account(cryptoUtils.crypto.randomBytes(32));
27351};
27352
27353/**
27354 * Address validation method.
27355 *
27356 * @static
27357 * @param {String/Hash} addr - Account address.
27358 * @param {Number} type - NormalType / ContractType
27359 *
27360 * @return {Boolean} Is address has correct format.
27361 *
27362 * @example
27363 * if ( Account.isValidAddress("n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5") ) {
27364 * // some code
27365 * };
27366 */
27367Account.isValidAddress = function (addr, type) {
27368 /*jshint maxcomplexity:10 */
27369
27370 if (utils.isString(addr)) {
27371 try {
27372 addr = Base58.decode(addr);
27373 } catch (e) {
27374 console.log("invalid address.");
27375 // if address can't be base58 decode, return false.
27376 return false;
27377 }
27378 } else if (!Buffer.isBuffer(addr)) {
27379 return false;
27380 }
27381 // address not equal to 26
27382 if (addr.length !== AddressLength) {
27383 return false;
27384 }
40235 27385
40236// go env doesn't have and need localStorage 27386 // check if address start with AddressPrefix
27387 var buff = Buffer.from(addr);
27388 if (buff.readUIntBE(0, 1) !== AddressPrefix) {
27389 return false;
27390 }
40237 27391
40238if (typeof localStorage === 'undefined') { 27392 // check if address type is NormalType or ContractType
40239 exports.localStorage = {}; 27393 var t = buff.readUIntBE(1, 1);
40240} else { 27394 if (utils.isNumber(type) && (type === NormalType || type === ContractType)) {
40241 exports.localStorage = localStorage; // jshint ignore:line 27395 if (t !== type) {
40242} 27396 return false;
27397 }
27398 } else if (t !== NormalType && t !== ContractType) {
27399 return false;
27400 }
27401 var content = addr.slice(0, 22);
27402 var checksum = addr.slice(-4);
27403 return Buffer.compare(cryptoUtils.sha3(content).slice(0, 4), checksum) === 0;
27404};
27405
27406/**
27407 * Restore account from address.
27408 * Receive addr or Account instance.
27409 * If addr is Account instance return new Account instance with same PrivateKey.
27410 *
27411 * @static
27412 * @param {(Hash|Object)} - Client address or Account instance.
27413 *
27414 * @return {Account} Instance of Account restored from address.
27415 *
27416 * @example var account = Account.fromAddress("n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5");
27417 */
27418Account.fromAddress = function (addr) {
27419 var acc = new Account();
27420 if (addr instanceof Account) {
27421 acc.setPrivateKey(addr.getPrivateKey());
27422 return acc;
27423 }
27424 if (utils.isString(addr) && this.isValidAddress(addr)) {
27425 acc.address = Base58.decode(addr);
27426 return acc;
27427 }
27428
27429 var buf = cryptoUtils.toBuffer(addr);
27430 if (this.isValidAddress(buf)) {
27431 acc.address = buf;
27432 return acc;
27433 }
27434 throw new Error("invalid address");
27435};
27436
27437/**
27438 * Restore account from public key.
27439 *
27440 * @static
27441 * @param {(String/Hash)} - Public key.
27442 *
27443 * @return {Account} Instance of Account restored from address.
27444 *
27445 * @example var account = Account.fromPubKey("f18ec04019dd131bbcfada4020b001d547244d768f144ef947577ce53a13ad690eb43e4b02a8daa3c168045cd122c0685f083e1656756ba7982721322ebe4da7");
27446 */
27447Account.fromPubKey = function (publicKey) {
27448 var acc = new Account();
27449 acc.pubKey = cryptoUtils.toBuffer(publicKey);
27450 return acc;
27451};
27452
27453Account.getNormalType = function () {
27454 return NormalType;
27455};
27456
27457Account.getContractType = function () {
27458 return ContractType;
27459};
27460
27461Account.prototype = {
27462 /**
27463 * Private Key setter.
27464 *
27465 * @param {Hash} priv - Account private key.
27466 *
27467 * @example account.setPrivateKey("ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6");
27468 */
27469 setPrivateKey: function (priv) {
27470 if (utils.isString(priv) || Buffer.isBuffer(priv)) {
27471 this.privKey = priv.length === 32 ? priv : Buffer(priv, 'hex');
27472 this.pubKey = null;
27473 this.address = null;
27474 }
27475 },
27476 /**
27477 * Private Key getter.
27478 *
27479 * @return {Buffer} Account private key.
27480 *
27481 * @example var privKey = account.getPrivateKey();
27482 * //<Buffer 5b ed 67 f9 9c b3 31 9e 0c 6f 6a 03 54 8b e3 c8 c5 2a 83 64 46 4f 88 6f> 24
27483 */
27484 getPrivateKey: function () {
27485 return this.privKey;
27486 },
27487 /**
27488 * Get Private Key in hex string format.
27489 *
27490 * @return {HexString} Account private key in String format.
27491 *
27492 * @example var privKey = account.getPrivateKeyString();
27493 * //"ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6"
27494 */
27495 getPrivateKeyString: function () {
27496 return this.getPrivateKey().toString('hex');
27497 },
27498 /**
27499 * Public Key getter.
27500 *
27501 * @return {Buffer} Account public key.
27502 *
27503 * @example var publicKey = account.getPublicKey();
27504 * //<Buffer c0 96 aa 4e 66 c7 4a 9a c7 18 31 f1 24 72 2a c1 3e b5 df 7f 97 1b 13 1d 46 a2 8a e6 81 c6 1d 96 f7 07 d0 aa e9 a7 67 436b 68 af a8 f0 96 65 17 24 29 ... >
27505 */
27506 getPublicKey: function () {
27507 if (utils.isNull(this.pubKey)) {
27508 this.pubKey = cryptoUtils.privateToPublic(this.privKey);
27509 }
27510 return this.pubKey;
27511 },
27512 /**
27513 * Get Public Key in hex string format.
27514 *
27515 * @return {HexString} Account public key in String format.
27516 *
27517 * @example var publicKey = account.getPublicKey();
27518 * //"f18ec04019dd131bbcfada4020b001d547244d768f144ef947577ce53a13ad690eb43e4b02a8daa3c168045cd122c0685f083e1656756ba7982721322ebe4da7"
27519 */
27520 getPublicKeyString: function () {
27521 return this.getPublicKey().toString('hex');
27522 },
27523 /**
27524 * Accaunt address getter.
27525 *
27526 * @return {Buffer} Account address.
27527 *
27528 * @example var publicKey = account.getAddress();
27529 * //<Buffer 7f 87 83 58 46 96 12 7d 1a c0 57 1a 42 87 c6 25 36 08 ff 32 61 36 51 7c>
27530 */
27531 getAddress: function () {
27532 if (utils.isNull(this.address)) {
27533
27534 var pubKey = this.getPublicKey();
27535 if (pubKey.length !== 64) {
27536 pubKey = cryptoUtils.secp256k1.publicKeyConvert(pubKey, false).slice(1);
27537 }
27538
27539 // The uncompressed form consists of a 0x04 (in analogy to the DER OCTET STRING tag) plus
27540 // the concatenation of the binary representation of the X coordinate plus the binary
27541 // representation of the y coordinate of the public point.
27542 pubKey = Buffer.concat([cryptoUtils.toBuffer(4), pubKey]);
27543
27544 // Only take the lower 160bits of the hash
27545 var content = cryptoUtils.sha3(pubKey);
27546 content = cryptoUtils.ripemd160(content);
27547 // content = AddressPrefix + NormalType + content(local address only use normal type)
27548 content = Buffer.concat([cryptoUtils.toBuffer(AddressPrefix), cryptoUtils.toBuffer(NormalType), content]);
27549 var checksum = cryptoUtils.sha3(content).slice(0, 4);
27550 this.address = Buffer.concat([content, checksum]);
27551 }
27552 return this.address;
27553 },
27554 /**
27555 * Get account address in hex string format.
27556 *
27557 * @return {HexString} Account address in String format.
27558 *
27559 * @example var publicKey = account.getAddressString();
27560 * //"802d529bf55d6693b3ac72c59b4a7d159da53cae5a7bf99c"
27561 */
27562 getAddressString: function () {
27563 var addr = this.getAddress();
27564 return Base58.encode(addr);
27565 },
27566 /**
27567 * Generate key buy passphrase and options.
27568 *
27569 * @param {Password} password - Provided password.
27570 * @param {KeyOptions} opts - Key options.
27571 *
27572 * @return {Key} Key Object.
27573 *
27574 * @example var key = account.toKey("passphrase");
27575 */
27576 toKey: function (password, opts) {
27577 /*jshint maxcomplexity:17 */
27578
27579 opts = opts || {};
27580 var salt = opts.salt || cryptoUtils.crypto.randomBytes(32);
27581 var iv = opts.iv || cryptoUtils.crypto.randomBytes(16);
27582 var derivedKey;
27583 var kdf = opts.kdf || 'scrypt';
27584 var kdfparams = {
27585 dklen: opts.dklen || 32,
27586 salt: salt.toString('hex')
27587 };
27588 if (kdf === 'pbkdf2') {
27589 kdfparams.c = opts.c || 262144;
27590 kdfparams.prf = 'hmac-sha256';
27591 derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), salt, kdfparams.c, kdfparams.dklen, 'sha256');
27592 } else if (kdf === 'scrypt') {
27593 kdfparams.n = opts.n || 4096;
27594 kdfparams.r = opts.r || 8;
27595 kdfparams.p = opts.p || 1;
27596 derivedKey = cryptoUtils.scrypt(new Buffer(password), salt, kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen);
27597 } else {
27598 throw new Error('Unsupported kdf');
27599 }
27600 var cipher = cryptoUtils.crypto.createCipheriv(opts.cipher || 'aes-128-ctr', derivedKey.slice(0, 16), iv);
27601 if (!cipher) {
27602 throw new Error('Unsupported cipher');
27603 }
27604 var ciphertext = Buffer.concat([cipher.update(this.privKey), cipher.final()]);
27605 // var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex')])); // KeyVersion3 deprecated
27606 var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex'), iv, new Buffer(opts.cipher || 'aes-128-ctr')]));
27607 return {
27608 version: KeyCurrentVersion,
27609 id: cryptoUtils.uuid.v4({
27610 random: opts.uuid || cryptoUtils.crypto.randomBytes(16)
27611 }),
27612 address: this.getAddressString(),
27613 crypto: {
27614 ciphertext: ciphertext.toString('hex'),
27615 cipherparams: {
27616 iv: iv.toString('hex')
27617 },
27618 cipher: opts.cipher || 'aes-128-ctr',
27619 kdf: kdf,
27620 kdfparams: kdfparams,
27621 mac: mac.toString('hex'),
27622 machash: "sha3256"
27623 }
27624 };
27625 },
27626 /**
27627 * Generate key buy passphrase and options.
27628 * Return in JSON format.
27629 *
27630 * @param {Password} password - Provided password.
27631 * @param {KeyOptions} opts - Key options.
27632 *
27633 * @return {String} JSON stringify Key.
27634 *
27635 * @example var key = account.toKeyString("passphrase");
27636 */
27637 toKeyString: function (password, opts) {
27638 return JSON.stringify(this.toKey(password, opts));
27639 },
27640 /**
27641 * Restore account from key and passphrase.
27642 *
27643 * @param {Key} input - Key Object.
27644 * @param {Password} password - Provided password.
27645 * @param {Boolean} nonStrict - Strict сase sensitivity flag.
27646 *
27647 * @return {@link Account} - Instance of Account restored from key and passphrase.
27648 */
27649 fromKey: function (input, password, nonStrict) {
27650 /*jshint maxcomplexity:10 */
27651
27652 var json = typeof input === 'object' ? input : JSON.parse(nonStrict ? input.toLowerCase() : input);
27653 if (json.version !== KeyVersion3 && json.version !== KeyCurrentVersion) {
27654 throw new Error('Not supported wallet version');
27655 }
27656 var derivedKey;
27657 var kdfparams;
27658 if (json.crypto.kdf === 'scrypt') {
27659 kdfparams = json.crypto.kdfparams;
27660 derivedKey = cryptoUtils.scrypt(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen);
27661 } else if (json.crypto.kdf === 'pbkdf2') {
27662 kdfparams = json.crypto.kdfparams;
27663 if (kdfparams.prf !== 'hmac-sha256') {
27664 throw new Error('Unsupported parameters to PBKDF2');
27665 }
27666 derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.c, kdfparams.dklen, 'sha256');
27667 } else {
27668 throw new Error('Unsupported key derivation scheme');
27669 }
27670 var ciphertext = new Buffer(json.crypto.ciphertext, 'hex');
27671 var mac;
27672
27673 if (json.version === KeyCurrentVersion) {
27674 mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext, new Buffer(json.crypto.cipherparams.iv, 'hex'), new Buffer(json.crypto.cipher)]));
27675 } else {
27676 // KeyVersion3
27677 mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext]));
27678 }
27679
27680 if (mac.toString('hex') !== json.crypto.mac) {
27681 throw new Error('Key derivation failed - possibly wrong passphrase');
27682 }
27683 var decipher = cryptoUtils.crypto.createDecipheriv(json.crypto.cipher, derivedKey.slice(0, 16), new Buffer(json.crypto.cipherparams.iv, 'hex'));
27684 var seed = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
27685 while (seed.length < 32) {
27686 var nullBuff = new Buffer([0x00]);
27687 seed = Buffer.concat([nullBuff, seed]);
27688 }
27689 this.setPrivateKey(seed);
27690 return this;
27691 }
27692
27693};
27694
27695module.exports = Account;
40243 27696
40244},{}]},{},[]); 27697},{"./utils/crypto-utils.js":1,"./utils/utils.js":2,"bs58":51,"safe-buffer":156}]},{},[]);
diff --git a/tests/spec/tests.js b/tests/spec/tests.js
index e0b1161..364349c 100644
--- a/tests/spec/tests.js
+++ b/tests/spec/tests.js
@@ -991,6 +991,13 @@ it('Allows selection of Navcoin', function(done) {
991 }; 991 };
992 testNetwork(done, params); 992 testNetwork(done, params);
993}); 993});
994it('Allows selection of Nebulas', function(done) {
995 var params = {
996 selectText: "NAS - Nebulas",
997 firstAddress: "n1PbK61DGBfDoDusLw621G6sVSMfLLHdfnm",
998 };
999 testNetwork(done, params);
1000});
994it('Allows selection of Neoscoin', function(done) { 1001it('Allows selection of Neoscoin', function(done) {
995 var params = { 1002 var params = {
996 selectText: "NEOS - Neoscoin", 1003 selectText: "NEOS - Neoscoin",