Skip to content

Instantly share code, notes, and snippets.

@evias
Last active December 27, 2018 04:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evias/8ce4177495bd6209f3d1b7be7840f1bc to your computer and use it in GitHub Desktop.
Save evias/8ce4177495bd6209f3d1b7be7840f1bc to your computer and use it in GitHub Desktop.
nem-sdk-v1.6.2.js
This file has been truncated, but you can view the full file.
require=(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){
'use strict';
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _headers = require('./headers');
var _headers2 = _interopRequireDefault(_headers);
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Gets the AccountMetaDataPair of an account.
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
*
* @return {object} - An [AccountMetaDataPair]{@link http://bob.nem.ninja/docs/#accountMetaDataPair} object
*/
var data = function data(endpoint, address) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/get',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'address': address }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets the AccountMetaDataPair of an account with a public Key.
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} publicKey - An account public key
*
* @return {object} - An [AccountMetaDataPair]{@link http://bob.nem.ninja/docs/#accountMetaDataPair} object
*/
var dataFromPublicKey = function dataFromPublicKey(endpoint, publicKey) {
// Configure the public key request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/get/from-public-key',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'publicKey': publicKey }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets an array of harvest info objects for an account.
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
*
* @return {array} - An array of [HarvestInfo]{@link http://bob.nem.ninja/docs/#harvestInfo} objects
*/
var harvestedBlocks = function harvestedBlocks(endpoint, address) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/harvests',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'address': address }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets an array of TransactionMetaDataPair objects where the recipient has the address given as parameter to the request.
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
* @param {string} txHash - The 256 bit sha3 hash of the transaction up to which transactions are returned. (optional)
* @param {string} txId - The transaction id up to which transactions are returned. (optional)
*
* @return {array} - An array of [TransactionMetaDataPair]{@link http://bob.nem.ninja/docs/#transactionMetaDataPair} objects
*/
var incomingTransactions = function incomingTransactions(endpoint, address, txHash, txId) {
// Arrange
var params = { 'address': address };
if (txHash) params['hash'] = txHash;
if (txId) params['id'] = txId;
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/transfers/incoming',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: params
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets an array of TransactionMetaDataPair objects where the sender has the address given as parameter to the request.
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
* @param {string} txHash - The 256 bit sha3 hash of the transaction up to which transactions are returned. (optional)
* @param {string} txId - The transaction id up to which transactions are returned. (optional)
*
* @return {array} - An array of [TransactionMetaDataPair]{@link http://bob.nem.ninja/docs/#transactionMetaDataPair} objects
*/
var outgoingTransactions = function outgoingTransactions(endpoint, address, txHash, txId) {
// Arrange
var params = { 'address': address };
if (txHash) params['hash'] = txHash;
if (txId) params['id'] = txId;
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/transfers/outgoing',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: params
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets the array of transactions for which an account is the sender or receiver and which have not yet been included in a block.
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
*
* @return {array} - An array of [UnconfirmedTransactionMetaDataPair]{@link http://bob.nem.ninja/docs/#unconfirmedTransactionMetaDataPair} objects
*/
var unconfirmedTransactions = function unconfirmedTransactions(endpoint, address) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/unconfirmedTransactions',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'address': address }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets information about the maximum number of allowed harvesters and how many harvesters are already using the node
*
* @param {object} endpoint - An NIS endpoint object
*
* @return {object} - An [UnlockInfo]{@link http://bob.nem.ninja/docs/#retrieving-the-unlock-info} object
*/
var unlockInfo = function unlockInfo(endpoint) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/unlocked/info',
method: 'POST',
headers: _headers2.default.urlEncoded
// Send the request
};return (0, _send2.default)(options);
};
/**
* Unlocks an account (starts harvesting).
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} privateKey - A delegated account private key
*
* @return - Nothing
*/
var startHarvesting = function startHarvesting(endpoint, privateKey) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/unlock',
method: 'POST',
json: true,
body: { 'value': privateKey }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Locks an account (stops harvesting).
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} privateKey - A delegated account private key
*
* @return - Nothing
*/
var stopHarvesting = function stopHarvesting(endpoint, privateKey) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/lock',
method: 'POST',
json: true,
body: { 'value': privateKey }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets the AccountMetaDataPair of the account for which the given account is the delegate account
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
*
* @return {object} - An [AccountMetaDataPair]{@link http://bob.nem.ninja/docs/#accountMetaDataPair} object
*/
var forwarded = function forwarded(endpoint, address) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/get/forwarded',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'address': address }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets namespaces that an account owns
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
* @param {string} parent - The namespace parent (optional)
*
* @return {object} - An array of [NamespaceMetaDataPair]{@link http://bob.nem.ninja/docs/#namespaceMetaDataPair} objects
*/
var namespacesOwned = function namespacesOwned(endpoint, address, parent) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/namespace/page',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'address': address, 'parent': parent || "" }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets mosaic definitions that an account has created
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
* @param {string} parent - The namespace parent (optional)
*
* @return {object} - An array of [MosaicDefinition]{@link http://bob.nem.ninja/docs/#mosaicDefinition} objects
*/
var mosaicDefinitionsCreated = function mosaicDefinitionsCreated(endpoint, address, parent) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/mosaic/definition/page',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'address': address, 'parent': parent || "" }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets mosaic definitions that an account owns
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
*
* @return {array} - An array of [MosaicDefinition]{@link http://bob.nem.ninja/docs/#mosaicDefinition} objects
*/
var mosaicDefinitions = function mosaicDefinitions(endpoint, address) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/mosaic/owned/definition',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'address': address }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets mosaics that an account owns
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
*
* @return {array} - An array of [Mosaic]{@link http://bob.nem.ninja/docs/#mosaic} objects
*/
var mosaicsOwned = function mosaicsOwned(endpoint, address) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/mosaic/owned',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'address': address }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets all transactions of an account
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
* @param {string} txHash - The 256 bit sha3 hash of the transaction up to which transactions are returned. (optional)
* @param {string} txId - The transaction id up to which transactions are returned. (optional)
*
* @return {array} - An array of [TransactionMetaDataPair]{@link http://bob.nem.ninja/docs/#transactionMetaDataPair} objects
*/
var allTransactions = function allTransactions(endpoint, address, txHash, txId) {
// Arrange
var params = { 'address': address };
if (txHash) params['hash'] = txHash;
if (txId) params['id'] = txId;
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/account/transfers/all',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: params
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
data: data,
dataFromPublicKey: dataFromPublicKey,
unlockInfo: unlockInfo,
forwarded: forwarded,
mosaics: {
owned: mosaicsOwned,
definitions: mosaicDefinitionsCreated,
allDefinitions: mosaicDefinitions
},
namespaces: {
owned: namespacesOwned
},
harvesting: {
blocks: harvestedBlocks,
start: startHarvesting,
stop: stopHarvesting
},
transactions: {
incoming: incomingTransactions,
outgoing: outgoingTransactions,
unconfirmed: unconfirmedTransactions,
all: allTransactions
}
};
},{"../../utils/helpers":51,"./headers":5,"./send":10}],2:[function(require,module,exports){
'use strict';
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
var _headers = require('./headers');
var _headers2 = _interopRequireDefault(_headers);
var _nodes = require('../../model/nodes');
var _nodes2 = _interopRequireDefault(_nodes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Audit an apostille file
*
* @param {string} publicKey - The signer public key
* @param {string} data - The file data of audited file
* @param {string} signedData - The signed data into the apostille transaction message
*
* @return {boolean} - True if valid, false otherwise
*/
var audit = function audit(publicKey, data, signedData) {
// Configure the request
var options = {
url: _nodes2.default.apostilleAuditServer,
method: 'POST',
headers: _headers2.default.urlEncoded,
qs: { 'publicKey': publicKey, 'data': data, 'signedData': signedData }
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
audit: audit
};
},{"../../model/nodes":27,"./headers":5,"./send":10}],3:[function(require,module,exports){
'use strict';
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Gets the current height of the block chain.
*
* @param {object} endpoint - An NIS endpoint object
*
* @return {object} - A [BlockHeight]{@link http://bob.nem.ninja/docs/#block-chain-height} object
*/
var height = function height(endpoint) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/chain/height',
method: 'GET'
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets the current last block of the chain.
*
* @param {object} endpoint - An NIS endpoint object
*
* @return {object} -
*/
var lastBlock = function lastBlock(endpoint) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/chain/last-block',
method: 'GET'
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets network time (in ms)
*
* @param {object} endpoint - An NIS endpoint object
*
* @return {object} - A [communicationTimeStamps]{@link http://bob.nem.ninja/docs/#communicationTimeStamps} object
*/
var time = function time(endpoint) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/time-sync/network-time',
method: 'GET'
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
height: height,
lastBlock: lastBlock,
time: time
};
},{"../../utils/helpers":51,"./send":10}],4:[function(require,module,exports){
'use strict';
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Determines if NIS is up and responsive.
*
* @param {object} endpoint - An NIS endpoint object
*
* @return {object} - A [NemRequestResult]{@link http://bob.nem.ninja/docs/#nemRequestResult} object
*/
var heartbeat = function heartbeat(endpoint) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/heartbeat',
method: 'GET'
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
heartbeat: heartbeat
};
},{"../../utils/helpers":51,"./send":10}],5:[function(require,module,exports){
(function (Buffer){
'use strict';
/**
* An url encoded header
*
* @type {object}
*/
var urlEncoded = {
'Content-Type': 'application/x-www-form-urlencoded'
/**
* Create an application/json header
*
* @param {data} - A json string
*
* @return {object} - An application/json header with content length
*/
};var json = function json(data) {
return {
"Content-Type": "application/json",
"Content-Length": Buffer.from(data).byteLength
};
};
module.exports = {
urlEncoded: urlEncoded,
json: json
};
}).call(this,require("buffer").Buffer)
},{"buffer":157}],6:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _account = require('./account');
var _account2 = _interopRequireDefault(_account);
var _apostille = require('./apostille');
var _apostille2 = _interopRequireDefault(_apostille);
var _chain = require('./chain');
var _chain2 = _interopRequireDefault(_chain);
var _endpoint = require('./endpoint');
var _endpoint2 = _interopRequireDefault(_endpoint);
var _market = require('./market');
var _market2 = _interopRequireDefault(_market);
var _mosaic = require('./mosaic');
var _mosaic2 = _interopRequireDefault(_mosaic);
var _namespace = require('./namespace');
var _namespace2 = _interopRequireDefault(_namespace);
var _supernodes = require('./supernodes');
var _supernodes2 = _interopRequireDefault(_supernodes);
var _transaction = require('./transaction');
var _transaction2 = _interopRequireDefault(_transaction);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
account: _account2.default,
apostille: _apostille2.default,
chain: _chain2.default,
endpoint: _endpoint2.default,
market: _market2.default,
mosaic: _mosaic2.default,
namespace: _namespace2.default,
supernodes: _supernodes2.default,
transaction: _transaction2.default
};
},{"./account":1,"./apostille":2,"./chain":3,"./endpoint":4,"./market":7,"./mosaic":8,"./namespace":9,"./supernodes":11,"./transaction":12}],7:[function(require,module,exports){
'use strict';
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
var _headers = require('./headers');
var _headers2 = _interopRequireDefault(_headers);
var _nodes = require('../../model/nodes');
var _nodes2 = _interopRequireDefault(_nodes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Gets market information from Poloniex api
*
* @return {object} - A MarketInfo object
*/
var xem = function xem() {
// Configure the request
var options = {
url: _nodes2.default.marketInfo,
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'command': 'returnTicker' }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets BTC price from blockchain.info API
*
* @return {object} - A MarketInfo object
*/
var btc = function btc() {
// Configure the request
var options = {
url: _nodes2.default.btcPrice,
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'cors': true }
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
xem: xem,
btc: btc
};
},{"../../model/nodes":27,"./headers":5,"./send":10}],8:[function(require,module,exports){
'use strict';
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
var _headers = require('./headers');
var _headers2 = _interopRequireDefault(_headers);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Gets the current supply of a mosaic
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} id - A mosaic id
*
* @return {object} - A mosaicSupplyInfo object
*/
var supply = function supply(endpoint, id) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/mosaic/supply',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'mosaicId': id }
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
supply: supply
};
},{"../../utils/helpers":51,"./headers":5,"./send":10}],9:[function(require,module,exports){
'use strict';
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
var _headers = require('./headers');
var _headers2 = _interopRequireDefault(_headers);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Gets root namespaces.
*
* @param {object} endpoint - An NIS endpoint object
* @param {number} id - The namespace id up to which root namespaces are returned (optional)
*
* @return {object} - An array of [NamespaceMetaDataPair]{@link http://bob.nem.ninja/docs/#namespaceMetaDataPair} objects
*/
var roots = function roots(endpoint, id) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/namespace/root/page',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: undefined === id ? { 'pageSize': 100 } : { 'id': id, 'pageSize': 100 }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets mosaic definitions of a namespace
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} id - A namespace id
*
* @return {object} - An array of [MosaicDefinition]{@link http://bob.nem.ninja/docs/#mosaicDefinition} objects
*/
var mosaicDefinitions = function mosaicDefinitions(endpoint, id) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/namespace/mosaic/definition/page',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'namespace': id }
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets the namespace with given id.
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} id - A namespace id
*
* @return {object} - A [NamespaceInfo]{@link http://bob.nem.ninja/docs/#namespace} object
*/
var info = function info(endpoint, id) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/namespace',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'namespace': id }
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
roots: roots,
mosaicDefinitions: mosaicDefinitions,
info: info
};
},{"../../utils/helpers":51,"./headers":5,"./send":10}],10:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _request = require('request');
var _request2 = _interopRequireDefault(_request);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Send a request
*
* @param {object} options - The options of the request
*
* @return {Promise} - A resolved promise with the requested data or a rejection with error data
*/
var send = function send(options) {
return new Promise(function (resolve, reject) {
(0, _request2.default)(options, function (error, response, body) {
var data = void 0;
if (_helpers2.default.isJSON(body)) {
data = JSON.parse(body);
} else {
data = body;
}
if (!error && response.statusCode == 200) {
resolve(data);
} else {
if (!error) {
reject({ "code": 0, "data": data });
} else {
reject({ "code": -1, "data": error });
}
}
});
});
};
exports.default = send;
},{"../../utils/helpers":51,"request":367}],11:[function(require,module,exports){
'use strict';
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
var _nodes = require('../../model/nodes');
var _nodes2 = _interopRequireDefault(_nodes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Gets all nodes of the node reward program
*
* @return {array} - An array of SuperNodeInfo objects
*/
var all = function all() {
// Configure the request
var options = {
url: _nodes2.default.supernodes,
method: 'GET'
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets the nearest supernodes
*
* @param {object} coords - A coordinates object: https://www.w3schools.com/html/html5_geolocation.asp
*
* @return {array} - An array of supernodeInfo objects
*/
var nearest = function nearest(coords) {
var obj = {
"latitude": coords.latitude,
"longitude": coords.longitude,
"numNodes": 5
// Configure the request
};var options = {
url: 'http://199.217.113.179:7782/nodes/nearest',
method: 'POST',
json: true,
body: obj
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets the all supernodes by status
*
* @param {number} status - 0 for all nodes, 1 for active nodes, 2 for inactive nodes
*
* @return {array} - An array of supernodeInfo objects
*/
var get = function get(status) {
var obj = {
"status": undefined === status ? 1 : status
// Configure the request
};var options = {
url: 'http://199.217.113.179:7782/nodes',
method: 'POST',
json: true,
body: obj
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
all: all,
nearest: nearest,
get: get
};
},{"../../model/nodes":27,"./send":10}],12:[function(require,module,exports){
'use strict';
var _send = require('./send');
var _send2 = _interopRequireDefault(_send);
var _headers = require('./headers');
var _headers2 = _interopRequireDefault(_headers);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Broadcast a transaction to the NEM network
*
* @param {object} endpoint - An NIS endpoint object
* @param {object} obj - A RequestAnnounce object
*
* @return {object} - A [NemAnnounceResult]{@link http://bob.nem.ninja/docs/#nemAnnounceResult} object
*/
var announce = function announce(endpoint, serializedTransaction) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/transaction/announce',
method: 'POST',
headers: _headers2.default.json(serializedTransaction),
json: JSON.parse(serializedTransaction)
// Send the request
};return (0, _send2.default)(options);
};
/**
* Gets a TransactionMetaDataPair object from the chain using it's hash
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} txHash - A transaction hash
*
* @return {object} - A [TransactionMetaDataPair]{@link http://bob.nem.ninja/docs/#transactionMetaDataPair} object
*/
var byHash = function byHash(endpoint, txHash) {
// Configure the request
var options = {
url: _helpers2.default.formatEndpoint(endpoint) + '/transaction/get',
method: 'GET',
headers: _headers2.default.urlEncoded,
qs: { 'hash': txHash }
// Send the request
};return (0, _send2.default)(options);
};
module.exports = {
announce: announce,
byHash: byHash
};
},{"../../utils/helpers":51,"./headers":5,"./send":10}],13:[function(require,module,exports){
'use strict';
var _sockjs = require('../../external/sockjs-0.3.4');
var _sockjsClient = require('sockjs-client');
var _sockjsClient2 = _interopRequireDefault(_sockjsClient);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Check if socket is open
*
* @param {object} connector - A connector object
*
* @return {boolean} - True if open, false otherwise
*/
var checkReadyState = function checkReadyState(connector) {
var self = connector;
if (_sockjs.SockJS ? self.socket.readyState !== _sockjs.SockJS.OPEN : self.socket.readyState !== _sockjsClient2.default.OPEN) {
return false;
}
return true;
};
/**
* Request the account data of the address in the given connector
* You can optionally use an address directly to request data for a specific account
*
* @param {object} connector - A connector object
* @param {string} address - A NEM account address (optional)
*
* @return the response in the subscription callback
*/
var requestAccountData = function requestAccountData(connector, address) {
var self = connector;
// If not ready, wait a bit more...
if (!checkReadyState(connector)) {
self.timeoutHandle = setTimeout(function () {
requestData(connector, address);
}, 100);
} else {
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.send("/w/api/account/get", {}, "{'account':'" + _address + "'}");
}
};
/**
* Request the recent transactions of the address in the given connector
* You can optionally use an address directly to request data for a specific account
*
* @param {object} connector - A connector object
* @param {string} address - A NEM account address (optional)
*
* @return the response in the subscription callback
*/
var requestRecentTransactions = function requestRecentTransactions(connector, address) {
var self = connector;
// If not ready, wait a bit more...
if (!checkReadyState(connector)) {
self.timeoutHandle = setTimeout(function () {
requestRecentTransactions(connector, address);
}, 100);
} else {
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.send("/w/api/account/transfers/all", {}, "{'account':'" + _address + "'}");
}
};
/**
* Request the owned mosaic definitions of the address in the given connector
* You can optionally use an address directly to request data for a specific account
*
* @param {object} connector - A connector object
* @param {string} address - A NEM account address (optional)
*
* @return the response in the subscription callback
*/
var requestMosaicDefinitions = function requestMosaicDefinitions(connector, address) {
var self = connector;
// If not ready, wait a bit more...
if (!checkReadyState(connector)) {
self.timeoutHandle = setTimeout(function () {
requestRecentTransactions(connector, address);
}, 100);
} else {
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.send("/w/api/account/mosaic/owned/definition", {}, "{'account':'" + _address + "'}");
}
};
/**
* Request the owned mosaics of the address in the given connector
* You can optionally use an address directly to request data for a specific account
*
* @param {object} connector - A connector object
* @param {string} address - A NEM account address (optional)
*
* @return the response in the subscription callback
*/
var requestMosaics = function requestMosaics(connector, address) {
var self = connector;
// If not ready, wait a bit more...
if (!checkReadyState(connector)) {
self.timeoutHandle = setTimeout(function () {
requestRecentTransactions(connector, address);
}, 100);
} else {
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.send("/w/api/account/mosaic/owned", {}, "{'account':'" + _address + "'}");
}
};
/**
* Request the owned namespaces of the address in the given connector
* You can optionally use an address directly to request data for a specific account
*
* @param {object} connector - A connector object
* @param {string} address - A NEM account address (optional)
*
* @return the response in the subscription callback
*/
var requestNamespaces = function requestNamespaces(connector, address) {
var self = connector;
// If not ready, wait a bit more...
if (!checkReadyState(connector)) {
self.timeoutHandle = setTimeout(function () {
requestRecentTransactions(connector, address);
}, 100);
} else {
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.send("/w/api/account/namespace/owned", {}, "{'account':'" + _address + "'}");
}
};
/**
* Subscribe to the account data channel for the address in the given connector
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
* @param {string} address - A NEM account address (optional)
*
* @return the received data in the callback
*/
var subscribeAccountData = function subscribeAccountData(connector, callback, address) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.subscribe('/account/' + _address, function (data) {
callback(JSON.parse(data.body));
});
};
/**
* Subscribe to the recent transactions channel for the address in the given connector
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
* @param {string} address - A NEM account address (optional)
*
* @return the received data in the callback
*/
var subscribeRecentTransactions = function subscribeRecentTransactions(connector, callback, address) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.subscribe('/recenttransactions/' + _address, function (data) {
callback(JSON.parse(data.body));
});
};
/**
* Subscribe to the unconfirmed transactions channel for the address in the given connector
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
* @param {string} address - A NEM account address (optional)
*
* @return the received data in the callback
*/
var subscribeUnconfirmedTransactions = function subscribeUnconfirmedTransactions(connector, callback, address) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.subscribe('/unconfirmed/' + _address, function (data) {
callback(JSON.parse(data.body));
});
};
/**
* Subscribe to the confirmed transactions channel for the address in the given connector
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
* @param {string} address - A NEM account address (optional)
*
* @return the received data in the callback
*/
var subscribeConfirmedTransactions = function subscribeConfirmedTransactions(connector, callback, address) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.subscribe('/transactions/' + _address, function (data) {
callback(JSON.parse(data.body));
});
};
/**
* Subscribe to the mosaic definitions channel for the address in the given connector
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
* @param {string} address - A NEM account address (optional)
*
* @return the received data in the callback
*/
var subscribeMosaicDefinitions = function subscribeMosaicDefinitions(connector, callback, address) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.subscribe('/account/mosaic/owned/definition/' + _address, function (data) {
callback(JSON.parse(data.body));
});
};
/**
* Subscribe to the owned mosaics channel for the address in the given connector
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
* @param {string} address - A NEM account address (optional)
*
* @return the received data in the callback
*/
var subscribeMosaics = function subscribeMosaics(connector, callback, address) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.subscribe('/account/mosaic/owned/' + _address, function (data) {
callback(JSON.parse(data.body), _address);
});
};
/**
* Subscribe to the owned namespaces channel for the address in the given connector
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
* @param {string} address - A NEM account address (optional)
*
* @return the received data in the callback
*/
var subscribeNamespaces = function subscribeNamespaces(connector, callback, address) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
// Use address if provided
var _address = undefined !== address ? address.replace(/-/g, "").toUpperCase() : self.address;
self.stompClient.subscribe('/account/namespace/owned/' + _address, function (data) {
callback(JSON.parse(data.body), _address);
});
};
module.exports = {
requests: {
data: requestAccountData,
transactions: {
recent: requestRecentTransactions
},
mosaics: {
owned: requestMosaics,
definitions: requestMosaicDefinitions
},
namespaces: {
owned: requestNamespaces
}
},
subscribe: {
data: subscribeAccountData,
transactions: {
recent: subscribeRecentTransactions,
confirmed: subscribeConfirmedTransactions,
unconfirmed: subscribeUnconfirmedTransactions
},
mosaics: {
owned: subscribeMosaics,
definitions: subscribeMosaicDefinitions
},
namespaces: {
owned: subscribeNamespaces
}
}
};
},{"../../external/sockjs-0.3.4":21,"sockjs-client":390}],14:[function(require,module,exports){
'use strict';
var _sockjs = require('../../external/sockjs-0.3.4');
var _sockjsClient = require('sockjs-client');
var _sockjsClient2 = _interopRequireDefault(_sockjsClient);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Check if socket is open
*
* @param {object} connector - A connector object
*
* @return {boolean} - True if open, false otherwise
*/
var checkReadyState = function checkReadyState(connector) {
var self = connector;
if (_sockjs.SockJS ? self.socket.readyState !== _sockjs.SockJS.OPEN : self.socket.readyState !== _sockjsClient2.default.OPEN) {
return false;
}
return true;
};
/**
* Subscribe to the new blocks channel
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
*
* @return the received data in the callback
*/
var subscribeNewBlocks = function subscribeNewBlocks(connector, callback) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
self.stompClient.subscribe('/blocks', function (data) {
callback(JSON.parse(data.body));
});
};
/**
* Subscribe to the new height channel
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
*
* @return the received data in the callback
*/
var subscribeNewHeight = function subscribeNewHeight(connector, callback) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
self.stompClient.subscribe('/blocks/new', function (data) {
callback(JSON.parse(data.body));
});
};
module.exports = {
requests: {},
subscribe: {
height: subscribeNewHeight,
blocks: subscribeNewBlocks
}
};
},{"../../external/sockjs-0.3.4":21,"sockjs-client":390}],15:[function(require,module,exports){
'use strict';
var _sockjs = require('../../external/sockjs-0.3.4');
var _sockjsClient = require('sockjs-client');
var _sockjsClient2 = _interopRequireDefault(_sockjsClient);
var _stomp = require('../../external/stomp');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Create a connector object
*
* @param {object} endpoint - An NIS endpoint object
* @param {string} address - An account address
*
* @return {object} - A connector object
*/
var create = function create(endpoint, address) {
return {
endpoint: endpoint,
address: address.replace(/-/g, "").toUpperCase(),
socket: undefined,
stompClient: undefined,
connect: connect,
close: close
};
};
/**
* Tries to establish a connection.
*
* @return {promise} - A resolved or rejected promise
*/
var connect = function connect() {
var _this = this;
return new Promise(function (resolve, reject) {
var self = _this;
if (!_sockjs.SockJS) self.socket = new _sockjsClient2.default(self.endpoint.host + ':' + self.endpoint.port + '/w/messages');else self.socket = new _sockjs.SockJS(self.endpoint.host + ':' + self.endpoint.port + '/w/messages');
self.stompClient = _stomp.Stomp.over(self.socket);
self.stompClient.debug = false;
self.stompClient.connect({}, function (frame) {
resolve(true);
}, function (err) {
reject("Connection failed!");
});
});
};
/**
* Close a connection
*/
var close = function close() {
var self = this;
console.log("Connection to " + self.endpoint.host + " must be closed now.");
self.socket.close();
self.socket.onclose = function (e) {
console.log(e);
};
};
module.exports = {
create: create
};
},{"../../external/sockjs-0.3.4":21,"../../external/stomp":22,"sockjs-client":390}],16:[function(require,module,exports){
'use strict';
var _sockjs = require('../../external/sockjs-0.3.4');
var _sockjsClient = require('sockjs-client');
var _sockjsClient2 = _interopRequireDefault(_sockjsClient);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Check if socket is open
*
* @param {object} connector - A connector object
*
* @return {boolean} - True if open, false otherwise
*/
var checkReadyState = function checkReadyState(connector) {
var self = connector;
if (_sockjs.SockJS ? self.socket.readyState !== _sockjs.SockJS.OPEN : self.socket.readyState !== _sockjsClient2.default.OPEN) {
return false;
}
return true;
};
/**
* Subscribe to errors channel
*
* @param {object} connector - A connector object
* @param {function} callback - A callback function where data will be received
*
* @return the received data in the callback
*/
var subscribe = function subscribe(connector, callback) {
var self = connector;
if (!checkReadyState(connector)) {
return false;
}
self.stompClient.subscribe('/errors', function (data) {
callback(JSON.parse(data.body));
});
};
module.exports = {
subscribe: subscribe
};
},{"../../external/sockjs-0.3.4":21,"sockjs-client":390}],17:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _connector = require('./connector');
var _connector2 = _interopRequireDefault(_connector);
var _account = require('./account');
var _account2 = _interopRequireDefault(_account);
var _chain = require('./chain');
var _chain2 = _interopRequireDefault(_chain);
var _errors = require('./errors');
var _errors2 = _interopRequireDefault(_errors);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
connector: _connector2.default,
requests: {
account: _account2.default.requests,
chain: _chain2.default.requests
},
subscribe: {
account: _account2.default.subscribe,
chain: _chain2.default.subscribe,
errors: _errors2.default.subscribe
}
};
},{"./account":13,"./chain":14,"./connector":15,"./errors":16}],18:[function(require,module,exports){
'use strict';
var _keyPair = require('./keyPair');
var _keyPair2 = _interopRequireDefault(_keyPair);
var _convert = require('../utils/convert');
var _convert2 = _interopRequireDefault(_convert);
var _address = require('../model/address');
var _address2 = _interopRequireDefault(_address);
var _naclFast = require('../external/nacl-fast');
var _naclFast2 = _interopRequireDefault(_naclFast);
var _network = require('../model/network');
var _network2 = _interopRequireDefault(_network);
var _cryptoJs = require('crypto-js');
var _cryptoJs2 = _interopRequireDefault(_cryptoJs);
var _helpers = require('../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Encrypt a private key for mobile apps (AES_PBKF2)
*
* @param {string} password - A wallet password
* @param {string} privateKey - An account private key
*
* @return {object} - The encrypted data
*/
var toMobileKey = function toMobileKey(password, privateKey) {
// Errors
if (!password || !privateKey) throw new Error('Missing argument !');
if (!_helpers2.default.isPrivateKeyValid(privateKey)) throw new Error('Private key is not valid !');
// Processing
var salt = _cryptoJs2.default.lib.WordArray.random(256 / 8);
var key = _cryptoJs2.default.PBKDF2(password, salt, {
keySize: 256 / 32,
iterations: 2000
});
var iv = _naclFast2.default.randomBytes(16);
var encIv = {
iv: _convert2.default.ua2words(iv, 16)
};
var encrypted = _cryptoJs2.default.AES.encrypt(_cryptoJs2.default.enc.Hex.parse(privateKey), key, encIv);
// Result
return {
encrypted: _convert2.default.ua2hex(iv) + encrypted.ciphertext,
salt: salt.toString()
};
};
/**
* Derive a private key from a password using count iterations of SHA3-256
*
* @param {string} password - A wallet password
* @param {number} count - A number of iterations above 0
*
* @return {object} - The derived private key
*/
var derivePassSha = function derivePassSha(password, count) {
// Errors
if (!password) throw new Error('Missing argument !');
if (!count || count <= 0) throw new Error('Please provide a count number above 0');
// Processing
var data = password;
console.time('sha3^n generation time');
for (var i = 0; i < count; ++i) {
data = _cryptoJs2.default.SHA3(data, {
outputLength: 256
});
}
console.timeEnd('sha3^n generation time');
// Result
return {
'priv': _cryptoJs2.default.enc.Hex.stringify(data)
};
};
/**
* Reveal the private key of an account or derive it from the wallet password
*
* @param {object} common- An object containing password and privateKey field
* @param {object} walletAccount - A wallet account object
* @param {string} algo - A wallet algorithm
*
* @return {object|boolean} - The account private key in and object or false
*/
var passwordToPrivatekey = function passwordToPrivatekey(common, walletAccount, algo) {
// Errors
if (!common || !walletAccount || !algo) throw new Error('Missing argument !');
var r = undefined;
if (algo === "trezor") {
// HW wallet
r = { 'priv': '' };
common.isHW = true;
} else if (!common.password) {
throw new Error('Missing argument !');
}
// Processing
if (algo === "pass:6k") {
// Brain wallets
if (!walletAccount.encrypted && !walletAccount.iv) {
// Account private key is generated simply using a passphrase so it has no encrypted and iv
r = derivePassSha(common.password, 6000);
} else if (!walletAccount.encrypted || !walletAccount.iv) {
// Else if one is missing there is a problem
//console.log("Account might be compromised, missing encrypted or iv");
return false;
} else {
// Else child accounts have encrypted and iv so we decrypt
var pass = derivePassSha(common.password, 20);
var obj = {
ciphertext: _cryptoJs2.default.enc.Hex.parse(walletAccount.encrypted),
iv: _convert2.default.hex2ua(walletAccount.iv),
key: _convert2.default.hex2ua(pass.priv)
};
var d = decrypt(obj);
r = { 'priv': d };
}
} else if (algo === "pass:bip32") {
// Wallets from PRNG
var _pass = derivePassSha(common.password, 20);
var _obj = {
ciphertext: _cryptoJs2.default.enc.Hex.parse(walletAccount.encrypted),
iv: _convert2.default.hex2ua(walletAccount.iv),
key: _convert2.default.hex2ua(_pass.priv)
};
var _d = decrypt(_obj);
r = { 'priv': _d };
} else if (algo === "pass:enc") {
// Private Key wallets
var _pass2 = derivePassSha(common.password, 20);
var _obj2 = {
ciphertext: _cryptoJs2.default.enc.Hex.parse(walletAccount.encrypted),
iv: _convert2.default.hex2ua(walletAccount.iv),
key: _convert2.default.hex2ua(_pass2.priv)
};
var _d2 = decrypt(_obj2);
r = { 'priv': _d2 };
} else if (!r) {
//console.log("Unknown wallet encryption method");
return false;
}
// Result
common.privateKey = r.priv;
return true;
};
/**
* Check if a private key correspond to an account address
*
* @param {string} priv - An account private key
* @param {number} network - A network id
* @param {string} _expectedAddress - The expected NEM address
*
* @return {boolean} - True if valid, false otherwise
*/
var checkAddress = function checkAddress(priv, network, _expectedAddress) {
// Errors
if (!priv || !network || !_expectedAddress) throw new Error('Missing argument !');
if (!_helpers2.default.isPrivateKeyValid(priv)) throw new Error('Private key is not valid !');
//Processing
var expectedAddress = _expectedAddress.toUpperCase().replace(/-/g, '');
var kp = _keyPair2.default.create(priv);
var address = _address2.default.toAddress(kp.publicKey.toString(), network);
// Result
return address === expectedAddress;
};
function hashfunc(dest, data, dataLength) {
var convertedData = _convert2.default.ua2words(data, dataLength);
var hash = _cryptoJs2.default.SHA3(convertedData, {
outputLength: 512
});
_convert2.default.words2ua(dest, hash);
}
function key_derive(shared, salt, sk, pk) {
_naclFast2.default.lowlevel.crypto_shared_key_hash(shared, pk, sk, hashfunc);
for (var i = 0; i < salt.length; i++) {
shared[i] ^= salt[i];
}
var hash = _cryptoJs2.default.SHA3(_convert2.default.ua2words(shared, 32), {
outputLength: 256
});
return hash;
}
/**
* Generate a random key
*
* @return {Uint8Array} - A random key
*/
var randomKey = function randomKey() {
var rkey = _naclFast2.default.randomBytes(32);
return rkey;
};
/**
* Encrypt hex data using a key
*
* @param {string} data - An hex string
* @param {Uint8Array} key - An Uint8Array key
*
* @return {object} - The encrypted data
*/
var encrypt = function encrypt(data, key) {
// Errors
if (!data || !key) throw new Error('Missing argument !');
// Processing
var iv = _naclFast2.default.randomBytes(16);
var encKey = _convert2.default.ua2words(key, 32);
var encIv = {
iv: _convert2.default.ua2words(iv, 16)
};
var encrypted = _cryptoJs2.default.AES.encrypt(_cryptoJs2.default.enc.Hex.parse(data), encKey, encIv);
// Result
return {
ciphertext: encrypted.ciphertext,
iv: iv,
key: key
};
};
/**
* Decrypt data
*
* @param {object} data - An encrypted data object
*
* @return {string} - The decrypted hex string
*/
var decrypt = function decrypt(data) {
// Errors
if (!data) throw new Error('Missing argument !');
// Processing
var encKey = _convert2.default.ua2words(data.key, 32);
var encIv = {
iv: _convert2.default.ua2words(data.iv, 16)
};
// Result
return _cryptoJs2.default.enc.Hex.stringify(_cryptoJs2.default.AES.decrypt(data, encKey, encIv));
};
/**
* Encode a private key using a password
*
* @param {string} privateKey - An hex private key
* @param {string} password - A password
*
* @return {object} - The encoded data
*/
var encodePrivKey = function encodePrivKey(privateKey, password) {
// Errors
if (!privateKey || !password) throw new Error('Missing argument !');
if (!_helpers2.default.isPrivateKeyValid(privateKey)) throw new Error('Private key is not valid !');
// Processing
var pass = derivePassSha(password, 20);
var r = encrypt(privateKey, _convert2.default.hex2ua(pass.priv));
// Result
return {
ciphertext: _cryptoJs2.default.enc.Hex.stringify(r.ciphertext),
iv: _convert2.default.ua2hex(r.iv)
};
};
/***
* Encode a message, separated from encode() to help testing
*
* @param {string} senderPriv - A sender private key
* @param {string} recipientPub - A recipient public key
* @param {string} msg - A text message
* @param {Uint8Array} iv - An initialization vector
* @param {Uint8Array} salt - A salt
*
* @return {string} - The encoded message
*/
var _encode = function _encode(senderPriv, recipientPub, msg, iv, salt) {
// Errors
if (!senderPriv || !recipientPub || !msg || !iv || !salt) throw new Error('Missing argument !');
if (!_helpers2.default.isPrivateKeyValid(senderPriv)) throw new Error('Private key is not valid !');
if (!_helpers2.default.isPublicKeyValid(recipientPub)) throw new Error('Public key is not valid !');
// Processing
var sk = _convert2.default.hex2ua_reversed(senderPriv);
var pk = _convert2.default.hex2ua(recipientPub);
var shared = new Uint8Array(32);
var r = key_derive(shared, salt, sk, pk);
var encKey = r;
var encIv = {
iv: _convert2.default.ua2words(iv, 16)
};
var encrypted = _cryptoJs2.default.AES.encrypt(_cryptoJs2.default.enc.Hex.parse(_convert2.default.utf8ToHex(msg)), encKey, encIv);
// Result
var result = _convert2.default.ua2hex(salt) + _convert2.default.ua2hex(iv) + _cryptoJs2.default.enc.Hex.stringify(encrypted.ciphertext);
return result;
};
/**
* Encode a message
*
* @param {string} senderPriv - A sender private key
* @param {string} recipientPub - A recipient public key
* @param {string} msg - A text message
*
* @return {string} - The encoded message
*/
var encode = function encode(senderPriv, recipientPub, msg) {
// Errors
if (!senderPriv || !recipientPub || !msg) throw new Error('Missing argument !');
if (!_helpers2.default.isPrivateKeyValid(senderPriv)) throw new Error('Private key is not valid !');
if (!_helpers2.default.isPublicKeyValid(recipientPub)) throw new Error('Public key is not valid !');
// Processing
var iv = _naclFast2.default.randomBytes(16);
//console.log("IV:", convert.ua2hex(iv));
var salt = _naclFast2.default.randomBytes(32);
var encoded = _encode(senderPriv, recipientPub, msg, iv, salt);
// Result
return encoded;
};
/**
* Decode an encrypted message payload
*
* @param {string} recipientPrivate - A recipient private key
* @param {string} senderPublic - A sender public key
* @param {string} _payload - An encrypted message payload
*
* @return {string} - The decoded payload as hex
*/
var decode = function decode(recipientPrivate, senderPublic, _payload) {
// Errors
if (!recipientPrivate || !senderPublic || !_payload) throw new Error('Missing argument !');
if (!_helpers2.default.isPrivateKeyValid(recipientPrivate)) throw new Error('Private key is not valid !');
if (!_helpers2.default.isPublicKeyValid(senderPublic)) throw new Error('Public key is not valid !');
// Processing
var binPayload = _convert2.default.hex2ua(_payload);
var salt = new Uint8Array(binPayload.buffer, 0, 32);
var iv = new Uint8Array(binPayload.buffer, 32, 16);
var payload = new Uint8Array(binPayload.buffer, 48);
var sk = _convert2.default.hex2ua_reversed(recipientPrivate);
var pk = _convert2.default.hex2ua(senderPublic);
var shared = new Uint8Array(32);
var r = key_derive(shared, salt, sk, pk);
var encKey = r;
var encIv = {
iv: _convert2.default.ua2words(iv, 16)
};
var encrypted = {
'ciphertext': _convert2.default.ua2words(payload, payload.length)
};
var plain = _cryptoJs2.default.AES.decrypt(encrypted, encKey, encIv);
// Result
var hexplain = _cryptoJs2.default.enc.Hex.stringify(plain);
return hexplain;
};
module.exports = {
toMobileKey: toMobileKey,
derivePassSha: derivePassSha,
passwordToPrivatekey: passwordToPrivatekey,
checkAddress: checkAddress,
randomKey: randomKey,
decrypt: decrypt,
encrypt: encrypt,
encodePrivKey: encodePrivKey,
_encode: _encode,
encode: encode,
decode: decode
};
},{"../external/nacl-fast":20,"../model/address":23,"../model/network":26,"../utils/convert":49,"../utils/helpers":51,"./keyPair":19,"crypto-js":179}],19:[function(require,module,exports){
'use strict';
var _naclFast = require('../external/nacl-fast');
var _naclFast2 = _interopRequireDefault(_naclFast);
var _convert = require('../utils/convert');
var _convert2 = _interopRequireDefault(_convert);
var _helpers = require('../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _cryptoJs = require('crypto-js');
var _cryptoJs2 = _interopRequireDefault(_cryptoJs);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/***
* Create a BinaryKey object
*
* @param {Uint8Array} keyData - A key data
*/
var BinaryKey = function BinaryKey(keyData) {
this.data = keyData;
this.toString = function () {
return _convert2.default.ua2hex(this.data);
};
};
var hashfunc = function hashfunc(dest, data, dataLength) {
var convertedData = _convert2.default.ua2words(data, dataLength);
var hash = _cryptoJs2.default.SHA3(convertedData, {
outputLength: 512
});
_convert2.default.words2ua(dest, hash);
};
/***
* Create an hasher object
*/
var hashobj = function hashobj() {
this.sha3 = _cryptoJs2.default.algo.SHA3.create({
outputLength: 512
});
this.reset = function () {
this.sha3 = _cryptoJs2.default.algo.SHA3.create({
outputLength: 512
});
};
this.update = function (data) {
if (data instanceof BinaryKey) {
var converted = _convert2.default.ua2words(data.data, data.data.length);
var result = _cryptoJs2.default.enc.Hex.stringify(converted);
this.sha3.update(converted);
} else if (data instanceof Uint8Array) {
var _converted = _convert2.default.ua2words(data, data.length);
this.sha3.update(_converted);
} else if (typeof data === "string") {
var _converted2 = _cryptoJs2.default.enc.Hex.parse(data);
this.sha3.update(_converted2);
} else {
throw new Error("unhandled argument");
}
};
this.finalize = function (result) {
var hash = this.sha3.finalize();
_convert2.default.words2ua(result, hash);
};
};
/***
* Create a KeyPair Object
*
* @param {string} privkey - An hex private key
*/
var KeyPair = function KeyPair(privkey) {
var _this = this;
this.publicKey = new BinaryKey(new Uint8Array(_naclFast2.default.lowlevel.crypto_sign_PUBLICKEYBYTES));
this.secretKey = _convert2.default.hex2ua_reversed(privkey);
_naclFast2.default.lowlevel.crypto_sign_keypair_hash(this.publicKey.data, this.secretKey, hashfunc);
// Signature
this.sign = function (data) {
var sig = new Uint8Array(64);
var hasher = new hashobj();
var r = _naclFast2.default.lowlevel.crypto_sign_hash(sig, _this, data, hasher);
if (!r) {
alert("Couldn't sign the tx, generated invalid signature");
throw new Error("Couldn't sign the tx, generated invalid signature");
}
return new BinaryKey(sig);
};
};
/**
* Create a NEM KeyPair
*
* @param {string} hexdata - An hex private key
*
* @return {object} - The NEM KeyPair object
*/
var create = function create(hexdata) {
// Errors
if (!hexdata) throw new Error('Missing argument !');
if (!_helpers2.default.isPrivateKeyValid(hexdata)) throw new Error('Private key is not valid !');
// Processing
var r = new KeyPair(hexdata);
// Result
return r;
};
/**
* Verify a signature.
*
* @param {string} publicKey - The public key to use for verification.
* @param {string} data - The data to verify.
* @param {string} signature - The signature to verify.
*
* @return {boolean} - True if the signature is valid, false otherwise.
*/
var verifySignature = function verifySignature(publicKey, data, signature) {
// Errors
if (!publicKey || !data || !signature) throw new Error('Missing argument !');
if (!_helpers2.default.isPublicKeyValid(publicKey)) throw new Error('Public key is not valid !');
if (!_helpers2.default.isHexadecimal(signature)) {
//console.error('Signature must be hexadecimal only !');
return false;
}
if (signature.length !== 128) {
//console.error('Signature length is incorrect !')
return false;
}
// Create an hasher object
var hasher = new hashobj();
// Convert public key to Uint8Array
var _pk = _convert2.default.hex2ua(publicKey);
// Convert signature to Uint8Array
var _signature = _convert2.default.hex2ua(signature);
var c = _naclFast2.default;
var p = [c.gf(), c.gf(), c.gf(), c.gf()];
var q = [c.gf(), c.gf(), c.gf(), c.gf()];
if (c.unpackneg(q, _pk)) return false;
var h = new Uint8Array(64);
hasher.reset();
hasher.update(_signature.subarray(0, 64 / 2));
hasher.update(_pk);
hasher.update(data);
hasher.finalize(h);
c.reduce(h);
c.scalarmult(p, q, h);
var t = new Uint8Array(64);
c.scalarbase(q, _signature.subarray(64 / 2));
c.add(p, q);
c.pack(t, p);
return 0 === _naclFast2.default.lowlevel.crypto_verify_32(_signature, 0, t, 0);
};
module.exports = {
create: create,
verifySignature: verifySignature
};
},{"../external/nacl-fast":20,"../utils/convert":49,"../utils/helpers":51,"crypto-js":179}],20:[function(require,module,exports){
'use strict';
(function (nacl) {
'use strict';
// polyfill for TypedArray.prototype.slice()
Uint8Array.prototype.slice = function (start, end) {
var len = this.length;
var relativeStart = start;
var k = relativeStart < 0 ? max(len + relativeStart, 0) : Math.min(relativeStart, len);
var relativeEnd = end === undefined ? len : end;
var final = relativeEnd < 0 ? max(len + relativeEnd, 0) : Math.min(relativeEnd, len);
var count = final - k;
var c = this.constructor;
var a = new c(count);
var n = 0;
while (k < final) {
a[n] = JSON.parse(JSON.stringify(this[k]));
k++;
n++;
}
return a;
};
Float64Array.prototype.slice = function (start, end) {
var len = this.length;
var relativeStart = start;
var k = relativeStart < 0 ? max(len + relativeStart, 0) : Math.min(relativeStart, len);
var relativeEnd = end === undefined ? len : end;
var final = relativeEnd < 0 ? max(len + relativeEnd, 0) : Math.min(relativeEnd, len);
var count = final - k;
var c = this.constructor;
var a = new c(count);
var n = 0;
while (k < final) {
a[n] = JSON.parse(JSON.stringify(this[k]));
k++;
n++;
}
return a;
};
// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
// Public domain.
//
// Implementation derived from TweetNaCl version 20140427.
// See for details: http://tweetnacl.cr.yp.to/
var gf = function gf(init) {
var i,
r = new Float64Array(16);
if (init) for (i = 0; i < init.length; i++) {
r[i] = init[i];
}return r;
};
// Pluggable, initialized in high-level API below.
var randombytes = function randombytes() /* x, n */{
throw new Error('no PRNG');
};
var _0 = new Uint8Array(16);
var _9 = new Uint8Array(32);_9[0] = 9;
var gf0 = gf(),
gf1 = gf([1]),
_121665 = gf([0xdb41, 1]),
D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),
D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),
X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),
Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),
I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
function vn(x, xi, y, yi, n) {
var i,
d = 0;
for (i = 0; i < n; i++) {
d |= x[xi + i] ^ y[yi + i];
}return (1 & d - 1 >>> 8) - 1;
}
function crypto_verify_32(x, xi, y, yi) {
return vn(x, xi, y, yi, 32);
}
function set25519(r, a) {
var i;
for (i = 0; i < 16; i++) {
r[i] = a[i] | 0;
}
}
function car25519(o) {
var i,
v,
c = 1;
for (i = 0; i < 16; i++) {
v = o[i] + c + 65535;
c = Math.floor(v / 65536);
o[i] = v - c * 65536;
}
o[0] += c - 1 + 37 * (c - 1);
}
function sel25519(p, q, b) {
var t,
c = ~(b - 1);
for (var i = 0; i < 16; i++) {
t = c & (p[i] ^ q[i]);
p[i] ^= t;
q[i] ^= t;
}
}
function pack25519(o, n) {
var i, j, b;
var m = gf(),
t = gf();
for (i = 0; i < 16; i++) {
t[i] = n[i];
}car25519(t);
car25519(t);
car25519(t);
for (j = 0; j < 2; j++) {
m[0] = t[0] - 0xffed;
for (i = 1; i < 15; i++) {
m[i] = t[i] - 0xffff - (m[i - 1] >> 16 & 1);
m[i - 1] &= 0xffff;
}
m[15] = t[15] - 0x7fff - (m[14] >> 16 & 1);
b = m[15] >> 16 & 1;
m[14] &= 0xffff;
sel25519(t, m, 1 - b);
}
for (i = 0; i < 16; i++) {
o[2 * i] = t[i] & 0xff;
o[2 * i + 1] = t[i] >> 8;
}
}
function neq25519(a, b) {
var c = new Uint8Array(32),
d = new Uint8Array(32);
pack25519(c, a);
pack25519(d, b);
return crypto_verify_32(c, 0, d, 0);
}
function par25519(a) {
var d = new Uint8Array(32);
pack25519(d, a);
return d[0] & 1;
}
function unpack25519(o, n) {
var i;
for (i = 0; i < 16; i++) {
o[i] = n[2 * i] + (n[2 * i + 1] << 8);
}o[15] &= 0x7fff;
}
function A(o, a, b) {
for (var i = 0; i < 16; i++) {
o[i] = a[i] + b[i];
}
}
function Z(o, a, b) {
for (var i = 0; i < 16; i++) {
o[i] = a[i] - b[i];
}
}
function M(o, a, b) {
var v,
c,
t0 = 0,
t1 = 0,
t2 = 0,
t3 = 0,
t4 = 0,
t5 = 0,
t6 = 0,
t7 = 0,
t8 = 0,
t9 = 0,
t10 = 0,
t11 = 0,
t12 = 0,
t13 = 0,
t14 = 0,
t15 = 0,
t16 = 0,
t17 = 0,
t18 = 0,
t19 = 0,
t20 = 0,
t21 = 0,
t22 = 0,
t23 = 0,
t24 = 0,
t25 = 0,
t26 = 0,
t27 = 0,
t28 = 0,
t29 = 0,
t30 = 0,
b0 = b[0],
b1 = b[1],
b2 = b[2],
b3 = b[3],
b4 = b[4],
b5 = b[5],
b6 = b[6],
b7 = b[7],
b8 = b[8],
b9 = b[9],
b10 = b[10],
b11 = b[11],
b12 = b[12],
b13 = b[13],
b14 = b[14],
b15 = b[15];
v = a[0];
t0 += v * b0;
t1 += v * b1;
t2 += v * b2;
t3 += v * b3;
t4 += v * b4;
t5 += v * b5;
t6 += v * b6;
t7 += v * b7;
t8 += v * b8;
t9 += v * b9;
t10 += v * b10;
t11 += v * b11;
t12 += v * b12;
t13 += v * b13;
t14 += v * b14;
t15 += v * b15;
v = a[1];
t1 += v * b0;
t2 += v * b1;
t3 += v * b2;
t4 += v * b3;
t5 += v * b4;
t6 += v * b5;
t7 += v * b6;
t8 += v * b7;
t9 += v * b8;
t10 += v * b9;
t11 += v * b10;
t12 += v * b11;
t13 += v * b12;
t14 += v * b13;
t15 += v * b14;
t16 += v * b15;
v = a[2];
t2 += v * b0;
t3 += v * b1;
t4 += v * b2;
t5 += v * b3;
t6 += v * b4;
t7 += v * b5;
t8 += v * b6;
t9 += v * b7;
t10 += v * b8;
t11 += v * b9;
t12 += v * b10;
t13 += v * b11;
t14 += v * b12;
t15 += v * b13;
t16 += v * b14;
t17 += v * b15;
v = a[3];
t3 += v * b0;
t4 += v * b1;
t5 += v * b2;
t6 += v * b3;
t7 += v * b4;
t8 += v * b5;
t9 += v * b6;
t10 += v * b7;
t11 += v * b8;
t12 += v * b9;
t13 += v * b10;
t14 += v * b11;
t15 += v * b12;
t16 += v * b13;
t17 += v * b14;
t18 += v * b15;
v = a[4];
t4 += v * b0;
t5 += v * b1;
t6 += v * b2;
t7 += v * b3;
t8 += v * b4;
t9 += v * b5;
t10 += v * b6;
t11 += v * b7;
t12 += v * b8;
t13 += v * b9;
t14 += v * b10;
t15 += v * b11;
t16 += v * b12;
t17 += v * b13;
t18 += v * b14;
t19 += v * b15;
v = a[5];
t5 += v * b0;
t6 += v * b1;
t7 += v * b2;
t8 += v * b3;
t9 += v * b4;
t10 += v * b5;
t11 += v * b6;
t12 += v * b7;
t13 += v * b8;
t14 += v * b9;
t15 += v * b10;
t16 += v * b11;
t17 += v * b12;
t18 += v * b13;
t19 += v * b14;
t20 += v * b15;
v = a[6];
t6 += v * b0;
t7 += v * b1;
t8 += v * b2;
t9 += v * b3;
t10 += v * b4;
t11 += v * b5;
t12 += v * b6;
t13 += v * b7;
t14 += v * b8;
t15 += v * b9;
t16 += v * b10;
t17 += v * b11;
t18 += v * b12;
t19 += v * b13;
t20 += v * b14;
t21 += v * b15;
v = a[7];
t7 += v * b0;
t8 += v * b1;
t9 += v * b2;
t10 += v * b3;
t11 += v * b4;
t12 += v * b5;
t13 += v * b6;
t14 += v * b7;
t15 += v * b8;
t16 += v * b9;
t17 += v * b10;
t18 += v * b11;
t19 += v * b12;
t20 += v * b13;
t21 += v * b14;
t22 += v * b15;
v = a[8];
t8 += v * b0;
t9 += v * b1;
t10 += v * b2;
t11 += v * b3;
t12 += v * b4;
t13 += v * b5;
t14 += v * b6;
t15 += v * b7;
t16 += v * b8;
t17 += v * b9;
t18 += v * b10;
t19 += v * b11;
t20 += v * b12;
t21 += v * b13;
t22 += v * b14;
t23 += v * b15;
v = a[9];
t9 += v * b0;
t10 += v * b1;
t11 += v * b2;
t12 += v * b3;
t13 += v * b4;
t14 += v * b5;
t15 += v * b6;
t16 += v * b7;
t17 += v * b8;
t18 += v * b9;
t19 += v * b10;
t20 += v * b11;
t21 += v * b12;
t22 += v * b13;
t23 += v * b14;
t24 += v * b15;
v = a[10];
t10 += v * b0;
t11 += v * b1;
t12 += v * b2;
t13 += v * b3;
t14 += v * b4;
t15 += v * b5;
t16 += v * b6;
t17 += v * b7;
t18 += v * b8;
t19 += v * b9;
t20 += v * b10;
t21 += v * b11;
t22 += v * b12;
t23 += v * b13;
t24 += v * b14;
t25 += v * b15;
v = a[11];
t11 += v * b0;
t12 += v * b1;
t13 += v * b2;
t14 += v * b3;
t15 += v * b4;
t16 += v * b5;
t17 += v * b6;
t18 += v * b7;
t19 += v * b8;
t20 += v * b9;
t21 += v * b10;
t22 += v * b11;
t23 += v * b12;
t24 += v * b13;
t25 += v * b14;
t26 += v * b15;
v = a[12];
t12 += v * b0;
t13 += v * b1;
t14 += v * b2;
t15 += v * b3;
t16 += v * b4;
t17 += v * b5;
t18 += v * b6;
t19 += v * b7;
t20 += v * b8;
t21 += v * b9;
t22 += v * b10;
t23 += v * b11;
t24 += v * b12;
t25 += v * b13;
t26 += v * b14;
t27 += v * b15;
v = a[13];
t13 += v * b0;
t14 += v * b1;
t15 += v * b2;
t16 += v * b3;
t17 += v * b4;
t18 += v * b5;
t19 += v * b6;
t20 += v * b7;
t21 += v * b8;
t22 += v * b9;
t23 += v * b10;
t24 += v * b11;
t25 += v * b12;
t26 += v * b13;
t27 += v * b14;
t28 += v * b15;
v = a[14];
t14 += v * b0;
t15 += v * b1;
t16 += v * b2;
t17 += v * b3;
t18 += v * b4;
t19 += v * b5;
t20 += v * b6;
t21 += v * b7;
t22 += v * b8;
t23 += v * b9;
t24 += v * b10;
t25 += v * b11;
t26 += v * b12;
t27 += v * b13;
t28 += v * b14;
t29 += v * b15;
v = a[15];
t15 += v * b0;
t16 += v * b1;
t17 += v * b2;
t18 += v * b3;
t19 += v * b4;
t20 += v * b5;
t21 += v * b6;
t22 += v * b7;
t23 += v * b8;
t24 += v * b9;
t25 += v * b10;
t26 += v * b11;
t27 += v * b12;
t28 += v * b13;
t29 += v * b14;
t30 += v * b15;
t0 += 38 * t16;
t1 += 38 * t17;
t2 += 38 * t18;
t3 += 38 * t19;
t4 += 38 * t20;
t5 += 38 * t21;
t6 += 38 * t22;
t7 += 38 * t23;
t8 += 38 * t24;
t9 += 38 * t25;
t10 += 38 * t26;
t11 += 38 * t27;
t12 += 38 * t28;
t13 += 38 * t29;
t14 += 38 * t30;
// t15 left as is
// first car
c = 1;
v = t0 + c + 65535;c = Math.floor(v / 65536);t0 = v - c * 65536;
v = t1 + c + 65535;c = Math.floor(v / 65536);t1 = v - c * 65536;
v = t2 + c + 65535;c = Math.floor(v / 65536);t2 = v - c * 65536;
v = t3 + c + 65535;c = Math.floor(v / 65536);t3 = v - c * 65536;
v = t4 + c + 65535;c = Math.floor(v / 65536);t4 = v - c * 65536;
v = t5 + c + 65535;c = Math.floor(v / 65536);t5 = v - c * 65536;
v = t6 + c + 65535;c = Math.floor(v / 65536);t6 = v - c * 65536;
v = t7 + c + 65535;c = Math.floor(v / 65536);t7 = v - c * 65536;
v = t8 + c + 65535;c = Math.floor(v / 65536);t8 = v - c * 65536;
v = t9 + c + 65535;c = Math.floor(v / 65536);t9 = v - c * 65536;
v = t10 + c + 65535;c = Math.floor(v / 65536);t10 = v - c * 65536;
v = t11 + c + 65535;c = Math.floor(v / 65536);t11 = v - c * 65536;
v = t12 + c + 65535;c = Math.floor(v / 65536);t12 = v - c * 65536;
v = t13 + c + 65535;c = Math.floor(v / 65536);t13 = v - c * 65536;
v = t14 + c + 65535;c = Math.floor(v / 65536);t14 = v - c * 65536;
v = t15 + c + 65535;c = Math.floor(v / 65536);t15 = v - c * 65536;
t0 += c - 1 + 37 * (c - 1);
// second car
c = 1;
v = t0 + c + 65535;c = Math.floor(v / 65536);t0 = v - c * 65536;
v = t1 + c + 65535;c = Math.floor(v / 65536);t1 = v - c * 65536;
v = t2 + c + 65535;c = Math.floor(v / 65536);t2 = v - c * 65536;
v = t3 + c + 65535;c = Math.floor(v / 65536);t3 = v - c * 65536;
v = t4 + c + 65535;c = Math.floor(v / 65536);t4 = v - c * 65536;
v = t5 + c + 65535;c = Math.floor(v / 65536);t5 = v - c * 65536;
v = t6 + c + 65535;c = Math.floor(v / 65536);t6 = v - c * 65536;
v = t7 + c + 65535;c = Math.floor(v / 65536);t7 = v - c * 65536;
v = t8 + c + 65535;c = Math.floor(v / 65536);t8 = v - c * 65536;
v = t9 + c + 65535;c = Math.floor(v / 65536);t9 = v - c * 65536;
v = t10 + c + 65535;c = Math.floor(v / 65536);t10 = v - c * 65536;
v = t11 + c + 65535;c = Math.floor(v / 65536);t11 = v - c * 65536;
v = t12 + c + 65535;c = Math.floor(v / 65536);t12 = v - c * 65536;
v = t13 + c + 65535;c = Math.floor(v / 65536);t13 = v - c * 65536;
v = t14 + c + 65535;c = Math.floor(v / 65536);t14 = v - c * 65536;
v = t15 + c + 65535;c = Math.floor(v / 65536);t15 = v - c * 65536;
t0 += c - 1 + 37 * (c - 1);
o[0] = t0;
o[1] = t1;
o[2] = t2;
o[3] = t3;
o[4] = t4;
o[5] = t5;
o[6] = t6;
o[7] = t7;
o[8] = t8;
o[9] = t9;
o[10] = t10;
o[11] = t11;
o[12] = t12;
o[13] = t13;
o[14] = t14;
o[15] = t15;
}
function S(o, a) {
M(o, a, a);
}
function inv25519(o, i) {
var c = gf();
var a;
for (a = 0; a < 16; a++) {
c[a] = i[a];
}for (a = 253; a >= 0; a--) {
S(c, c);
if (a !== 2 && a !== 4) M(c, c, i);
}
for (a = 0; a < 16; a++) {
o[a] = c[a];
}
}
function pow2523(o, i) {
var c = gf();
var a;
for (a = 0; a < 16; a++) {
c[a] = i[a];
}for (a = 250; a >= 0; a--) {
S(c, c);
if (a !== 1) M(c, c, i);
}
for (a = 0; a < 16; a++) {
o[a] = c[a];
}
}
function crypto_scalarmult(q, n, p) {
var z = new Uint8Array(32);
var x = new Float64Array(80),
r,
i;
var a = gf(),
b = gf(),
c = gf(),
d = gf(),
e = gf(),
f = gf();
for (i = 0; i < 31; i++) {
z[i] = n[i];
}z[31] = n[31] & 127 | 64;
z[0] &= 248;
unpack25519(x, p);
for (i = 0; i < 16; i++) {
b[i] = x[i];
d[i] = a[i] = c[i] = 0;
}
a[0] = d[0] = 1;
for (i = 254; i >= 0; --i) {
r = z[i >>> 3] >>> (i & 7) & 1;
sel25519(a, b, r);
sel25519(c, d, r);
A(e, a, c);
Z(a, a, c);
A(c, b, d);
Z(b, b, d);
S(d, e);
S(f, a);
M(a, c, a);
M(c, b, e);
A(e, a, c);
Z(a, a, c);
S(b, a);
Z(c, d, f);
M(a, c, _121665);
A(a, a, d);
M(c, c, a);
M(a, d, f);
M(d, b, x);
S(b, e);
sel25519(a, b, r);
sel25519(c, d, r);
}
for (i = 0; i < 16; i++) {
x[i + 16] = a[i];
x[i + 32] = c[i];
x[i + 48] = b[i];
x[i + 64] = d[i];
}
var x32 = x.subarray(32);
var x16 = x.subarray(16);
inv25519(x32, x32);
M(x16, x16, x32);
pack25519(q, x16);
return 0;
}
function crypto_scalarmult_base(q, n) {
return crypto_scalarmult(q, n, _9);
}
function add(p, q) {
var a = gf(),
b = gf(),
c = gf(),
d = gf(),
e = gf(),
f = gf(),
g = gf(),
h = gf(),
t = gf();
Z(a, p[1], p[0]);
Z(t, q[1], q[0]);
M(a, a, t);
A(b, p[0], p[1]);
A(t, q[0], q[1]);
M(b, b, t);
M(c, p[3], q[3]);
M(c, c, D2);
M(d, p[2], q[2]);
A(d, d, d);
Z(e, b, a);
Z(f, d, c);
A(g, d, c);
A(h, b, a);
M(p[0], e, f);
M(p[1], h, g);
M(p[2], g, f);
M(p[3], e, h);
}
function cswap(p, q, b) {
var i;
for (i = 0; i < 4; i++) {
sel25519(p[i], q[i], b);
}
}
function pack(r, p) {
var tx = gf(),
ty = gf(),
zi = gf();
inv25519(zi, p[2]);
M(tx, p[0], zi);
M(ty, p[1], zi);
pack25519(r, ty);
r[31] ^= par25519(tx) << 7;
}
function scalarmult(p, q, s) {
var b, i;
set25519(p[0], gf0);
set25519(p[1], gf1);
set25519(p[2], gf1);
set25519(p[3], gf0);
for (i = 255; i >= 0; --i) {
b = s[i / 8 | 0] >> (i & 7) & 1;
cswap(p, q, b);
add(q, p);
add(p, p);
cswap(p, q, b);
}
}
function scalarbase(p, s) {
var q = [gf(), gf(), gf(), gf()];
set25519(q[0], X);
set25519(q[1], Y);
set25519(q[2], gf1);
M(q[3], X, Y);
scalarmult(p, q, s);
}
function crypto_sign_keypair_hash(pk, sk, hashfunc) {
var d = new Uint8Array(64);
var p = [gf(), gf(), gf(), gf()];
var i;
hashfunc(d, sk, 32);
d[0] &= 248;
d[31] &= 127;
d[31] |= 64;
scalarbase(p, d);
pack(pk, p);
for (i = 0; i < 32; i++) {
sk[i + 32] = pk[i];
}return 0;
}
function crypto_shared_key_hash(shared, pk, sk, hashfunc) {
var d = new Uint8Array(64);
var p = [gf(), gf(), gf(), gf()];
hashfunc(d, sk, 32);
d[0] &= 248;
d[31] &= 127;
d[31] |= 64;
var q = [gf(), gf(), gf(), gf()];
unpack(q, pk);
scalarmult(p, q, d);
pack(shared, p);
}
function crypto_sign_hash(sm, keypair, data, hasher) {
var privHash = new Uint8Array(64);
var seededHash = new Uint8Array(64);
var result = new Uint8Array(64);
var p = [gf(), gf(), gf(), gf()];
var i;
hasher.update(keypair.secretKey);
hasher.finalize(privHash);
privHash[0] &= 248;
privHash[31] &= 127;
privHash[31] |= 64;
hasher.reset();
hasher.update(privHash.slice(32));
hasher.update(data);
hasher.finalize(seededHash);
reduce(seededHash);
scalarbase(p, seededHash);
pack(sm, p);
hasher.reset();
hasher.update(sm.slice(0, 32));
hasher.update(keypair.publicKey);
hasher.update(data);
hasher.finalize(result);
reduce(result);
// muladd - this is from original tweetnacl-js
var x = new Float64Array(64);
for (var i = 0; i < 64; i++) {
x[i] = 0;
}for (var i = 0; i < 32; i++) {
x[i] = seededHash[i];
}for (var i = 0; i < 32; i++) {
for (var j = 0; j < 32; j++) {
x[i + j] += result[i] * privHash[j];
}
}
modL(sm.subarray(32), x);
// check if zero
var isZero = 0;
for (var i = 0; i < 32; i++) {
isZero |= sm[32 + i] ^ 0;
result[i] = sm[32 + i];
}
if (isZero == 0) return false;
reduce(result);
// check if canonical
isZero = 0;
for (var i = 0; i < 32; i++) {
isZero |= sm[32 + i] ^ result[i];
}
return isZero == 0;
}
var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);
function modL(r, x) {
var carry, i, j, k;
for (i = 63; i >= 32; --i) {
carry = 0;
for (j = i - 32, k = i - 12; j < k; ++j) {
x[j] += carry - 16 * x[i] * L[j - (i - 32)];
carry = x[j] + 128 >> 8;
x[j] -= carry * 256;
}
x[j] += carry;
x[i] = 0;
}
carry = 0;
for (j = 0; j < 32; j++) {
x[j] += carry - (x[31] >> 4) * L[j];
carry = x[j] >> 8;
x[j] &= 255;
}
for (j = 0; j < 32; j++) {
x[j] -= carry * L[j];
}for (i = 0; i < 32; i++) {
x[i + 1] += x[i] >> 8;
r[i] = x[i] & 255;
}
}
function reduce(r) {
var x = new Float64Array(64),
i;
for (i = 0; i < 64; i++) {
x[i] = r[i];
}for (i = 0; i < 64; i++) {
r[i] = 0;
}modL(r, x);
}
function unpackneg(r, p) {
var t = gf(),
chk = gf(),
num = gf(),
den = gf(),
den2 = gf(),
den4 = gf(),
den6 = gf();
set25519(r[2], gf1);
unpack25519(r[1], p);
// num = u = y^2 - 1
// den = v = d * y^2 + 1
S(num, r[1]);
M(den, num, D);
Z(num, num, r[2]);
A(den, r[2], den);
// r[0] = x = sqrt(u / v)
S(den2, den);
S(den4, den2);
M(den6, den4, den2);
M(t, den6, num);
M(t, t, den);
pow2523(t, t);
M(t, t, num);
M(t, t, den);
M(t, t, den);
M(r[0], t, den);
S(chk, r[0]);
M(chk, chk, den);
if (neq25519(chk, num)) {
M(r[0], r[0], I);
}
S(chk, r[0]);
M(chk, chk, den);
if (neq25519(chk, num)) {
return -1;
}
if (par25519(r[0]) === p[31] >> 7) {
Z(r[0], gf0, r[0]);
}
M(r[3], r[0], r[1]);
return 0;
}
function unpack(r, p) {
var t = gf(),
chk = gf(),
num = gf(),
den = gf(),
den2 = gf(),
den4 = gf(),
den6 = gf();
set25519(r[2], gf1);
unpack25519(r[1], p);
// num = u = y^2 - 1
// den = v = d * y^2 + 1
S(num, r[1]);
M(den, num, D);
Z(num, num, r[2]);
A(den, r[2], den);
// r[0] = x = sqrt(u / v)
S(den2, den);
S(den4, den2);
M(den6, den4, den2);
M(t, den6, num);
M(t, t, den);
pow2523(t, t);
M(t, t, num);
M(t, t, den);
M(t, t, den);
M(r[0], t, den);
S(chk, r[0]);
M(chk, chk, den);
if (neq25519(chk, num)) {
M(r[0], r[0], I);
}
S(chk, r[0]);
M(chk, chk, den);
if (neq25519(chk, num)) {
console.log("not a valid Ed25519EncodedGroupElement.");
return -1;
}
if (par25519(r[0]) !== p[31] >> 7) {
Z(r[0], gf0, r[0]);
}
M(r[3], r[0], r[1]);
return 0;
}
var crypto_scalarmult_BYTES = 32,
crypto_scalarmult_SCALARBYTES = 32,
crypto_sign_BYTES = 64,
crypto_sign_PUBLICKEYBYTES = 32,
crypto_sign_SECRETKEYBYTES = 64,
crypto_sign_SEEDBYTES = 32,
crypto_hash_BYTES = 64;
function crypto_sign_open(m, sm, n, pk) {
var i, mlen;
var t = new Uint8Array(32),
h = new Uint8Array(64);
var p = [gf(), gf(), gf(), gf()],
q = [gf(), gf(), gf(), gf()];
mlen = -1;
if (n < 64) return -1;
if (unpackneg(q, pk)) return -1;
for (i = 0; i < n; i++) {
m[i] = sm[i];
}for (i = 0; i < 32; i++) {
m[i + 32] = pk[i];
}crypto_hash(h, m, n);
reduce(h);
scalarmult(p, q, h);
scalarbase(q, sm.subarray(32));
add(p, q);
pack(t, p);
n -= 64;
if (crypto_verify_32(sm, 0, t, 0)) {
for (i = 0; i < n; i++) {
m[i] = 0;
}return -1;
}
for (i = 0; i < n; i++) {
m[i] = sm[i + 64];
}mlen = n;
return mlen;
};
nacl.lowlevel = {
crypto_verify_32: crypto_verify_32,
crypto_scalarmult: crypto_scalarmult,
crypto_scalarmult_base: crypto_scalarmult_base,
crypto_sign_keypair_hash: crypto_sign_keypair_hash,
crypto_shared_key_hash: crypto_shared_key_hash,
crypto_sign_hash: crypto_sign_hash,
crypto_scalarmult_BYTES: crypto_scalarmult_BYTES,
crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES,
crypto_sign_BYTES: crypto_sign_BYTES,
crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES,
crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES,
crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES,
crypto_hash_BYTES: crypto_hash_BYTES
};
/*/////////////////////////////////////////////// High-level API ///////////////////////////////////////// */
function checkArrayTypes() {
var t, i;
for (i = 0; i < arguments.length; i++) {
if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') throw new TypeError('unexpected type ' + t + ', use Uint8Array');
}
}
function cleanup(arr) {
for (var i = 0; i < arr.length; i++) {
arr[i] = 0;
}
}
nacl.randomBytes = function (n) {
var b = new Uint8Array(n);
randombytes(b, n);
return b;
};
nacl.scalarMult = function (n, p) {
checkArrayTypes(n, p);
if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');
var q = new Uint8Array(crypto_scalarmult_BYTES);
crypto_scalarmult(q, n, p);
return q;
};
nacl.scalarMult.base = function (n) {
checkArrayTypes(n);
if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
var q = new Uint8Array(crypto_scalarmult_BYTES);
crypto_scalarmult_base(q, n);
return q;
};
nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;
nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;
nacl.verify = function (x, y) {
checkArrayTypes(x, y);
// Zero length arguments are considered not equal.
if (x.length === 0 || y.length === 0) return false;
if (x.length !== y.length) return false;
return vn(x, 0, y, 0, x.length) === 0 ? true : false;
};
nacl.setPRNG = function (fn) {
randombytes = fn;
};
// For signature verification in KeyPair.js
nacl.gf = gf;
nacl.unpackneg = unpackneg;
nacl.reduce = reduce;
nacl.scalarmult = scalarmult;
nacl.scalarbase = scalarbase;
nacl.add = add;
nacl.pack = pack;
(function () {
// Initialize PRNG if environment provides CSPRNG.
// If not, methods calling randombytes will throw.
var crypto;
if (typeof window !== 'undefined') {
// Browser.
if (window.crypto && window.crypto.getRandomValues) {
crypto = window.crypto; // Standard
} else if (window.msCrypto && window.msCrypto.getRandomValues) {
crypto = window.msCrypto; // Internet Explorer 11+
}
if (crypto) {
nacl.setPRNG(function (x, n) {
var i,
v = new Uint8Array(n);
crypto.getRandomValues(v);
for (i = 0; i < n; i++) {
x[i] = v[i];
}cleanup(v);
});
}
} else if (typeof require !== 'undefined') {
// Node.js.
crypto = require('crypto');
if (crypto) {
nacl.setPRNG(function (x, n) {
var i,
v = crypto.randomBytes(n);
for (i = 0; i < n; i++) {
x[i] = v[i];
}cleanup(v);
});
}
}
})();
})(typeof module !== 'undefined' && module.exports ? module.exports : window.nacl = window.nacl || {});
},{"crypto":170}],21:[function(require,module,exports){
"use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/* SockJS client, version 0.3.4, http://sockjs.org, MIT License
Copyright (c) 2011-2012 VMware, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// JSON2 by Douglas Crockford (minified).
var JSON;JSON || (JSON = {}), function () {
function str(a, b) {
var c,
d,
e,
f,
g = gap,
h,
i = b[a];i && (typeof i === "undefined" ? "undefined" : _typeof(i)) == "object" && typeof i.toJSON == "function" && (i = i.toJSON(a)), typeof rep == "function" && (i = rep.call(b, a, i));switch (typeof i === "undefined" ? "undefined" : _typeof(i)) {case "string":
return quote(i);case "number":
return isFinite(i) ? String(i) : "null";case "boolean":case "null":
return String(i);case "object":
if (!i) return "null";gap += indent, h = [];if (Object.prototype.toString.apply(i) === "[object Array]") {
f = i.length;for (c = 0; c < f; c += 1) {
h[c] = str(c, i) || "null";
}e = h.length === 0 ? "[]" : gap ? "[\n" + gap + h.join(",\n" + gap) + "\n" + g + "]" : "[" + h.join(",") + "]", gap = g;return e;
}if (rep && (typeof rep === "undefined" ? "undefined" : _typeof(rep)) == "object") {
f = rep.length;for (c = 0; c < f; c += 1) {
typeof rep[c] == "string" && (d = rep[c], e = str(d, i), e && h.push(quote(d) + (gap ? ": " : ":") + e));
}
} else for (d in i) {
Object.prototype.hasOwnProperty.call(i, d) && (e = str(d, i), e && h.push(quote(d) + (gap ? ": " : ":") + e));
}e = h.length === 0 ? "{}" : gap ? "{\n" + gap + h.join(",\n" + gap) + "\n" + g + "}" : "{" + h.join(",") + "}", gap = g;return e;}
}function quote(a) {
escapable.lastIndex = 0;return escapable.test(a) ? '"' + a.replace(escapable, function (a) {
var b = meta[a];return typeof b == "string" ? b : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + a + '"';
}function f(a) {
return a < 10 ? "0" + a : a;
}"use strict", typeof Date.prototype.toJSON != "function" && (Date.prototype.toJSON = function (a) {
return isFinite(this.valueOf()) ? this.getUTCFullYear() + "-" + f(this.getUTCMonth() + 1) + "-" + f(this.getUTCDate()) + "T" + f(this.getUTCHours()) + ":" + f(this.getUTCMinutes()) + ":" + f(this.getUTCSeconds()) + "Z" : null;
}, String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (a) {
return this.valueOf();
});var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { "\b": "\\b", "\t": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "\\": "\\\\" },
rep;typeof JSON.stringify != "function" && (JSON.stringify = function (a, b, c) {
var d;gap = "", indent = "";if (typeof c == "number") for (d = 0; d < c; d += 1) {
indent += " ";
} else typeof c == "string" && (indent = c);rep = b;if (!b || typeof b == "function" || (typeof b === "undefined" ? "undefined" : _typeof(b)) == "object" && typeof b.length == "number") return str("", { "": a });throw new Error("JSON.stringify");
}), typeof JSON.parse != "function" && (JSON.parse = function (text, reviver) {
function walk(a, b) {
var c,
d,
e = a[b];if (e && (typeof e === "undefined" ? "undefined" : _typeof(e)) == "object") for (c in e) {
Object.prototype.hasOwnProperty.call(e, c) && (d = walk(e, c), d !== undefined ? e[c] = d : delete e[c]);
}return reviver.call(a, b, e);
}var j;text = String(text), cx.lastIndex = 0, cx.test(text) && (text = text.replace(cx, function (a) {
return "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
}));if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) {
j = eval("(" + text + ")");return typeof reviver == "function" ? walk({ "": j }, "") : j;
}throw new SyntaxError("JSON.parse");
});
}();
// [*] Including lib/index.js
// Public object
var SockJS = function () {
if (typeof document === "undefined" || typeof window === "undefined") {
return null;
}
var _document = document;
var _window = window;
var utils = {};
// [*] Including lib/reventtarget.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
/* Simplified implementation of DOM2 EventTarget.
* http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget
*/
var REventTarget = function REventTarget() {};
REventTarget.prototype.addEventListener = function (eventType, listener) {
if (!this._listeners) {
this._listeners = {};
}
if (!(eventType in this._listeners)) {
this._listeners[eventType] = [];
}
var arr = this._listeners[eventType];
if (utils.arrIndexOf(arr, listener) === -1) {
arr.push(listener);
}
return;
};
REventTarget.prototype.removeEventListener = function (eventType, listener) {
if (!(this._listeners && eventType in this._listeners)) {
return;
}
var arr = this._listeners[eventType];
var idx = utils.arrIndexOf(arr, listener);
if (idx !== -1) {
if (arr.length > 1) {
this._listeners[eventType] = arr.slice(0, idx).concat(arr.slice(idx + 1));
} else {
delete this._listeners[eventType];
}
return;
}
return;
};
REventTarget.prototype.dispatchEvent = function (event) {
var t = event.type;
var args = Array.prototype.slice.call(arguments, 0);
if (this['on' + t]) {
this['on' + t].apply(this, args);
}
if (this._listeners && t in this._listeners) {
for (var i = 0; i < this._listeners[t].length; i++) {
this._listeners[t][i].apply(this, args);
}
}
};
// [*] End of lib/reventtarget.js
// [*] Including lib/simpleevent.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var SimpleEvent = function SimpleEvent(type, obj) {
this.type = type;
if (typeof obj !== 'undefined') {
for (var k in obj) {
if (!obj.hasOwnProperty(k)) continue;
this[k] = obj[k];
}
}
};
SimpleEvent.prototype.toString = function () {
var r = [];
for (var k in this) {
if (!this.hasOwnProperty(k)) continue;
var v = this[k];
if (typeof v === 'function') v = '[function]';
r.push(k + '=' + v);
}
return 'SimpleEvent(' + r.join(', ') + ')';
};
// [*] End of lib/simpleevent.js
// [*] Including lib/eventemitter.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var EventEmitter = function EventEmitter(events) {
var that = this;
that._events = events || [];
that._listeners = {};
};
EventEmitter.prototype.emit = function (type) {
var that = this;
that._verifyType(type);
if (that._nuked) return;
var args = Array.prototype.slice.call(arguments, 1);
if (that['on' + type]) {
that['on' + type].apply(that, args);
}
if (type in that._listeners) {
for (var i = 0; i < that._listeners[type].length; i++) {
that._listeners[type][i].apply(that, args);
}
}
};
EventEmitter.prototype.on = function (type, callback) {
var that = this;
that._verifyType(type);
if (that._nuked) return;
if (!(type in that._listeners)) {
that._listeners[type] = [];
}
that._listeners[type].push(callback);
};
EventEmitter.prototype._verifyType = function (type) {
var that = this;
if (utils.arrIndexOf(that._events, type) === -1) {
utils.log('Event ' + JSON.stringify(type) + ' not listed ' + JSON.stringify(that._events) + ' in ' + that);
}
};
EventEmitter.prototype.nuke = function () {
var that = this;
that._nuked = true;
for (var i = 0; i < that._events.length; i++) {
delete that[that._events[i]];
}
that._listeners = {};
};
// [*] End of lib/eventemitter.js
// [*] Including lib/utils.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var random_string_chars = 'abcdefghijklmnopqrstuvwxyz0123456789_';
utils.random_string = function (length, max) {
max = max || random_string_chars.length;
var i,
ret = [];
for (i = 0; i < length; i++) {
ret.push(random_string_chars.substr(Math.floor(Math.random() * max), 1));
}
return ret.join('');
};
utils.random_number = function (max) {
return Math.floor(Math.random() * max);
};
utils.random_number_string = function (max) {
var t = ('' + (max - 1)).length;
var p = Array(t + 1).join('0');
return (p + utils.random_number(max)).slice(-t);
};
// Assuming that url looks like: http://asdasd:111/asd
utils.getOrigin = function (url) {
url += '/';
var parts = url.split('/').slice(0, 3);
return parts.join('/');
};
utils.isSameOriginUrl = function (url_a, url_b) {
// location.origin would do, but it's not always available.
if (!url_b) url_b = _window.location.href;
return url_a.split('/').slice(0, 3).join('/') === url_b.split('/').slice(0, 3).join('/');
};
utils.getParentDomain = function (url) {
// ipv4 ip address
if (/^[0-9.]*$/.test(url)) return url;
// ipv6 ip address
if (/^\[/.test(url)) return url;
// no dots
if (!/[.]/.test(url)) return url;
var parts = url.split('.').slice(1);
return parts.join('.');
};
utils.objectExtend = function (dst, src) {
for (var k in src) {
if (src.hasOwnProperty(k)) {
dst[k] = src[k];
}
}
return dst;
};
var WPrefix = '_jp';
utils.polluteGlobalNamespace = function () {
if (!(WPrefix in _window)) {
_window[WPrefix] = {};
}
};
utils.closeFrame = function (code, reason) {
return 'c' + JSON.stringify([code, reason]);
};
utils.userSetCode = function (code) {
return code === 1000 || code >= 3000 && code <= 4999;
};
// See: http://www.erg.abdn.ac.uk/~gerrit/dccp/notes/ccid2/rto_estimator/
// and RFC 2988.
utils.countRTO = function (rtt) {
var rto;
if (rtt > 100) {
rto = 3 * rtt; // rto > 300msec
} else {
rto = rtt + 200; // 200msec < rto <= 300msec
}
return rto;
};
utils.log = function () {
if (_window.console && console.log && console.log.apply) {
console.log.apply(console, arguments);
}
};
utils.bind = function (fun, that) {
if (fun.bind) {
return fun.bind(that);
} else {
return function () {
return fun.apply(that, arguments);
};
}
};
utils.flatUrl = function (url) {
return url.indexOf('?') === -1 && url.indexOf('#') === -1;
};
utils.amendUrl = function (url) {
var dl = _document.location;
if (!url) {
throw new Error('Wrong url for SockJS');
}
if (!utils.flatUrl(url)) {
throw new Error('Only basic urls are supported in SockJS');
}
// '//abc' --> 'http://abc'
if (url.indexOf('//') === 0) {
url = dl.protocol + url;
}
// '/abc' --> 'http://localhost:80/abc'
if (url.indexOf('/') === 0) {
url = dl.protocol + '//' + dl.host + url;
}
// strip trailing slashes
url = url.replace(/[/]+$/, '');
return url;
};
// IE doesn't support [].indexOf.
utils.arrIndexOf = function (arr, obj) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === obj) {
return i;
}
}
return -1;
};
utils.arrSkip = function (arr, obj) {
var idx = utils.arrIndexOf(arr, obj);
if (idx === -1) {
return arr.slice();
} else {
var dst = arr.slice(0, idx);
return dst.concat(arr.slice(idx + 1));
}
};
// Via: https://gist.github.com/1133122/2121c601c5549155483f50be3da5305e83b8c5df
utils.isArray = Array.isArray || function (value) {
return {}.toString.call(value).indexOf('Array') >= 0;
};
utils.delay = function (t, fun) {
if (typeof t === 'function') {
fun = t;
t = 0;
}
return setTimeout(fun, t);
};
// Chars worth escaping, as defined by Douglas Crockford:
// https://github.com/douglascrockford/JSON-js/blob/47a9882cddeb1e8529e07af9736218075372b8ac/json2.js#L196
var json_escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
json_lookup = {
"\0": "\\u0000", "\x01": "\\u0001", "\x02": "\\u0002", "\x03": "\\u0003",
"\x04": "\\u0004", "\x05": "\\u0005", "\x06": "\\u0006", "\x07": "\\u0007",
"\b": "\\b", "\t": "\\t", "\n": "\\n", "\x0B": "\\u000b", "\f": "\\f", "\r": "\\r",
"\x0E": "\\u000e", "\x0F": "\\u000f", "\x10": "\\u0010", "\x11": "\\u0011",
"\x12": "\\u0012", "\x13": "\\u0013", "\x14": "\\u0014", "\x15": "\\u0015",
"\x16": "\\u0016", "\x17": "\\u0017", "\x18": "\\u0018", "\x19": "\\u0019",
"\x1A": "\\u001a", "\x1B": "\\u001b", "\x1C": "\\u001c", "\x1D": "\\u001d",
"\x1E": "\\u001e", "\x1F": "\\u001f", "\"": "\\\"", "\\": "\\\\",
"\x7F": "\\u007f", "\x80": "\\u0080", "\x81": "\\u0081", "\x82": "\\u0082",
"\x83": "\\u0083", "\x84": "\\u0084", "\x85": "\\u0085", "\x86": "\\u0086",
"\x87": "\\u0087", "\x88": "\\u0088", "\x89": "\\u0089", "\x8A": "\\u008a",
"\x8B": "\\u008b", "\x8C": "\\u008c", "\x8D": "\\u008d", "\x8E": "\\u008e",
"\x8F": "\\u008f", "\x90": "\\u0090", "\x91": "\\u0091", "\x92": "\\u0092",
"\x93": "\\u0093", "\x94": "\\u0094", "\x95": "\\u0095", "\x96": "\\u0096",
"\x97": "\\u0097", "\x98": "\\u0098", "\x99": "\\u0099", "\x9A": "\\u009a",
"\x9B": "\\u009b", "\x9C": "\\u009c", "\x9D": "\\u009d", "\x9E": "\\u009e",
"\x9F": "\\u009f", "\xAD": "\\u00ad", "\u0600": "\\u0600", "\u0601": "\\u0601",
"\u0602": "\\u0602", "\u0603": "\\u0603", "\u0604": "\\u0604", "\u070F": "\\u070f",
"\u17B4": "\\u17b4", "\u17B5": "\\u17b5", "\u200C": "\\u200c", "\u200D": "\\u200d",
"\u200E": "\\u200e", "\u200F": "\\u200f", "\u2028": "\\u2028", "\u2029": "\\u2029",
"\u202A": "\\u202a", "\u202B": "\\u202b", "\u202C": "\\u202c", "\u202D": "\\u202d",
"\u202E": "\\u202e", "\u202F": "\\u202f", "\u2060": "\\u2060", "\u2061": "\\u2061",
"\u2062": "\\u2062", "\u2063": "\\u2063", "\u2064": "\\u2064", "\u2065": "\\u2065",
"\u2066": "\\u2066", "\u2067": "\\u2067", "\u2068": "\\u2068", "\u2069": "\\u2069",
"\u206A": "\\u206a", "\u206B": "\\u206b", "\u206C": "\\u206c", "\u206D": "\\u206d",
"\u206E": "\\u206e", "\u206F": "\\u206f", "\uFEFF": "\\ufeff", "\uFFF0": "\\ufff0",
"\uFFF1": "\\ufff1", "\uFFF2": "\\ufff2", "\uFFF3": "\\ufff3", "\uFFF4": "\\ufff4",
"\uFFF5": "\\ufff5", "\uFFF6": "\\ufff6", "\uFFF7": "\\ufff7", "\uFFF8": "\\ufff8",
"\uFFF9": "\\ufff9", "\uFFFA": "\\ufffa", "\uFFFB": "\\ufffb", "\uFFFC": "\\ufffc",
"\uFFFD": "\\ufffd", "\uFFFE": "\\ufffe", "\uFFFF": "\\uffff" };
// Some extra characters that Chrome gets wrong, and substitutes with
// something else on the wire.
var extra_escapable = /[\x00-\x1f\ud800-\udfff\ufffe\uffff\u0300-\u0333\u033d-\u0346\u034a-\u034c\u0350-\u0352\u0357-\u0358\u035c-\u0362\u0374\u037e\u0387\u0591-\u05af\u05c4\u0610-\u0617\u0653-\u0654\u0657-\u065b\u065d-\u065e\u06df-\u06e2\u06eb-\u06ec\u0730\u0732-\u0733\u0735-\u0736\u073a\u073d\u073f-\u0741\u0743\u0745\u0747\u07eb-\u07f1\u0951\u0958-\u095f\u09dc-\u09dd\u09df\u0a33\u0a36\u0a59-\u0a5b\u0a5e\u0b5c-\u0b5d\u0e38-\u0e39\u0f43\u0f4d\u0f52\u0f57\u0f5c\u0f69\u0f72-\u0f76\u0f78\u0f80-\u0f83\u0f93\u0f9d\u0fa2\u0fa7\u0fac\u0fb9\u1939-\u193a\u1a17\u1b6b\u1cda-\u1cdb\u1dc0-\u1dcf\u1dfc\u1dfe\u1f71\u1f73\u1f75\u1f77\u1f79\u1f7b\u1f7d\u1fbb\u1fbe\u1fc9\u1fcb\u1fd3\u1fdb\u1fe3\u1feb\u1fee-\u1fef\u1ff9\u1ffb\u1ffd\u2000-\u2001\u20d0-\u20d1\u20d4-\u20d7\u20e7-\u20e9\u2126\u212a-\u212b\u2329-\u232a\u2adc\u302b-\u302c\uaab2-\uaab3\uf900-\ufa0d\ufa10\ufa12\ufa15-\ufa1e\ufa20\ufa22\ufa25-\ufa26\ufa2a-\ufa2d\ufa30-\ufa6d\ufa70-\ufad9\ufb1d\ufb1f\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4e\ufff0-\uffff]/g,
extra_lookup;
// JSON Quote string. Use native implementation when possible.
var JSONQuote = JSON && JSON.stringify || function (string) {
json_escapable.lastIndex = 0;
if (json_escapable.test(string)) {
string = string.replace(json_escapable, function (a) {
return json_lookup[a];
});
}
return '"' + string + '"';
};
// This may be quite slow, so let's delay until user actually uses bad
// characters.
var unroll_lookup = function unroll_lookup(escapable) {
var i;
var unrolled = {};
var c = [];
for (i = 0; i < 65536; i++) {
c.push(String.fromCharCode(i));
}
escapable.lastIndex = 0;
c.join('').replace(escapable, function (a) {
unrolled[a] = "\\u" + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
return '';
});
escapable.lastIndex = 0;
return unrolled;
};
// Quote string, also taking care of unicode characters that browsers
// often break. Especially, take care of unicode surrogates:
// http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Surrogates
utils.quote = function (string) {
var quoted = JSONQuote(string);
// In most cases this should be very fast and good enough.
extra_escapable.lastIndex = 0;
if (!extra_escapable.test(quoted)) {
return quoted;
}
if (!extra_lookup) extra_lookup = unroll_lookup(extra_escapable);
return quoted.replace(extra_escapable, function (a) {
return extra_lookup[a];
});
};
var _all_protocols = ['websocket', 'xdr-streaming', 'xhr-streaming', 'iframe-eventsource', 'iframe-htmlfile', 'xdr-polling', 'xhr-polling', 'iframe-xhr-polling', 'jsonp-polling'];
utils.probeProtocols = function () {
var probed = {};
for (var i = 0; i < _all_protocols.length; i++) {
var protocol = _all_protocols[i];
// User can have a typo in protocol name.
probed[protocol] = SockJS[protocol] && SockJS[protocol].enabled();
}
return probed;
};
utils.detectProtocols = function (probed, protocols_whitelist, info) {
var pe = {},
protocols = [];
if (!protocols_whitelist) protocols_whitelist = _all_protocols;
for (var i = 0; i < protocols_whitelist.length; i++) {
var protocol = protocols_whitelist[i];
pe[protocol] = probed[protocol];
}
var maybe_push = function maybe_push(protos) {
var proto = protos.shift();
if (pe[proto]) {
protocols.push(proto);
} else {
if (protos.length > 0) {
maybe_push(protos);
}
}
};
// 1. Websocket
if (info.websocket !== false) {
maybe_push(['websocket']);
}
// 2. Streaming
if (pe['xhr-streaming'] && !info.null_origin) {
protocols.push('xhr-streaming');
} else {
if (pe['xdr-streaming'] && !info.cookie_needed && !info.null_origin) {
protocols.push('xdr-streaming');
} else {
maybe_push(['iframe-eventsource', 'iframe-htmlfile']);
}
}
// 3. Polling
if (pe['xhr-polling'] && !info.null_origin) {
protocols.push('xhr-polling');
} else {
if (pe['xdr-polling'] && !info.cookie_needed && !info.null_origin) {
protocols.push('xdr-polling');
} else {
maybe_push(['iframe-xhr-polling', 'jsonp-polling']);
}
}
return protocols;
};
// [*] End of lib/utils.js
// [*] Including lib/dom.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
// May be used by htmlfile jsonp and transports.
var MPrefix = '_sockjs_global';
utils.createHook = function () {
var window_id = 'a' + utils.random_string(8);
if (!(MPrefix in _window)) {
var map = {};
_window[MPrefix] = function (window_id) {
if (!(window_id in map)) {
map[window_id] = {
id: window_id,
del: function del() {
delete map[window_id];
}
};
}
return map[window_id];
};
}
return _window[MPrefix](window_id);
};
utils.attachMessage = function (listener) {
utils.attachEvent('message', listener);
};
utils.attachEvent = function (event, listener) {
if (typeof _window.addEventListener !== 'undefined') {
_window.addEventListener(event, listener, false);
} else {
// IE quirks.
// According to: http://stevesouders.com/misc/test-postmessage.php
// the message gets delivered only to 'document', not 'window'.
_document.attachEvent("on" + event, listener);
// I get 'window' for ie8.
_window.attachEvent("on" + event, listener);
}
};
utils.detachMessage = function (listener) {
utils.detachEvent('message', listener);
};
utils.detachEvent = function (event, listener) {
if (typeof _window.addEventListener !== 'undefined') {
_window.removeEventListener(event, listener, false);
} else {
_document.detachEvent("on" + event, listener);
_window.detachEvent("on" + event, listener);
}
};
var on_unload = {};
// Things registered after beforeunload are to be called immediately.
var after_unload = false;
var trigger_unload_callbacks = function trigger_unload_callbacks() {
for (var ref in on_unload) {
on_unload[ref]();
delete on_unload[ref];
};
};
var unload_triggered = function unload_triggered() {
if (after_unload) return;
after_unload = true;
trigger_unload_callbacks();
};
// 'unload' alone is not reliable in opera within an iframe, but we
// can't use `beforeunload` as IE fires it on javascript: links.
utils.attachEvent('unload', unload_triggered);
utils.unload_add = function (listener) {
var ref = utils.random_string(8);
on_unload[ref] = listener;
if (after_unload) {
utils.delay(trigger_unload_callbacks);
}
return ref;
};
utils.unload_del = function (ref) {
if (ref in on_unload) delete on_unload[ref];
};
utils.createIframe = function (iframe_url, error_callback) {
var iframe = _document.createElement('iframe');
var tref, unload_ref;
var unattach = function unattach() {
clearTimeout(tref);
// Explorer had problems with that.
try {
iframe.onload = null;
} catch (x) {}
iframe.onerror = null;
};
var cleanup = function cleanup() {
if (iframe) {
unattach();
// This timeout makes chrome fire onbeforeunload event
// within iframe. Without the timeout it goes straight to
// onunload.
setTimeout(function () {
if (iframe) {
iframe.parentNode.removeChild(iframe);
}
iframe = null;
}, 0);
utils.unload_del(unload_ref);
}
};
var onerror = function onerror(r) {
if (iframe) {
cleanup();
error_callback(r);
}
};
var post = function post(msg, origin) {
try {
// When the iframe is not loaded, IE raises an exception
// on 'contentWindow'.
if (iframe && iframe.contentWindow) {
iframe.contentWindow.postMessage(msg, origin);
}
} catch (x) {};
};
iframe.src = iframe_url;
iframe.style.display = 'none';
iframe.style.position = 'absolute';
iframe.onerror = function () {
onerror('onerror');
};
iframe.onload = function () {
// `onload` is triggered before scripts on the iframe are
// executed. Give it few seconds to actually load stuff.
clearTimeout(tref);
tref = setTimeout(function () {
onerror('onload timeout');
}, 2000);
};
_document.body.appendChild(iframe);
tref = setTimeout(function () {
onerror('timeout');
}, 15000);
unload_ref = utils.unload_add(cleanup);
return {
post: post,
cleanup: cleanup,
loaded: unattach
};
};
utils.createHtmlfile = function (iframe_url, error_callback) {
var doc = new ActiveXObject('htmlfile');
var tref, unload_ref;
var iframe;
var unattach = function unattach() {
clearTimeout(tref);
};
var cleanup = function cleanup() {
if (doc) {
unattach();
utils.unload_del(unload_ref);
iframe.parentNode.removeChild(iframe);
iframe = doc = null;
CollectGarbage();
}
};
var onerror = function onerror(r) {
if (doc) {
cleanup();
error_callback(r);
}
};
var post = function post(msg, origin) {
try {
// When the iframe is not loaded, IE raises an exception
// on 'contentWindow'.
if (iframe && iframe.contentWindow) {
iframe.contentWindow.postMessage(msg, origin);
}
} catch (x) {};
};
doc.open();
doc.write('<html><s' + 'cript>' + 'document.domain="' + document.domain + '";' + '</s' + 'cript></html>');
doc.close();
doc.parentWindow[WPrefix] = _window[WPrefix];
var c = doc.createElement('div');
doc.body.appendChild(c);
iframe = doc.createElement('iframe');
c.appendChild(iframe);
iframe.src = iframe_url;
tref = setTimeout(function () {
onerror('timeout');
}, 15000);
unload_ref = utils.unload_add(cleanup);
return {
post: post,
cleanup: cleanup,
loaded: unattach
};
};
// [*] End of lib/dom.js
// [*] Including lib/dom2.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var AbstractXHRObject = function AbstractXHRObject() {};
AbstractXHRObject.prototype = new EventEmitter(['chunk', 'finish']);
AbstractXHRObject.prototype._start = function (method, url, payload, opts) {
var that = this;
try {
that.xhr = new XMLHttpRequest();
} catch (x) {};
if (!that.xhr) {
try {
that.xhr = new _window.ActiveXObject('Microsoft.XMLHTTP');
} catch (x) {};
}
if (_window.ActiveXObject || _window.XDomainRequest) {
// IE8 caches even POSTs
url += (url.indexOf('?') === -1 ? '?' : '&') + 't=' + +new Date();
}
// Explorer tends to keep connection open, even after the
// tab gets closed: http://bugs.jquery.com/ticket/5280
that.unload_ref = utils.unload_add(function () {
that._cleanup(true);
});
try {
that.xhr.open(method, url, true);
} catch (e) {
// IE raises an exception on wrong port.
that.emit('finish', 0, '');
that._cleanup();
return;
};
if (!opts || !opts.no_credentials) {
// Mozilla docs says https://developer.mozilla.org/en/XMLHttpRequest :
// "This never affects same-site requests."
that.xhr.withCredentials = 'true';
}
if (opts && opts.headers) {
for (var key in opts.headers) {
that.xhr.setRequestHeader(key, opts.headers[key]);
}
}
that.xhr.onreadystatechange = function () {
if (that.xhr) {
var x = that.xhr;
switch (x.readyState) {
case 3:
// IE doesn't like peeking into responseText or status
// on Microsoft.XMLHTTP and readystate=3
try {
var status = x.status;
var text = x.responseText;
} catch (x) {};
// IE returns 1223 for 204: http://bugs.jquery.com/ticket/1450
if (status === 1223) status = 204;
// IE does return readystate == 3 for 404 answers.
if (text && text.length > 0) {
that.emit('chunk', status, text);
}
break;
case 4:
var status = x.status;
// IE returns 1223 for 204: http://bugs.jquery.com/ticket/1450
if (status === 1223) status = 204;
that.emit('finish', status, x.responseText);
that._cleanup(false);
break;
}
}
};
that.xhr.send(payload);
};
AbstractXHRObject.prototype._cleanup = function (abort) {
var that = this;
if (!that.xhr) return;
utils.unload_del(that.unload_ref);
// IE needs this field to be a function
that.xhr.onreadystatechange = function () {};
if (abort) {
try {
that.xhr.abort();
} catch (x) {};
}
that.unload_ref = that.xhr = null;
};
AbstractXHRObject.prototype.close = function () {
var that = this;
that.nuke();
that._cleanup(true);
};
var XHRCorsObject = utils.XHRCorsObject = function () {
var that = this,
args = arguments;
utils.delay(function () {
that._start.apply(that, args);
});
};
XHRCorsObject.prototype = new AbstractXHRObject();
var XHRLocalObject = utils.XHRLocalObject = function (method, url, payload) {
var that = this;
utils.delay(function () {
that._start(method, url, payload, {
no_credentials: true
});
});
};
XHRLocalObject.prototype = new AbstractXHRObject();
// References:
// http://ajaxian.com/archives/100-line-ajax-wrapper
// http://msdn.microsoft.com/en-us/library/cc288060(v=VS.85).aspx
var XDRObject = utils.XDRObject = function (method, url, payload) {
var that = this;
utils.delay(function () {
that._start(method, url, payload);
});
};
XDRObject.prototype = new EventEmitter(['chunk', 'finish']);
XDRObject.prototype._start = function (method, url, payload) {
var that = this;
var xdr = new XDomainRequest();
// IE caches even POSTs
url += (url.indexOf('?') === -1 ? '?' : '&') + 't=' + +new Date();
var onerror = xdr.ontimeout = xdr.onerror = function () {
that.emit('finish', 0, '');
that._cleanup(false);
};
xdr.onprogress = function () {
that.emit('chunk', 200, xdr.responseText);
};
xdr.onload = function () {
that.emit('finish', 200, xdr.responseText);
that._cleanup(false);
};
that.xdr = xdr;
that.unload_ref = utils.unload_add(function () {
that._cleanup(true);
});
try {
// Fails with AccessDenied if port number is bogus
that.xdr.open(method, url);
that.xdr.send(payload);
} catch (x) {
onerror();
}
};
XDRObject.prototype._cleanup = function (abort) {
var that = this;
if (!that.xdr) return;
utils.unload_del(that.unload_ref);
that.xdr.ontimeout = that.xdr.onerror = that.xdr.onprogress = that.xdr.onload = null;
if (abort) {
try {
that.xdr.abort();
} catch (x) {};
}
that.unload_ref = that.xdr = null;
};
XDRObject.prototype.close = function () {
var that = this;
that.nuke();
that._cleanup(true);
};
// 1. Is natively via XHR
// 2. Is natively via XDR
// 3. Nope, but postMessage is there so it should work via the Iframe.
// 4. Nope, sorry.
utils.isXHRCorsCapable = function () {
if (_window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()) {
return 1;
}
// XDomainRequest doesn't work if page is served from file://
if (_window.XDomainRequest && _document.domain) {
return 2;
}
if (IframeTransport.enabled()) {
return 3;
}
return 4;
};
// [*] End of lib/dom2.js
// [*] Including lib/sockjs.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var SockJS = function SockJS(url, dep_protocols_whitelist, options) {
if (this === _window) {
// makes `new` optional
return new SockJS(url, dep_protocols_whitelist, options);
}
var that = this,
protocols_whitelist;
that._options = { devel: false, debug: false, protocols_whitelist: [],
info: undefined, rtt: undefined };
if (options) {
utils.objectExtend(that._options, options);
}
that._base_url = utils.amendUrl(url);
that._server = that._options.server || utils.random_number_string(1000);
if (that._options.protocols_whitelist && that._options.protocols_whitelist.length) {
protocols_whitelist = that._options.protocols_whitelist;
} else {
// Deprecated API
if (typeof dep_protocols_whitelist === 'string' && dep_protocols_whitelist.length > 0) {
protocols_whitelist = [dep_protocols_whitelist];
} else if (utils.isArray(dep_protocols_whitelist)) {
protocols_whitelist = dep_protocols_whitelist;
} else {
protocols_whitelist = null;
}
if (protocols_whitelist) {
that._debug('Deprecated API: Use "protocols_whitelist" option ' + 'instead of supplying protocol list as a second ' + 'parameter to SockJS constructor.');
}
}
that._protocols = [];
that.protocol = null;
that.readyState = SockJS.CONNECTING;
that._ir = createInfoReceiver(that._base_url);
that._ir.onfinish = function (info, rtt) {
that._ir = null;
if (info) {
if (that._options.info) {
// Override if user supplies the option
info = utils.objectExtend(info, that._options.info);
}
if (that._options.rtt) {
rtt = that._options.rtt;
}
that._applyInfo(info, rtt, protocols_whitelist);
that._didClose();
} else {
that._didClose(1002, 'Can\'t connect to server', true);
}
};
};
// Inheritance
SockJS.prototype = new REventTarget();
SockJS.version = "0.3.4";
SockJS.CONNECTING = 0;
SockJS.OPEN = 1;
SockJS.CLOSING = 2;
SockJS.CLOSED = 3;
SockJS.prototype._debug = function () {
if (this._options.debug) utils.log.apply(utils, arguments);
};
SockJS.prototype._dispatchOpen = function () {
var that = this;
if (that.readyState === SockJS.CONNECTING) {
if (that._transport_tref) {
clearTimeout(that._transport_tref);
that._transport_tref = null;
}
that.readyState = SockJS.OPEN;
that.dispatchEvent(new SimpleEvent("open"));
} else {
// The server might have been restarted, and lost track of our
// connection.
that._didClose(1006, "Server lost session");
}
};
SockJS.prototype._dispatchMessage = function (data) {
var that = this;
if (that.readyState !== SockJS.OPEN) return;
that.dispatchEvent(new SimpleEvent("message", { data: data }));
};
SockJS.prototype._dispatchHeartbeat = function (data) {
var that = this;
if (that.readyState !== SockJS.OPEN) return;
that.dispatchEvent(new SimpleEvent('heartbeat', {}));
};
SockJS.prototype._didClose = function (code, reason, force) {
var that = this;
if (that.readyState !== SockJS.CONNECTING && that.readyState !== SockJS.OPEN && that.readyState !== SockJS.CLOSING) throw new Error('INVALID_STATE_ERR');
if (that._ir) {
that._ir.nuke();
that._ir = null;
}
if (that._transport) {
that._transport.doCleanup();
that._transport = null;
}
var close_event = new SimpleEvent("close", {
code: code,
reason: reason,
wasClean: utils.userSetCode(code) });
if (!utils.userSetCode(code) && that.readyState === SockJS.CONNECTING && !force) {
if (that._try_next_protocol(close_event)) {
return;
}
close_event = new SimpleEvent("close", { code: 2000,
reason: "All transports failed",
wasClean: false,
last_event: close_event });
}
that.readyState = SockJS.CLOSED;
utils.delay(function () {
that.dispatchEvent(close_event);
});
};
SockJS.prototype._didMessage = function (data) {
var that = this;
var type = data.slice(0, 1);
switch (type) {
case 'o':
that._dispatchOpen();
break;
case 'a':
var payload = JSON.parse(data.slice(1) || '[]');
for (var i = 0; i < payload.length; i++) {
that._dispatchMessage(payload[i]);
}
break;
case 'm':
var payload = JSON.parse(data.slice(1) || 'null');
that._dispatchMessage(payload);
break;
case 'c':
var payload = JSON.parse(data.slice(1) || '[]');
that._didClose(payload[0], payload[1]);
break;
case 'h':
that._dispatchHeartbeat();
break;
}
};
SockJS.prototype._try_next_protocol = function (close_event) {
var that = this;
if (that.protocol) {
that._debug('Closed transport:', that.protocol, '' + close_event);
that.protocol = null;
}
if (that._transport_tref) {
clearTimeout(that._transport_tref);
that._transport_tref = null;
}
while (1) {
var protocol = that.protocol = that._protocols.shift();
if (!protocol) {
return false;
}
// Some protocols require access to `body`, what if were in
// the `head`?
if (SockJS[protocol] && SockJS[protocol].need_body === true && (!_document.body || typeof _document.readyState !== 'undefined' && _document.readyState !== 'complete')) {
that._protocols.unshift(protocol);
that.protocol = 'waiting-for-load';
utils.attachEvent('load', function () {
that._try_next_protocol();
});
return true;
}
if (!SockJS[protocol] || !SockJS[protocol].enabled(that._options)) {
that._debug('Skipping transport:', protocol);
} else {
var roundTrips = SockJS[protocol].roundTrips || 1;
var to = (that._options.rto || 0) * roundTrips || 5000;
that._transport_tref = utils.delay(to, function () {
if (that.readyState === SockJS.CONNECTING) {
// I can't understand how it is possible to run
// this timer, when the state is CLOSED, but
// apparently in IE everythin is possible.
that._didClose(2007, "Transport timeouted");
}
});
var connid = utils.random_string(8);
var trans_url = that._base_url + '/' + that._server + '/' + connid;
that._debug('Opening transport:', protocol, ' url:' + trans_url, ' RTO:' + that._options.rto);
that._transport = new SockJS[protocol](that, trans_url, that._base_url);
return true;
}
}
};
SockJS.prototype.close = function (code, reason) {
var that = this;
if (code && !utils.userSetCode(code)) throw new Error("INVALID_ACCESS_ERR");
if (that.readyState !== SockJS.CONNECTING && that.readyState !== SockJS.OPEN) {
return false;
}
that.readyState = SockJS.CLOSING;
that._didClose(code || 1000, reason || "Normal closure");
return true;
};
SockJS.prototype.send = function (data) {
var that = this;
if (that.readyState === SockJS.CONNECTING) throw new Error('INVALID_STATE_ERR');
if (that.readyState === SockJS.OPEN) {
that._transport.doSend(utils.quote('' + data));
}
return true;
};
SockJS.prototype._applyInfo = function (info, rtt, protocols_whitelist) {
var that = this;
that._options.info = info;
that._options.rtt = rtt;
that._options.rto = utils.countRTO(rtt);
that._options.info.null_origin = !_document.domain;
var probed = utils.probeProtocols();
that._protocols = utils.detectProtocols(probed, protocols_whitelist, info);
};
// [*] End of lib/sockjs.js
// [*] Including lib/trans-websocket.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var WebSocketTransport = SockJS.websocket = function (ri, trans_url) {
var that = this;
var url = trans_url + '/websocket';
if (url.slice(0, 5) === 'https') {
url = 'wss' + url.slice(5);
} else {
url = 'ws' + url.slice(4);
}
that.ri = ri;
that.url = url;
var Constructor = _window.WebSocket || _window.MozWebSocket;
that.ws = new Constructor(that.url);
that.ws.onmessage = function (e) {
that.ri._didMessage(e.data);
};
// Firefox has an interesting bug. If a websocket connection is
// created after onunload, it stays alive even when user
// navigates away from the page. In such situation let's lie -
// let's not open the ws connection at all. See:
// https://github.com/sockjs/sockjs-client/issues/28
// https://bugzilla.mozilla.org/show_bug.cgi?id=696085
that.unload_ref = utils.unload_add(function () {
that.ws.close();
});
that.ws.onclose = function () {
that.ri._didMessage(utils.closeFrame(1006, "WebSocket connection broken"));
};
};
WebSocketTransport.prototype.doSend = function (data) {
this.ws.send('[' + data + ']');
};
WebSocketTransport.prototype.doCleanup = function () {
var that = this;
var ws = that.ws;
if (ws) {
ws.onmessage = ws.onclose = null;
ws.close();
utils.unload_del(that.unload_ref);
that.unload_ref = that.ri = that.ws = null;
}
};
WebSocketTransport.enabled = function () {
return !!(_window.WebSocket || _window.MozWebSocket);
};
// In theory, ws should require 1 round trip. But in chrome, this is
// not very stable over SSL. Most likely a ws connection requires a
// separate SSL connection, in which case 2 round trips are an
// absolute minumum.
WebSocketTransport.roundTrips = 2;
// [*] End of lib/trans-websocket.js
// [*] Including lib/trans-sender.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var BufferedSender = function BufferedSender() {};
BufferedSender.prototype.send_constructor = function (sender) {
var that = this;
that.send_buffer = [];
that.sender = sender;
};
BufferedSender.prototype.doSend = function (message) {
var that = this;
that.send_buffer.push(message);
if (!that.send_stop) {
that.send_schedule();
}
};
// For polling transports in a situation when in the message callback,
// new message is being send. If the sending connection was started
// before receiving one, it is possible to saturate the network and
// timeout due to the lack of receiving socket. To avoid that we delay
// sending messages by some small time, in order to let receiving
// connection be started beforehand. This is only a halfmeasure and
// does not fix the big problem, but it does make the tests go more
// stable on slow networks.
BufferedSender.prototype.send_schedule_wait = function () {
var that = this;
var tref;
that.send_stop = function () {
that.send_stop = null;
clearTimeout(tref);
};
tref = utils.delay(25, function () {
that.send_stop = null;
that.send_schedule();
});
};
BufferedSender.prototype.send_schedule = function () {
var that = this;
if (that.send_buffer.length > 0) {
var payload = '[' + that.send_buffer.join(',') + ']';
that.send_stop = that.sender(that.trans_url, payload, function (success, abort_reason) {
that.send_stop = null;
if (success === false) {
that.ri._didClose(1006, 'Sending error ' + abort_reason);
} else {
that.send_schedule_wait();
}
});
that.send_buffer = [];
}
};
BufferedSender.prototype.send_destructor = function () {
var that = this;
if (that._send_stop) {
that._send_stop();
}
that._send_stop = null;
};
var jsonPGenericSender = function jsonPGenericSender(url, payload, callback) {
var that = this;
if (!('_send_form' in that)) {
var form = that._send_form = _document.createElement('form');
var area = that._send_area = _document.createElement('textarea');
area.name = 'd';
form.style.display = 'none';
form.style.position = 'absolute';
form.method = 'POST';
form.enctype = 'application/x-www-form-urlencoded';
form.acceptCharset = "UTF-8";
form.appendChild(area);
_document.body.appendChild(form);
}
var form = that._send_form;
var area = that._send_area;
var id = 'a' + utils.random_string(8);
form.target = id;
form.action = url + '/jsonp_send?i=' + id;
var iframe;
try {
// ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
iframe = _document.createElement('<iframe name="' + id + '">');
} catch (x) {
iframe = _document.createElement('iframe');
iframe.name = id;
}
iframe.id = id;
form.appendChild(iframe);
iframe.style.display = 'none';
try {
area.value = payload;
} catch (e) {
utils.log('Your browser is seriously broken. Go home! ' + e.message);
}
form.submit();
var completed = function completed(e) {
if (!iframe.onerror) return;
iframe.onreadystatechange = iframe.onerror = iframe.onload = null;
// Opera mini doesn't like if we GC iframe
// immediately, thus this timeout.
utils.delay(500, function () {
iframe.parentNode.removeChild(iframe);
iframe = null;
});
area.value = '';
// It is not possible to detect if the iframe succeeded or
// failed to submit our form.
callback(true);
};
iframe.onerror = iframe.onload = completed;
iframe.onreadystatechange = function (e) {
if (iframe.readyState == 'complete') completed();
};
return completed;
};
var createAjaxSender = function createAjaxSender(AjaxObject) {
return function (url, payload, callback) {
var xo = new AjaxObject('POST', url + '/xhr_send', payload);
xo.onfinish = function (status, text) {
callback(status === 200 || status === 204, 'http status ' + status);
};
return function (abort_reason) {
callback(false, abort_reason);
};
};
};
// [*] End of lib/trans-sender.js
// [*] Including lib/trans-jsonp-receiver.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
// Parts derived from Socket.io:
// https://github.com/LearnBoost/socket.io/blob/0.6.17/lib/socket.io/transports/jsonp-polling.js
// and jQuery-JSONP:
// https://code.google.com/p/jquery-jsonp/source/browse/trunk/core/jquery.jsonp.js
var jsonPGenericReceiver = function jsonPGenericReceiver(url, callback) {
var tref;
var script = _document.createElement('script');
var script2; // Opera synchronous load trick.
var close_script = function close_script(frame) {
if (script2) {
script2.parentNode.removeChild(script2);
script2 = null;
}
if (script) {
clearTimeout(tref);
// Unfortunately, you can't really abort script loading of
// the script.
script.parentNode.removeChild(script);
script.onreadystatechange = script.onerror = script.onload = script.onclick = null;
script = null;
callback(frame);
callback = null;
}
};
// IE9 fires 'error' event after orsc or before, in random order.
var loaded_okay = false;
var error_timer = null;
script.id = 'a' + utils.random_string(8);
script.src = url;
script.type = 'text/javascript';
script.charset = 'UTF-8';
script.onerror = function (e) {
if (!error_timer) {
// Delay firing close_script.
error_timer = setTimeout(function () {
if (!loaded_okay) {
close_script(utils.closeFrame(1006, "JSONP script loaded abnormally (onerror)"));
}
}, 1000);
}
};
script.onload = function (e) {
close_script(utils.closeFrame(1006, "JSONP script loaded abnormally (onload)"));
};
script.onreadystatechange = function (e) {
if (/loaded|closed/.test(script.readyState)) {
if (script && script.htmlFor && script.onclick) {
loaded_okay = true;
try {
// In IE, actually execute the script.
script.onclick();
} catch (x) {}
}
if (script) {
close_script(utils.closeFrame(1006, "JSONP script loaded abnormally (onreadystatechange)"));
}
}
};
// IE: event/htmlFor/onclick trick.
// One can't rely on proper order for onreadystatechange. In order to
// make sure, set a 'htmlFor' and 'event' properties, so that
// script code will be installed as 'onclick' handler for the
// script object. Later, onreadystatechange, manually execute this
// code. FF and Chrome doesn't work with 'event' and 'htmlFor'
// set. For reference see:
// http://jaubourg.net/2010/07/loading-script-as-onclick-handler-of.html
// Also, read on that about script ordering:
// http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
if (typeof script.async === 'undefined' && _document.attachEvent) {
// According to mozilla docs, in recent browsers script.async defaults
// to 'true', so we may use it to detect a good browser:
// https://developer.mozilla.org/en/HTML/Element/script
if (!/opera/i.test(navigator.userAgent)) {
// Naively assume we're in IE
try {
script.htmlFor = script.id;
script.event = "onclick";
} catch (x) {}
script.async = true;
} else {
// Opera, second sync script hack
script2 = _document.createElement('script');
script2.text = "try{var a = document.getElementById('" + script.id + "'); if(a)a.onerror();}catch(x){};";
script.async = script2.async = false;
}
}
if (typeof script.async !== 'undefined') {
script.async = true;
}
// Fallback mostly for Konqueror - stupid timer, 35 seconds shall be plenty.
tref = setTimeout(function () {
close_script(utils.closeFrame(1006, "JSONP script loaded abnormally (timeout)"));
}, 35000);
var head = _document.getElementsByTagName('head')[0];
head.insertBefore(script, head.firstChild);
if (script2) {
head.insertBefore(script2, head.firstChild);
}
return close_script;
};
// [*] End of lib/trans-jsonp-receiver.js
// [*] Including lib/trans-jsonp-polling.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
// The simplest and most robust transport, using the well-know cross
// domain hack - JSONP. This transport is quite inefficient - one
// mssage could use up to one http request. But at least it works almost
// everywhere.
// Known limitations:
// o you will get a spinning cursor
// o for Konqueror a dumb timer is needed to detect errors
var JsonPTransport = SockJS['jsonp-polling'] = function (ri, trans_url) {
utils.polluteGlobalNamespace();
var that = this;
that.ri = ri;
that.trans_url = trans_url;
that.send_constructor(jsonPGenericSender);
that._schedule_recv();
};
// Inheritnace
JsonPTransport.prototype = new BufferedSender();
JsonPTransport.prototype._schedule_recv = function () {
var that = this;
var callback = function callback(data) {
that._recv_stop = null;
if (data) {
// no data - heartbeat;
if (!that._is_closing) {
that.ri._didMessage(data);
}
}
// The message can be a close message, and change is_closing state.
if (!that._is_closing) {
that._schedule_recv();
}
};
that._recv_stop = jsonPReceiverWrapper(that.trans_url + '/jsonp', jsonPGenericReceiver, callback);
};
JsonPTransport.enabled = function () {
return true;
};
JsonPTransport.need_body = true;
JsonPTransport.prototype.doCleanup = function () {
var that = this;
that._is_closing = true;
if (that._recv_stop) {
that._recv_stop();
}
that.ri = that._recv_stop = null;
that.send_destructor();
};
// Abstract away code that handles global namespace pollution.
var jsonPReceiverWrapper = function jsonPReceiverWrapper(url, constructReceiver, user_callback) {
var id = 'a' + utils.random_string(6);
var url_id = url + '?c=' + escape(WPrefix + '.' + id);
// Unfortunately it is not possible to abort loading of the
// script. We need to keep track of frake close frames.
var aborting = 0;
// Callback will be called exactly once.
var callback = function callback(frame) {
switch (aborting) {
case 0:
// Normal behaviour - delete hook _and_ emit message.
delete _window[WPrefix][id];
user_callback(frame);
break;
case 1:
// Fake close frame - emit but don't delete hook.
user_callback(frame);
aborting = 2;
break;
case 2:
// Got frame after connection was closed, delete hook, don't emit.
delete _window[WPrefix][id];
break;
}
};
var close_script = constructReceiver(url_id, callback);
_window[WPrefix][id] = close_script;
var stop = function stop() {
if (_window[WPrefix][id]) {
aborting = 1;
_window[WPrefix][id](utils.closeFrame(1000, "JSONP user aborted read"));
}
};
return stop;
};
// [*] End of lib/trans-jsonp-polling.js
// [*] Including lib/trans-xhr.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var AjaxBasedTransport = function AjaxBasedTransport() {};
AjaxBasedTransport.prototype = new BufferedSender();
AjaxBasedTransport.prototype.run = function (ri, trans_url, url_suffix, Receiver, AjaxObject) {
var that = this;
that.ri = ri;
that.trans_url = trans_url;
that.send_constructor(createAjaxSender(AjaxObject));
that.poll = new Polling(ri, Receiver, trans_url + url_suffix, AjaxObject);
};
AjaxBasedTransport.prototype.doCleanup = function () {
var that = this;
if (that.poll) {
that.poll.abort();
that.poll = null;
}
};
// xhr-streaming
var XhrStreamingTransport = SockJS['xhr-streaming'] = function (ri, trans_url) {
this.run(ri, trans_url, '/xhr_streaming', XhrReceiver, utils.XHRCorsObject);
};
XhrStreamingTransport.prototype = new AjaxBasedTransport();
XhrStreamingTransport.enabled = function () {
// Support for CORS Ajax aka Ajax2? Opera 12 claims CORS but
// doesn't do streaming.
return _window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest() && !/opera/i.test(navigator.userAgent);
};
XhrStreamingTransport.roundTrips = 2; // preflight, ajax
// Safari gets confused when a streaming ajax request is started
// before onload. This causes the load indicator to spin indefinetely.
XhrStreamingTransport.need_body = true;
// According to:
// http://stackoverflow.com/questions/1641507/detect-browser-support-for-cross-domain-xmlhttprequests
// http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
// xdr-streaming
var XdrStreamingTransport = SockJS['xdr-streaming'] = function (ri, trans_url) {
this.run(ri, trans_url, '/xhr_streaming', XhrReceiver, utils.XDRObject);
};
XdrStreamingTransport.prototype = new AjaxBasedTransport();
XdrStreamingTransport.enabled = function () {
return !!_window.XDomainRequest;
};
XdrStreamingTransport.roundTrips = 2; // preflight, ajax
// xhr-polling
var XhrPollingTransport = SockJS['xhr-polling'] = function (ri, trans_url) {
this.run(ri, trans_url, '/xhr', XhrReceiver, utils.XHRCorsObject);
};
XhrPollingTransport.prototype = new AjaxBasedTransport();
XhrPollingTransport.enabled = XhrStreamingTransport.enabled;
XhrPollingTransport.roundTrips = 2; // preflight, ajax
// xdr-polling
var XdrPollingTransport = SockJS['xdr-polling'] = function (ri, trans_url) {
this.run(ri, trans_url, '/xhr', XhrReceiver, utils.XDRObject);
};
XdrPollingTransport.prototype = new AjaxBasedTransport();
XdrPollingTransport.enabled = XdrStreamingTransport.enabled;
XdrPollingTransport.roundTrips = 2; // preflight, ajax
// [*] End of lib/trans-xhr.js
// [*] Including lib/trans-iframe.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
// Few cool transports do work only for same-origin. In order to make
// them working cross-domain we shall use iframe, served form the
// remote domain. New browsers, have capabilities to communicate with
// cross domain iframe, using postMessage(). In IE it was implemented
// from IE 8+, but of course, IE got some details wrong:
// http://msdn.microsoft.com/en-us/library/cc197015(v=VS.85).aspx
// http://stevesouders.com/misc/test-postmessage.php
var IframeTransport = function IframeTransport() {};
IframeTransport.prototype.i_constructor = function (ri, trans_url, base_url) {
var that = this;
that.ri = ri;
that.origin = utils.getOrigin(base_url);
that.base_url = base_url;
that.trans_url = trans_url;
var iframe_url = base_url + '/iframe.html';
if (that.ri._options.devel) {
iframe_url += '?t=' + +new Date();
}
that.window_id = utils.random_string(8);
iframe_url += '#' + that.window_id;
that.iframeObj = utils.createIframe(iframe_url, function (r) {
that.ri._didClose(1006, "Unable to load an iframe (" + r + ")");
});
that.onmessage_cb = utils.bind(that.onmessage, that);
utils.attachMessage(that.onmessage_cb);
};
IframeTransport.prototype.doCleanup = function () {
var that = this;
if (that.iframeObj) {
utils.detachMessage(that.onmessage_cb);
try {
// When the iframe is not loaded, IE raises an exception
// on 'contentWindow'.
if (that.iframeObj.iframe.contentWindow) {
that.postMessage('c');
}
} catch (x) {}
that.iframeObj.cleanup();
that.iframeObj = null;
that.onmessage_cb = that.iframeObj = null;
}
};
IframeTransport.prototype.onmessage = function (e) {
var that = this;
if (e.origin !== that.origin) return;
var window_id = e.data.slice(0, 8);
var type = e.data.slice(8, 9);
var data = e.data.slice(9);
if (window_id !== that.window_id) return;
switch (type) {
case 's':
that.iframeObj.loaded();
that.postMessage('s', JSON.stringify([SockJS.version, that.protocol, that.trans_url, that.base_url]));
break;
case 't':
that.ri._didMessage(data);
break;
}
};
IframeTransport.prototype.postMessage = function (type, data) {
var that = this;
that.iframeObj.post(that.window_id + type + (data || ''), that.origin);
};
IframeTransport.prototype.doSend = function (message) {
this.postMessage('m', message);
};
IframeTransport.enabled = function () {
// postMessage misbehaves in konqueror 4.6.5 - the messages are delivered with
// huge delay, or not at all.
var konqueror = navigator && navigator.userAgent && navigator.userAgent.indexOf('Konqueror') !== -1;
return (typeof _window.postMessage === 'function' || _typeof(_window.postMessage) === 'object') && !konqueror;
};
// [*] End of lib/trans-iframe.js
// [*] Including lib/trans-iframe-within.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var curr_window_id;
var postMessage = function postMessage(type, data) {
if (parent !== _window) {
parent.postMessage(curr_window_id + type + (data || ''), '*');
} else {
utils.log("Can't postMessage, no parent window.", type, data);
}
};
var FacadeJS = function FacadeJS() {};
FacadeJS.prototype._didClose = function (code, reason) {
postMessage('t', utils.closeFrame(code, reason));
};
FacadeJS.prototype._didMessage = function (frame) {
postMessage('t', frame);
};
FacadeJS.prototype._doSend = function (data) {
this._transport.doSend(data);
};
FacadeJS.prototype._doCleanup = function () {
this._transport.doCleanup();
};
utils.parent_origin = undefined;
SockJS.bootstrap_iframe = function () {
var facade;
curr_window_id = _document.location.hash.slice(1);
var onMessage = function onMessage(e) {
if (e.source !== parent) return;
if (typeof utils.parent_origin === 'undefined') utils.parent_origin = e.origin;
if (e.origin !== utils.parent_origin) return;
var window_id = e.data.slice(0, 8);
var type = e.data.slice(8, 9);
var data = e.data.slice(9);
if (window_id !== curr_window_id) return;
switch (type) {
case 's':
var p = JSON.parse(data);
var version = p[0];
var protocol = p[1];
var trans_url = p[2];
var base_url = p[3];
if (version !== SockJS.version) {
utils.log("Incompatibile SockJS! Main site uses:" + " \"" + version + "\", the iframe:" + " \"" + SockJS.version + "\".");
}
if (!utils.flatUrl(trans_url) || !utils.flatUrl(base_url)) {
utils.log("Only basic urls are supported in SockJS");
return;
}
if (!utils.isSameOriginUrl(trans_url) || !utils.isSameOriginUrl(base_url)) {
utils.log("Can't connect to different domain from within an " + "iframe. (" + JSON.stringify([_window.location.href, trans_url, base_url]) + ")");
return;
}
facade = new FacadeJS();
facade._transport = new FacadeJS[protocol](facade, trans_url, base_url);
break;
case 'm':
facade._doSend(data);
break;
case 'c':
if (facade) facade._doCleanup();
facade = null;
break;
}
};
// alert('test ticker');
// facade = new FacadeJS();
// facade._transport = new FacadeJS['w-iframe-xhr-polling'](facade, 'http://host.com:9999/ticker/12/basd');
utils.attachMessage(onMessage);
// Start
postMessage('s');
};
// [*] End of lib/trans-iframe-within.js
// [*] Including lib/info.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var InfoReceiver = function InfoReceiver(base_url, AjaxObject) {
var that = this;
utils.delay(function () {
that.doXhr(base_url, AjaxObject);
});
};
InfoReceiver.prototype = new EventEmitter(['finish']);
InfoReceiver.prototype.doXhr = function (base_url, AjaxObject) {
var that = this;
var t0 = new Date().getTime();
var xo = new AjaxObject('GET', base_url + '/info');
var tref = utils.delay(8000, function () {
xo.ontimeout();
});
xo.onfinish = function (status, text) {
clearTimeout(tref);
tref = null;
if (status === 200) {
var rtt = new Date().getTime() - t0;
var info = JSON.parse(text);
if ((typeof info === "undefined" ? "undefined" : _typeof(info)) !== 'object') info = {};
that.emit('finish', info, rtt);
} else {
that.emit('finish');
}
};
xo.ontimeout = function () {
xo.close();
that.emit('finish');
};
};
var InfoReceiverIframe = function InfoReceiverIframe(base_url) {
var that = this;
var go = function go() {
var ifr = new IframeTransport();
ifr.protocol = 'w-iframe-info-receiver';
var fun = function fun(r) {
if (typeof r === 'string' && r.substr(0, 1) === 'm') {
var d = JSON.parse(r.substr(1));
var info = d[0],
rtt = d[1];
that.emit('finish', info, rtt);
} else {
that.emit('finish');
}
ifr.doCleanup();
ifr = null;
};
var mock_ri = {
_options: {},
_didClose: fun,
_didMessage: fun
};
ifr.i_constructor(mock_ri, base_url, base_url);
};
if (!_document.body) {
utils.attachEvent('load', go);
} else {
go();
}
};
InfoReceiverIframe.prototype = new EventEmitter(['finish']);
var InfoReceiverFake = function InfoReceiverFake() {
// It may not be possible to do cross domain AJAX to get the info
// data, for example for IE7. But we want to run JSONP, so let's
// fake the response, with rtt=2s (rto=6s).
var that = this;
utils.delay(function () {
that.emit('finish', {}, 2000);
});
};
InfoReceiverFake.prototype = new EventEmitter(['finish']);
var createInfoReceiver = function createInfoReceiver(base_url) {
if (utils.isSameOriginUrl(base_url)) {
// If, for some reason, we have SockJS locally - there's no
// need to start up the complex machinery. Just use ajax.
return new InfoReceiver(base_url, utils.XHRLocalObject);
}
switch (utils.isXHRCorsCapable()) {
case 1:
// XHRLocalObject -> no_credentials=true
return new InfoReceiver(base_url, utils.XHRLocalObject);
case 2:
return new InfoReceiver(base_url, utils.XDRObject);
case 3:
// Opera
return new InfoReceiverIframe(base_url);
default:
// IE 7
return new InfoReceiverFake();
};
};
var WInfoReceiverIframe = FacadeJS['w-iframe-info-receiver'] = function (ri, _trans_url, base_url) {
var ir = new InfoReceiver(base_url, utils.XHRLocalObject);
ir.onfinish = function (info, rtt) {
ri._didMessage('m' + JSON.stringify([info, rtt]));
ri._didClose();
};
};
WInfoReceiverIframe.prototype.doCleanup = function () {};
// [*] End of lib/info.js
// [*] Including lib/trans-iframe-eventsource.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var EventSourceIframeTransport = SockJS['iframe-eventsource'] = function () {
var that = this;
that.protocol = 'w-iframe-eventsource';
that.i_constructor.apply(that, arguments);
};
EventSourceIframeTransport.prototype = new IframeTransport();
EventSourceIframeTransport.enabled = function () {
return 'EventSource' in _window && IframeTransport.enabled();
};
EventSourceIframeTransport.need_body = true;
EventSourceIframeTransport.roundTrips = 3; // html, javascript, eventsource
// w-iframe-eventsource
var EventSourceTransport = FacadeJS['w-iframe-eventsource'] = function (ri, trans_url) {
this.run(ri, trans_url, '/eventsource', EventSourceReceiver, utils.XHRLocalObject);
};
EventSourceTransport.prototype = new AjaxBasedTransport();
// [*] End of lib/trans-iframe-eventsource.js
// [*] Including lib/trans-iframe-xhr-polling.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var XhrPollingIframeTransport = SockJS['iframe-xhr-polling'] = function () {
var that = this;
that.protocol = 'w-iframe-xhr-polling';
that.i_constructor.apply(that, arguments);
};
XhrPollingIframeTransport.prototype = new IframeTransport();
XhrPollingIframeTransport.enabled = function () {
return _window.XMLHttpRequest && IframeTransport.enabled();
};
XhrPollingIframeTransport.need_body = true;
XhrPollingIframeTransport.roundTrips = 3; // html, javascript, xhr
// w-iframe-xhr-polling
var XhrPollingITransport = FacadeJS['w-iframe-xhr-polling'] = function (ri, trans_url) {
this.run(ri, trans_url, '/xhr', XhrReceiver, utils.XHRLocalObject);
};
XhrPollingITransport.prototype = new AjaxBasedTransport();
// [*] End of lib/trans-iframe-xhr-polling.js
// [*] Including lib/trans-iframe-htmlfile.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
// This transport generally works in any browser, but will cause a
// spinning cursor to appear in any browser other than IE.
// We may test this transport in all browsers - why not, but in
// production it should be only run in IE.
var HtmlFileIframeTransport = SockJS['iframe-htmlfile'] = function () {
var that = this;
that.protocol = 'w-iframe-htmlfile';
that.i_constructor.apply(that, arguments);
};
// Inheritance.
HtmlFileIframeTransport.prototype = new IframeTransport();
HtmlFileIframeTransport.enabled = function () {
return IframeTransport.enabled();
};
HtmlFileIframeTransport.need_body = true;
HtmlFileIframeTransport.roundTrips = 3; // html, javascript, htmlfile
// w-iframe-htmlfile
var HtmlFileTransport = FacadeJS['w-iframe-htmlfile'] = function (ri, trans_url) {
this.run(ri, trans_url, '/htmlfile', HtmlfileReceiver, utils.XHRLocalObject);
};
HtmlFileTransport.prototype = new AjaxBasedTransport();
// [*] End of lib/trans-iframe-htmlfile.js
// [*] Including lib/trans-polling.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var Polling = function Polling(ri, Receiver, recv_url, AjaxObject) {
var that = this;
that.ri = ri;
that.Receiver = Receiver;
that.recv_url = recv_url;
that.AjaxObject = AjaxObject;
that._scheduleRecv();
};
Polling.prototype._scheduleRecv = function () {
var that = this;
var poll = that.poll = new that.Receiver(that.recv_url, that.AjaxObject);
var msg_counter = 0;
poll.onmessage = function (e) {
msg_counter += 1;
that.ri._didMessage(e.data);
};
poll.onclose = function (e) {
that.poll = poll = poll.onmessage = poll.onclose = null;
if (!that.poll_is_closing) {
if (e.reason === 'permanent') {
that.ri._didClose(1006, 'Polling error (' + e.reason + ')');
} else {
that._scheduleRecv();
}
}
};
};
Polling.prototype.abort = function () {
var that = this;
that.poll_is_closing = true;
if (that.poll) {
that.poll.abort();
}
};
// [*] End of lib/trans-polling.js
// [*] Including lib/trans-receiver-eventsource.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var EventSourceReceiver = function EventSourceReceiver(url) {
var that = this;
var es = new EventSource(url);
es.onmessage = function (e) {
that.dispatchEvent(new SimpleEvent('message', { 'data': unescape(e.data) }));
};
that.es_close = es.onerror = function (e, abort_reason) {
// ES on reconnection has readyState = 0 or 1.
// on network error it's CLOSED = 2
var reason = abort_reason ? 'user' : es.readyState !== 2 ? 'network' : 'permanent';
that.es_close = es.onmessage = es.onerror = null;
// EventSource reconnects automatically.
es.close();
es = null;
// Safari and chrome < 15 crash if we close window before
// waiting for ES cleanup. See:
// https://code.google.com/p/chromium/issues/detail?id=89155
utils.delay(200, function () {
that.dispatchEvent(new SimpleEvent('close', { reason: reason }));
});
};
};
EventSourceReceiver.prototype = new REventTarget();
EventSourceReceiver.prototype.abort = function () {
var that = this;
if (that.es_close) {
that.es_close({}, true);
}
};
// [*] End of lib/trans-receiver-eventsource.js
// [*] Including lib/trans-receiver-htmlfile.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var _is_ie_htmlfile_capable;
var isIeHtmlfileCapable = function isIeHtmlfileCapable() {
if (_is_ie_htmlfile_capable === undefined) {
if ('ActiveXObject' in _window) {
try {
_is_ie_htmlfile_capable = !!new ActiveXObject('htmlfile');
} catch (x) {}
} else {
_is_ie_htmlfile_capable = false;
}
}
return _is_ie_htmlfile_capable;
};
var HtmlfileReceiver = function HtmlfileReceiver(url) {
var that = this;
utils.polluteGlobalNamespace();
that.id = 'a' + utils.random_string(6, 26);
url += (url.indexOf('?') === -1 ? '?' : '&') + 'c=' + escape(WPrefix + '.' + that.id);
var constructor = isIeHtmlfileCapable() ? utils.createHtmlfile : utils.createIframe;
var iframeObj;
_window[WPrefix][that.id] = {
start: function start() {
iframeObj.loaded();
},
message: function message(data) {
that.dispatchEvent(new SimpleEvent('message', { 'data': data }));
},
stop: function stop() {
that.iframe_close({}, 'network');
}
};
that.iframe_close = function (e, abort_reason) {
iframeObj.cleanup();
that.iframe_close = iframeObj = null;
delete _window[WPrefix][that.id];
that.dispatchEvent(new SimpleEvent('close', { reason: abort_reason }));
};
iframeObj = constructor(url, function (e) {
that.iframe_close({}, 'permanent');
});
};
HtmlfileReceiver.prototype = new REventTarget();
HtmlfileReceiver.prototype.abort = function () {
var that = this;
if (that.iframe_close) {
that.iframe_close({}, 'user');
}
};
// [*] End of lib/trans-receiver-htmlfile.js
// [*] Including lib/trans-receiver-xhr.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var XhrReceiver = function XhrReceiver(url, AjaxObject) {
var that = this;
var buf_pos = 0;
that.xo = new AjaxObject('POST', url, null);
that.xo.onchunk = function (status, text) {
if (status !== 200) return;
while (1) {
var buf = text.slice(buf_pos);
var p = buf.indexOf('\n');
if (p === -1) break;
buf_pos += p + 1;
var msg = buf.slice(0, p);
that.dispatchEvent(new SimpleEvent('message', { data: msg }));
}
};
that.xo.onfinish = function (status, text) {
that.xo.onchunk(status, text);
that.xo = null;
var reason = status === 200 ? 'network' : 'permanent';
that.dispatchEvent(new SimpleEvent('close', { reason: reason }));
};
};
XhrReceiver.prototype = new REventTarget();
XhrReceiver.prototype.abort = function () {
var that = this;
if (that.xo) {
that.xo.close();
that.dispatchEvent(new SimpleEvent('close', { reason: 'user' }));
that.xo = null;
}
};
// [*] End of lib/trans-receiver-xhr.js
// [*] Including lib/test-hooks.js
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
// For testing
SockJS.getUtils = function () {
return utils;
};
SockJS.getIframeTransport = function () {
return IframeTransport;
};
// [*] End of lib/test-hooks.js
return SockJS;
}();
if (typeof window !== 'undefined' && '_sockjs_onload' in window) setTimeout(_sockjs_onload, 1);
if (typeof exports !== "undefined" && exports !== null) {
exports.SockJS = SockJS;
}
// [*] End of lib/index.js
// [*] End of lib/all.js
},{}],22:[function(require,module,exports){
'use strict';
// Generated by CoffeeScript 1.7.1
/*
Stomp Over WebSocket http://www.jmesnil.net/stomp-websocket/doc/ | Apache License V2.0
Copyright (C) 2010-2013 [Jeff Mesnil](http://jmesnil.net/)
Copyright (C) 2012 [FuseSource, Inc.](http://fusesource.com)
*/
(function () {
var Byte,
Client,
Frame,
Stomp,
__hasProp = {}.hasOwnProperty,
__slice = [].slice;
Byte = {
LF: '\x0A',
NULL: '\x00'
};
Frame = function () {
var unmarshallSingle;
function Frame(command, headers, body) {
this.command = command;
this.headers = headers != null ? headers : {};
this.body = body != null ? body : '';
}
Frame.prototype.toString = function () {
var lines, name, skipContentLength, value, _ref;
lines = [this.command];
skipContentLength = this.headers['content-length'] === false ? true : false;
if (skipContentLength) {
delete this.headers['content-length'];
}
_ref = this.headers;
for (name in _ref) {
if (!__hasProp.call(_ref, name)) continue;
value = _ref[name];
lines.push("" + name + ":" + value);
}
if (this.body && !skipContentLength) {
lines.push("content-length:" + Frame.sizeOfUTF8(this.body));
}
lines.push(Byte.LF + this.body);
return lines.join(Byte.LF);
};
Frame.sizeOfUTF8 = function (s) {
if (s) {
return encodeURI(s).match(/%..|./g).length;
} else {
return 0;
}
};
unmarshallSingle = function unmarshallSingle(data) {
var body, chr, command, divider, headerLines, headers, i, idx, len, line, start, trim, _i, _j, _len, _ref, _ref1;
divider = data.search(RegExp("" + Byte.LF + Byte.LF));
headerLines = data.substring(0, divider).split(Byte.LF);
command = headerLines.shift();
headers = {};
trim = function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
};
_ref = headerLines.reverse();
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
line = _ref[_i];
idx = line.indexOf(':');
headers[trim(line.substring(0, idx))] = trim(line.substring(idx + 1));
}
body = '';
start = divider + 2;
if (headers['content-length']) {
len = parseInt(headers['content-length']);
body = ('' + data).substring(start, start + len);
} else {
chr = null;
for (i = _j = start, _ref1 = data.length; start <= _ref1 ? _j < _ref1 : _j > _ref1; i = start <= _ref1 ? ++_j : --_j) {
chr = data.charAt(i);
if (chr === Byte.NULL) {
break;
}
body += chr;
}
}
return new Frame(command, headers, body);
};
Frame.unmarshall = function (datas) {
var frame, frames, last_frame, r;
frames = datas.split(RegExp("" + Byte.NULL + Byte.LF + "*"));
r = {
frames: [],
partial: ''
};
r.frames = function () {
var _i, _len, _ref, _results;
_ref = frames.slice(0, -1);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
frame = _ref[_i];
_results.push(unmarshallSingle(frame));
}
return _results;
}();
last_frame = frames.slice(-1)[0];
if (last_frame === Byte.LF || last_frame.search(RegExp("" + Byte.NULL + Byte.LF + "*$")) !== -1) {
r.frames.push(unmarshallSingle(last_frame));
} else {
r.partial = last_frame;
}
return r;
};
Frame.marshall = function (command, headers, body) {
var frame;
frame = new Frame(command, headers, body);
return frame.toString() + Byte.NULL;
};
return Frame;
}();
Client = function () {
var now;
function Client(ws) {
this.ws = ws;
this.ws.binaryType = "arraybuffer";
this.counter = 0;
this.connected = false;
this.heartbeat = {
outgoing: 10000,
incoming: 10000
};
this.maxWebSocketFrameSize = 16 * 1024;
this.subscriptions = {};
this.partialData = '';
}
Client.prototype.debug = function (message) {
var _ref;
return typeof window !== "undefined" && window !== null ? (_ref = window.console) != null ? _ref.log(message) : void 0 : void 0;
};
now = function now() {
if (Date.now) {
return Date.now();
} else {
return new Date().valueOf;
}
};
Client.prototype._transmit = function (command, headers, body) {
var out;
out = Frame.marshall(command, headers, body);
if (typeof this.debug === "function") {
this.debug(">>> " + out);
}
while (true) {
if (out.length > this.maxWebSocketFrameSize) {
this.ws.send(out.substring(0, this.maxWebSocketFrameSize));
out = out.substring(this.maxWebSocketFrameSize);
if (typeof this.debug === "function") {
this.debug("remaining = " + out.length);
}
} else {
return this.ws.send(out);
}
}
};
Client.prototype._setupHeartbeat = function (headers) {
var serverIncoming, serverOutgoing, ttl, v, _ref, _ref1;
if ((_ref = headers.version) !== Stomp.VERSIONS.V1_1 && _ref !== Stomp.VERSIONS.V1_2) {
return;
}
_ref1 = function () {
var _i, _len, _ref1, _results;
_ref1 = headers['heart-beat'].split(",");
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
v = _ref1[_i];
_results.push(parseInt(v));
}
return _results;
}(), serverOutgoing = _ref1[0], serverIncoming = _ref1[1];
if (!(this.heartbeat.outgoing === 0 || serverIncoming === 0)) {
ttl = Math.max(this.heartbeat.outgoing, serverIncoming);
if (typeof this.debug === "function") {
this.debug("send PING every " + ttl + "ms");
}
this.pinger = Stomp.setInterval(ttl, function (_this) {
return function () {
_this.ws.send(Byte.LF);
return typeof _this.debug === "function" ? _this.debug(">>> PING") : void 0;
};
}(this));
}
if (!(this.heartbeat.incoming === 0 || serverOutgoing === 0)) {
ttl = Math.max(this.heartbeat.incoming, serverOutgoing);
if (typeof this.debug === "function") {
this.debug("check PONG every " + ttl + "ms");
}
return this.ponger = Stomp.setInterval(ttl, function (_this) {
return function () {
var delta;
delta = now() - _this.serverActivity;
if (delta > ttl * 2) {
if (typeof _this.debug === "function") {
_this.debug("did not receive server activity for the last " + delta + "ms");
}
return _this.ws.close();
}
};
}(this));
}
};
Client.prototype._parseConnect = function () {
var args, connectCallback, errorCallback, headers;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
headers = {};
switch (args.length) {
case 2:
headers = args[0], connectCallback = args[1];
break;
case 3:
if (args[1] instanceof Function) {
headers = args[0], connectCallback = args[1], errorCallback = args[2];
} else {
headers.login = args[0], headers.passcode = args[1], connectCallback = args[2];
}
break;
case 4:
headers.login = args[0], headers.passcode = args[1], connectCallback = args[2], errorCallback = args[3];
break;
default:
headers.login = args[0], headers.passcode = args[1], connectCallback = args[2], errorCallback = args[3], headers.host = args[4];
}
return [headers, connectCallback, errorCallback];
};
Client.prototype.connect = function () {
var args, errorCallback, headers, out;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
out = this._parseConnect.apply(this, args);
headers = out[0], this.connectCallback = out[1], errorCallback = out[2];
if (typeof this.debug === "function") {
this.debug("Opening Web Socket...");
}
this.ws.onmessage = function (_this) {
return function (evt) {
var arr, c, client, data, frame, messageID, onreceive, subscription, unmarshalledData, _i, _len, _ref, _results;
data = typeof ArrayBuffer !== 'undefined' && evt.data instanceof ArrayBuffer ? (arr = new Uint8Array(evt.data), typeof _this.debug === "function" ? _this.debug("--- got data length: " + arr.length) : void 0, function () {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = arr.length; _i < _len; _i++) {
c = arr[_i];
_results.push(String.fromCharCode(c));
}
return _results;
}().join('')) : evt.data;
_this.serverActivity = now();
if (data === Byte.LF) {
if (typeof _this.debug === "function") {
_this.debug("<<< PONG");
}
return;
}
if (typeof _this.debug === "function") {
_this.debug("<<< " + data);
}
unmarshalledData = Frame.unmarshall(_this.partialData + data);
_this.partialData = unmarshalledData.partial;
_ref = unmarshalledData.frames;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
frame = _ref[_i];
switch (frame.command) {
case "CONNECTED":
if (typeof _this.debug === "function") {
_this.debug("connected to server " + frame.headers.server);
}
_this.connected = true;
_this._setupHeartbeat(frame.headers);
_results.push(typeof _this.connectCallback === "function" ? _this.connectCallback(frame) : void 0);
break;
case "MESSAGE":
subscription = frame.headers.subscription;
onreceive = _this.subscriptions[subscription] || _this.onreceive;
if (onreceive) {
client = _this;
messageID = frame.headers["message-id"];
frame.ack = function (headers) {
if (headers == null) {
headers = {};
}
return client.ack(messageID, subscription, headers);
};
frame.nack = function (headers) {
if (headers == null) {
headers = {};
}
return client.nack(messageID, subscription, headers);
};
_results.push(onreceive(frame));
} else {
_results.push(typeof _this.debug === "function" ? _this.debug("Unhandled received MESSAGE: " + frame) : void 0);
}
break;
case "RECEIPT":
_results.push(typeof _this.onreceipt === "function" ? _this.onreceipt(frame) : void 0);
break;
case "ERROR":
_results.push(typeof errorCallback === "function" ? errorCallback(frame) : void 0);
break;
default:
_results.push(typeof _this.debug === "function" ? _this.debug("Unhandled frame: " + frame) : void 0);
}
}
return _results;
};
}(this);
this.ws.onclose = function (_this) {
return function () {
var msg;
msg = "Whoops! Lost connection to " + _this.ws.url;
if (typeof _this.debug === "function") {
_this.debug(msg);
}
_this._cleanUp();
return typeof errorCallback === "function" ? errorCallback(msg) : void 0;
};
}(this);
return this.ws.onopen = function (_this) {
return function () {
if (typeof _this.debug === "function") {
_this.debug('Web Socket Opened...');
}
headers["accept-version"] = Stomp.VERSIONS.supportedVersions();
headers["heart-beat"] = [_this.heartbeat.outgoing, _this.heartbeat.incoming].join(',');
return _this._transmit("CONNECT", headers);
};
}(this);
};
Client.prototype.disconnect = function (disconnectCallback, headers) {
if (headers == null) {
headers = {};
}
this._transmit("DISCONNECT", headers);
this.ws.onclose = null;
this.ws.close();
this._cleanUp();
return typeof disconnectCallback === "function" ? disconnectCallback() : void 0;
};
Client.prototype._cleanUp = function () {
this.connected = false;
if (this.pinger) {
Stomp.clearInterval(this.pinger);
}
if (this.ponger) {
return Stomp.clearInterval(this.ponger);
}
};
Client.prototype.send = function (destination, headers, body) {
if (headers == null) {
headers = {};
}
if (body == null) {
body = '';
}
headers.destination = destination;
return this._transmit("SEND", headers, body);
};
Client.prototype.subscribe = function (destination, callback, headers) {
var client;
if (headers == null) {
headers = {};
}
if (!headers.id) {
headers.id = "sub-" + this.counter++;
}
headers.destination = destination;
this.subscriptions[headers.id] = callback;
this._transmit("SUBSCRIBE", headers);
client = this;
return {
id: headers.id,
unsubscribe: function unsubscribe() {
return client.unsubscribe(headers.id);
}
};
};
Client.prototype.unsubscribe = function (id) {
delete this.subscriptions[id];
return this._transmit("UNSUBSCRIBE", {
id: id
});
};
Client.prototype.begin = function (transaction) {
var client, txid;
txid = transaction || "tx-" + this.counter++;
this._transmit("BEGIN", {
transaction: txid
});
client = this;
return {
id: txid,
commit: function commit() {
return client.commit(txid);
},
abort: function abort() {
return client.abort(txid);
}
};
};
Client.prototype.commit = function (transaction) {
return this._transmit("COMMIT", {
transaction: transaction
});
};
Client.prototype.abort = function (transaction) {
return this._transmit("ABORT", {
transaction: transaction
});
};
Client.prototype.ack = function (messageID, subscription, headers) {
if (headers == null) {
headers = {};
}
headers["message-id"] = messageID;
headers.subscription = subscription;
return this._transmit("ACK", headers);
};
Client.prototype.nack = function (messageID, subscription, headers) {
if (headers == null) {
headers = {};
}
headers["message-id"] = messageID;
headers.subscription = subscription;
return this._transmit("NACK", headers);
};
return Client;
}();
Stomp = {
VERSIONS: {
V1_0: '1.0',
V1_1: '1.1',
V1_2: '1.2',
supportedVersions: function supportedVersions() {
return '1.1,1.0';
}
},
client: function client(url, protocols) {
var klass, ws;
if (protocols == null) {
protocols = ['v10.stomp', 'v11.stomp'];
}
klass = Stomp.WebSocketClass || WebSocket;
ws = new klass(url, protocols);
return new Client(ws);
},
over: function over(ws) {
return new Client(ws);
},
Frame: Frame
};
if (typeof exports !== "undefined" && exports !== null) {
exports.Stomp = Stomp;
}
if (typeof window !== "undefined" && window !== null) {
Stomp.setInterval = function (interval, f) {
return window.setInterval(f, interval);
};
Stomp.clearInterval = function (id) {
return window.clearInterval(id);
};
window.Stomp = Stomp;
} else if (!exports) {
self.Stomp = Stomp;
}
}).call(undefined);
},{}],23:[function(require,module,exports){
'use strict';
var _convert = require('../utils/convert');
var _convert2 = _interopRequireDefault(_convert);
var _network = require('./network');
var _network2 = _interopRequireDefault(_network);
var _cryptoJs = require('crypto-js');
var _cryptoJs2 = _interopRequireDefault(_cryptoJs);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
/**
* Encode a string to base32
*
* @param {string} s - A string
*
* @return {string} - The encoded string
*/
var b32encode = function b32encode(s) {
var parts = [];
var quanta = Math.floor(s.length / 5);
var leftover = s.length % 5;
if (leftover != 0) {
for (var i = 0; i < 5 - leftover; i++) {
s += '\x00';
}
quanta += 1;
}
for (var _i = 0; _i < quanta; _i++) {
parts.push(alphabet.charAt(s.charCodeAt(_i * 5) >> 3));
parts.push(alphabet.charAt((s.charCodeAt(_i * 5) & 0x07) << 2 | s.charCodeAt(_i * 5 + 1) >> 6));
parts.push(alphabet.charAt((s.charCodeAt(_i * 5 + 1) & 0x3F) >> 1));
parts.push(alphabet.charAt((s.charCodeAt(_i * 5 + 1) & 0x01) << 4 | s.charCodeAt(_i * 5 + 2) >> 4));
parts.push(alphabet.charAt((s.charCodeAt(_i * 5 + 2) & 0x0F) << 1 | s.charCodeAt(_i * 5 + 3) >> 7));
parts.push(alphabet.charAt((s.charCodeAt(_i * 5 + 3) & 0x7F) >> 2));
parts.push(alphabet.charAt((s.charCodeAt(_i * 5 + 3) & 0x03) << 3 | s.charCodeAt(_i * 5 + 4) >> 5));
parts.push(alphabet.charAt(s.charCodeAt(_i * 5 + 4) & 0x1F));
}
var replace = 0;
if (leftover == 1) replace = 6;else if (leftover == 2) replace = 4;else if (leftover == 3) replace = 3;else if (leftover == 4) replace = 1;
for (var _i2 = 0; _i2 < replace; _i2++) {
parts.pop();
}for (var _i3 = 0; _i3 < replace; _i3++) {
parts.push("=");
}return parts.join("");
};
/**
* Decode a base32 string.
* This is made specifically for our use, deals only with proper strings
*
* @param {string} s - A base32 string
*
* @return {Uint8Array} - The decoded string
*/
var b32decode = function b32decode(s) {
var r = new ArrayBuffer(s.length * 5 / 8);
var b = new Uint8Array(r);
for (var j = 0; j < s.length / 8; j++) {
var v = [0, 0, 0, 0, 0, 0, 0, 0];
for (var _i4 = 0; _i4 < 8; ++_i4) {
v[_i4] = alphabet.indexOf(s[j * 8 + _i4]);
}
var i = 0;
b[j * 5 + 0] = v[i + 0] << 3 | v[i + 1] >> 2;
b[j * 5 + 1] = (v[i + 1] & 0x3) << 6 | v[i + 2] << 1 | v[i + 3] >> 4;
b[j * 5 + 2] = (v[i + 3] & 0xf) << 4 | v[i + 4] >> 1;
b[j * 5 + 3] = (v[i + 4] & 0x1) << 7 | v[i + 5] << 2 | v[i + 6] >> 3;
b[j * 5 + 4] = (v[i + 6] & 0x7) << 5 | v[i + 7];
}
return b;
};
/**
* Convert a public key to a NEM address
*
* @param {string} publicKey - A public key
* @param {number} networkId - A network id
*
* @return {string} - The NEM address
*/
var toAddress = function toAddress(publicKey, networkId) {
var binPubKey = _cryptoJs2.default.enc.Hex.parse(publicKey);
var hash = _cryptoJs2.default.SHA3(binPubKey, {
outputLength: 256
});
var hash2 = _cryptoJs2.default.RIPEMD160(hash);
// 98 is for testnet
var networkPrefix = _network2.default.id2Prefix(networkId);
var versionPrefixedRipemd160Hash = networkPrefix + _cryptoJs2.default.enc.Hex.stringify(hash2);
var tempHash = _cryptoJs2.default.SHA3(_cryptoJs2.default.enc.Hex.parse(versionPrefixedRipemd160Hash), {
outputLength: 256
});
var stepThreeChecksum = _cryptoJs2.default.enc.Hex.stringify(tempHash).substr(0, 8);
var concatStepThreeAndStepSix = _convert2.default.hex2a(versionPrefixedRipemd160Hash + stepThreeChecksum);
var ret = b32encode(concatStepThreeAndStepSix);
return ret;
};
/**
* Check if an address is from a specified network
*
* @param {string} _address - An address
* @param {number} networkId - A network id
*
* @return {boolean} - True if address is from network, false otherwise
*/
var isFromNetwork = function isFromNetwork(_address, networkId) {
var address = _address.toString().toUpperCase().replace(/-/g, '');
var a = address[0];
return _network2.default.id2Char(networkId) === a;
};
/**
* Check if an address is valid
*
* @param {string} _address - An address
*
* @return {boolean} - True if address is valid, false otherwise
*/
var isValid = function isValid(_address) {
var address = _address.toString().toUpperCase().replace(/-/g, '');
if (!address || address.length !== 40) {
return false;
}
var decoded = _convert2.default.ua2hex(b32decode(address));
var versionPrefixedRipemd160Hash = _cryptoJs2.default.enc.Hex.parse(decoded.slice(0, 42));
var tempHash = _cryptoJs2.default.SHA3(versionPrefixedRipemd160Hash, {
outputLength: 256
});
var stepThreeChecksum = _cryptoJs2.default.enc.Hex.stringify(tempHash).substr(0, 8);
return stepThreeChecksum === decoded.slice(42);
};
/**
* Remove hyphens from an address
*
* @param {string} _address - An address
*
* @return {string} - A clean address
*/
var clean = function clean(_address) {
return _address.toUpperCase().replace(/-|\s/g, "");
};
module.exports = {
b32encode: b32encode,
b32decode: b32decode,
toAddress: toAddress,
isFromNetwork: isFromNetwork,
isValid: isValid,
clean: clean
};
},{"../utils/convert":49,"./network":26,"crypto-js":179}],24:[function(require,module,exports){
'use strict';
var _cryptoJs = require('crypto-js');
var _cryptoJs2 = _interopRequireDefault(_cryptoJs);
var _helpers = require('../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _convert = require('../utils/convert');
var _convert2 = _interopRequireDefault(_convert);
var _keyPair = require('../crypto/keyPair');
var _keyPair2 = _interopRequireDefault(_keyPair);
var _address = require('../model/address');
var _address2 = _interopRequireDefault(_address);
var _sinks = require('../model/sinks');
var _sinks2 = _interopRequireDefault(_sinks);
var _objects = require('../model/objects');
var _objects2 = _interopRequireDefault(_objects);
var _transactions = require('../model/transactions');
var _transactions2 = _interopRequireDefault(_transactions);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Apostille hashing methods with version bytes
*
* @type {object}
*/
var hashing = {
"MD5": {
name: "MD5",
signedVersion: "81",
version: "01"
},
"SHA1": {
name: "SHA1",
signedVersion: "82",
version: "02"
},
"SHA256": {
name: "SHA256",
signedVersion: "83",
version: "03"
},
"SHA3-256": {
name: "SHA3-256",
signedVersion: "88",
version: "08"
},
"SHA3-512": {
name: "SHA3-512",
signedVersion: "89",
version: "09"
}
/**
* Hash the file content depending of hashing
*
* @param {wordArray} data - File content
* @param {object} hashing - The chosen hashing object
* @param {boolean} isPrivate - True if apostille is private, false otherwise
*
* @return {string} - The file hash with checksum
*/
};var hashFileData = function hashFileData(data, hashing, isPrivate) {
// Full checksum is 0xFE (added automatically if hex txes) + 0x4E + 0x54 + 0x59 + hashing version byte
var checksum = void 0;
// Append byte to checksum
if (isPrivate) {
checksum = "4e5459" + hashing.signedVersion;
} else {
checksum = "4e5459" + hashing.version;
}
// Build the apostille hash
if (hashing.name === "MD5") {
return checksum + _cryptoJs2.default.MD5(data);
} else if (hashing.name === "SHA1") {
return checksum + _cryptoJs2.default.SHA1(data);
} else if (hashing.name === "SHA256") {
return checksum + _cryptoJs2.default.SHA256(data);
} else if (hashing.name === "SHA3-256") {
return checksum + _cryptoJs2.default.SHA3(data, {
outputLength: 256
});
} else {
return checksum + _cryptoJs2.default.SHA3(data, {
outputLength: 512
});
}
};
/**
* Create an apostille object
*
* @param {object} common - A common object
* @param {string} fileName - The file name (with extension)
* @param {wordArray} fileContent - The file content
* @param {string} tags - The apostille tags
* @param {object} hashing - An hashing object
* @param {boolean} isMultisig - True if transaction is multisig, false otherwise
* @param {object} multisigAccount - An [AccountInfo]{@link https://bob.nem.ninja/docs/#accountInfo} object
* @param {boolean} isPrivate - True if apostille is private / transferable / updateable, false if public
* @param {number} network - A network id
*
* @return {object} - An apostille object containing apostille data and the prepared transaction ready to be sent
*/
var create = function create(common, fileName, fileContent, tags, hashing, isMultisig, multisigAccount, isPrivate, network) {
var dedicatedAccount = {};
var apostilleHash = void 0;
//
if (isPrivate) {
// Create user keypair
var kp = _keyPair2.default.create(_helpers2.default.fixPrivateKey(common.privateKey));
// Create the dedicated account
dedicatedAccount = generateAccount(common, fileName, network);
// Create hash from file content and selected hashing
var hash = hashFileData(fileContent, hashing, isPrivate);
// Get checksum
var checksum = hash.substring(0, 8);
// Get hash without checksum
var dataHash = hash.substring(8);
// Set checksum + signed hash as message
apostilleHash = checksum + kp.sign(dataHash).toString();
} else {
// Use sink account
dedicatedAccount.address = _sinks2.default.apostille[network].toUpperCase().replace(/-/g, '');
// Set recipient private key
dedicatedAccount.privateKey = "None (public sink)";
// No signing we just put the hash in message
apostilleHash = hashFileData(fileContent, hashing, isPrivate);
}
// Create transfer transaction object
var transaction = _objects2.default.create("transferTransaction")(dedicatedAccount.address, 0, apostilleHash);
// Multisig
transaction.isMultisig = isMultisig;
transaction.multisigAccount = multisigAccount;
// Set message type to hexadecimal
transaction.messageType = 0;
// Prepare the transfer transaction object
var transactionEntity = _transactions2.default.prepare("transferTransaction")(common, transaction, network);
return {
"data": {
"file": {
"name": fileName,
"hash": apostilleHash.substring(8),
"content": fileContent
},
"hash": "fe" + apostilleHash,
"checksum": "fe" + apostilleHash.substring(0, 8),
"dedicatedAccount": {
"address": dedicatedAccount.address,
"privateKey": dedicatedAccount.privateKey
},
"tags": tags
},
"transaction": transactionEntity
};
};
/**
* Verify an apostille
*
* @param {wordArray} fileContent - The file content
* @param {object} apostilleTransaction - The transaction object for the apostille
*
* @return {boolean} - True if valid, false otherwise
*/
var verify = function verify(fileContent, apostilleTransaction) {
var apostilleHash = void 0;
if (apostilleTransaction.type === 4100) {
apostilleHash = apostilleTransaction.otherTrans.message.payload;
} else {
apostilleHash = apostilleTransaction.message.payload;
}
// Get the checksum
var checksum = apostilleHash.substring(0, 10);
// Get the hashing byte
var hashingByte = checksum.substring(8);
// Retrieve the hashing method using the checksum in message and hash the file accordingly
var fileHash = retrieveHash(apostilleHash, fileContent);
// Check if apostille is signed
if (isSigned(hashingByte)) {
// Verify signature
return _keyPair2.default.verifySignature(apostilleTransaction.signer, fileHash, apostilleHash.substring(10));
} else {
// Check if hashed file match hash in transaction (without checksum)
return fileHash === apostilleHash.substring(10);
}
};
/**
* Hash a file according to version byte in checksum
*
* @param {string} apostilleHash - The hash contained in the apostille transaction
* @param {wordArray} fileContent - The file content
*
* @return {string} - The file content hashed with correct hashing method
*/
var retrieveHash = function retrieveHash(apostilleHash, fileContent) {
// Get checksum
var checksum = apostilleHash.substring(0, 10);
// Get the version byte
var hashingVersionBytes = checksum.substring(8);
// Hash depending of version byte
if (hashingVersionBytes === "01" || hashingVersionBytes === "81") {
return _cryptoJs2.default.MD5(fileContent).toString(_cryptoJs2.default.enc.Hex);
} else if (hashingVersionBytes === "02" || hashingVersionBytes === "82") {
return _cryptoJs2.default.SHA1(fileContent).toString(_cryptoJs2.default.enc.Hex);
} else if (hashingVersionBytes === "03" || hashingVersionBytes === "83") {
return _cryptoJs2.default.SHA256(fileContent).toString(_cryptoJs2.default.enc.Hex);
} else if (hashingVersionBytes === "08" || hashingVersionBytes === "88") {
return _cryptoJs2.default.SHA3(fileContent, { outputLength: 256 }).toString(_cryptoJs2.default.enc.Hex);
} else {
return _cryptoJs2.default.SHA3(fileContent, { outputLength: 512 }).toString(_cryptoJs2.default.enc.Hex);
}
};
/**
* Check if an apostille is signed
*
* @param {string} hashingByte - An hashing version byte
*
* @return {boolean} - True if signed, false otherwise
*/
var isSigned = function isSigned(hashingByte) {
var array = Object.keys(hashing);
for (var i = 0; array.length > i; i++) {
if (hashing[array[i]].signedVersion === hashingByte) {
return true;
}
}
return false;
};
/**
* Generate the dedicated account for a file. It will always generate the same private key for a given file name and private key
*
* @param {object} common - A common object
* @param {string} fileName - The file name (with extension)
* @param {number} network - A network id
*
* @return {object} - An object containing address and private key of the dedicated account
*/
var generateAccount = function generateAccount(common, fileName, network) {
// Create user keypair
var kp = _keyPair2.default.create(_helpers2.default.fixPrivateKey(common.privateKey));
// Create recipient account from signed sha256 hash of new filename
var signedFilename = kp.sign(_cryptoJs2.default.SHA256(fileName).toString(_cryptoJs2.default.enc.Hex)).toString();
// Truncate signed file name to get a 32 bytes private key
var dedicatedAccountPrivateKey = _helpers2.default.fixPrivateKey(signedFilename);
// Create dedicated account key pair
var dedicatedAccountKeyPair = _keyPair2.default.create(dedicatedAccountPrivateKey);
return {
"address": _address2.default.toAddress(dedicatedAccountKeyPair.publicKey.toString(), network),
"privateKey": dedicatedAccountPrivateKey
};
};
module.exports = {
create: create,
generateAccount: generateAccount,
hashing: hashing,
verify: verify,
isSigned: isSigned
};
},{"../crypto/keyPair":19,"../model/address":23,"../model/objects":28,"../model/sinks":35,"../model/transactions":37,"../utils/convert":49,"../utils/helpers":51,"crypto-js":179}],25:[function(require,module,exports){
'use strict';
var _helpers = require('../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _format = require('../utils/format');
var _format2 = _interopRequireDefault(_format);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The Fee structure's base fee
*
* @type {number}
*/
var baseTransactionFee = 3;
/**
* The Fee structure's Fee factor
*
* @type {number}
*/
var currentFeeFactor = 0.05;
/**
* The multisignature transaction fee
*
* @type {number}
*/
var multisigTransaction = Math.floor(baseTransactionFee * currentFeeFactor * 1000000);
/**
* The provision namespace transaction rental fee for root namespace
*
* @type {number}
*/
var rootProvisionNamespaceTransaction = 100 * 1000000;
/**
* The provision namespace transaction rental fee for sub-namespace
*
* @type {number}
*/
var subProvisionNamespaceTransaction = 10 * 1000000;
/**
* The mosaic definition transaction fee
*
* @type {number}
*/
var mosaicDefinitionTransaction = 10 * 1000000;
/**
* The common transaction fee for namespaces and mosaics
*
* @type {number}
*/
var namespaceAndMosaicCommon = Math.floor(baseTransactionFee * currentFeeFactor * 1000000);
/**
* The cosignature transaction fee
*
* @type {number}
*/
var signatureTransaction = Math.floor(baseTransactionFee * currentFeeFactor * 1000000);
/**
* The importance transfer transaction fee
*
* @type {number}
*/
var importanceTransferTransaction = Math.floor(baseTransactionFee * currentFeeFactor * 1000000);
/**
* The multisignature aggregate modification transaction fee
*
* @type {number}
*/
var multisigAggregateModificationTransaction = Math.floor(10 * currentFeeFactor * 1000000);
/**
* Calculate message fee. 0.05 XEM per commenced 32 bytes
*
* If the message is empty, the fee will be 0
*
* @param {object} message - An message object
* @param {boolean} isHW - True if hardware wallet, false otherwise
*
* @return {number} - The message fee
*/
var calculateMessage = function calculateMessage(message, isHW) {
if (!message.payload || !message.payload.length) return 0.00;
var length = message.payload.length / 2;
// Add salt and IV and round up to AES block size
if (isHW && message.type == 2) length = 32 + 16 + Math.ceil(length / 16) * 16;
return currentFeeFactor * (Math.floor(length / 32) + 1);
};
/**
* Calculate fees for mosaics included in a transfer transaction
*
* @param {number} multiplier - A quantity multiplier
* @param {object} mosaics - A mosaicDefinitionMetaDataPair object
* @param {array} attachedMosaics - An array of mosaics to send
*
* @return {number} - The fee amount for the mosaics in the transaction
*/
var calculateMosaics = function calculateMosaics(multiplier, mosaics, attachedMosaics) {
var totalFee = 0;
var fee = 0;
var supplyRelatedAdjustment = 0;
for (var i = 0; i < attachedMosaics.length; i++) {
var m = attachedMosaics[i];
var mosaicName = _format2.default.mosaicIdToName(m.mosaicId);
if (!(mosaicName in mosaics)) {
return ['unknown mosaic divisibility']; //
}
var mosaicDefinitionMetaDataPair = mosaics[mosaicName];
var divisibilityProperties = _helpers2.default.grep(mosaicDefinitionMetaDataPair.mosaicDefinition.properties, function (w) {
return w.name === "divisibility";
});
var divisibility = divisibilityProperties.length === 1 ? ~~divisibilityProperties[0].value : 0;
var supply = mosaicDefinitionMetaDataPair.mosaicDefinition.properties[1].value; //
var quantity = m.quantity;
if (supply <= 10000 && divisibility === 0) {
// Small business mosaic fee
fee = currentFeeFactor;
} else {
var maxMosaicQuantity = 9000000000000000;
var totalMosaicQuantity = supply * Math.pow(10, divisibility);
supplyRelatedAdjustment = Math.floor(0.8 * Math.log(maxMosaicQuantity / totalMosaicQuantity));
var numNem = calculateXemEquivalent(multiplier, quantity, supply, divisibility);
// Using Math.ceil below because xem equivalent returned is sometimes a bit lower than it should
// Ex: 150'000 of nem:xem gives 149999.99999999997
fee = calculateMinimum(Math.ceil(numNem));
}
totalFee += currentFeeFactor * Math.max(1, fee - supplyRelatedAdjustment);
}
return totalFee;
};
/**
* Calculate fees from an amount of XEM
*
* @param {number} numNem - An amount of XEM
*
* @return {number} - The minimum fee
*/
var calculateMinimum = function calculateMinimum(numNem) {
var fee = Math.floor(Math.max(1, numNem / 10000));
return fee > 25 ? 25 : fee;
};
/**
* Calculate mosaic quantity equivalent in XEM
*
* @param {number} multiplier - A mosaic multiplier
* @param {number} q - A mosaic quantity
* @param {number} sup - A mosaic supply
* @param {number} divisibility - A mosaic divisibility
*
* @return {number} - The XEM equivalent of a mosaic quantity
*/
var calculateXemEquivalent = function calculateXemEquivalent(multiplier, q, sup, divisibility) {
if (sup === 0) {
return 0;
}
// TODO: can this go out of JS (2^54) bounds? (possible BUG)
return 8999999999 * q * multiplier / sup / Math.pow(10, divisibility + 6);
};
module.exports = {
multisigTransaction: multisigTransaction,
rootProvisionNamespaceTransaction: rootProvisionNamespaceTransaction,
subProvisionNamespaceTransaction: subProvisionNamespaceTransaction,
mosaicDefinitionTransaction: mosaicDefinitionTransaction,
namespaceAndMosaicCommon: namespaceAndMosaicCommon,
signatureTransaction: signatureTransaction,
calculateMosaics: calculateMosaics,
calculateMinimum: calculateMinimum,
calculateMessage: calculateMessage,
calculateXemEquivalent: calculateXemEquivalent,
currentFeeFactor: currentFeeFactor,
importanceTransferTransaction: importanceTransferTransaction,
multisigAggregateModificationTransaction: multisigAggregateModificationTransaction
};
},{"../utils/format":50,"../utils/helpers":51}],26:[function(require,module,exports){
"use strict";
/**
* Networks info data
*
* @type {object}
*/
var data = {
"mainnet": {
"id": 104,
"prefix": "68",
"char": "N"
},
"testnet": {
"id": -104,
"prefix": "98",
"char": "T"
},
"mijin": {
"id": 96,
"prefix": "60",
"char": "M"
}
/**
* Gets a network prefix from network id
*
* @param {number} id - A network id
*
* @return {string} - The network prefix
*/
};var id2Prefix = function id2Prefix(id) {
if (id === 104) {
return "68";
} else if (id === -104) {
return "98";
} else {
return "60";
}
};
/**
* Gets the starting char of the addresses of a network id
*
* @param {number} id - A network id
*
* @return {string} - The starting char of addresses
*/
var id2Char = function id2Char(id) {
if (id === 104) {
return "N";
} else if (id === -104) {
return "T";
} else {
return "M";
}
};
/**
* Gets the network id from the starting char of an address
*
* @param {string} startChar - A starting char from an address
*
* @return {number} - The network id
*/
var char2Id = function char2Id(startChar) {
if (startChar === "N") {
return 104;
} else if (startChar === "T") {
return -104;
} else {
return 96;
}
};
/**
* Gets the network version
*
* @param {number} val - A version number (1 or 2)
* @param {number} network - A network id
*
* @return {number} - A network version
*/
var getVersion = function getVersion(val, network) {
if (network === data.mainnet.id) {
return 0x68000000 | val;
} else if (network === data.testnet.id) {
return 0x98000000 | val;
}
return 0x60000000 | val;
};
module.exports = {
data: data,
id2Prefix: id2Prefix,
id2Char: id2Char,
char2Id: char2Id,
getVersion: getVersion
};
},{}],27:[function(require,module,exports){
'use strict';
/**
* The default testnet node
*
* @type {string}
*/
var defaultTestnet = 'http://bigalice2.nem.ninja';
/**
* The default mainnet node
*
* @type {string}
*/
var defaultMainnet = 'http://alice6.nem.ninja';
/**
* The default mijin node
*
* @type {string}
*/
var defaultMijin = '';
/**
* The default mainnet block explorer
*
* @type {string}
*/
var mainnetExplorer = 'http://chain.nem.ninja/#/transfer/';
/**
* The default testnet block explorer
*
* @type {string}
*/
var testnetExplorer = 'http://bob.nem.ninja:8765/#/transfer/';
/**
* The default mijin block explorer
*
* @type {string}
*/
var mijinExplorer = '';
/**
* The nodes allowing search by transaction hash on testnet
*
* @type {array}
*/
var searchOnTestnet = [{
'uri': 'http://bigalice2.nem.ninja',
'location': 'America / New_York'
}, {
'uri': 'http://192.3.61.243',
'location': 'America / Los_Angeles'
}, {
'uri': 'http://23.228.67.85',
'location': 'America / Los_Angeles'
}];
/**
* The nodes allowing search by transaction hash on mainnet
*
* @type {array}
*/
var searchOnMainnet = [{
'uri': 'http://62.75.171.41',
'location': 'Germany'
}, {
'uri': 'http://104.251.212.131',
'location': 'USA'
}, {
'uri': 'http://45.124.65.125',
'location': 'Hong Kong'
}, {
'uri': 'http://185.53.131.101',
'location': 'Netherlands'
}, {
'uri': 'http://sz.nemchina.com',
'location': 'China'
}];
/**
* The nodes allowing search by transaction hash on mijin
*
* @type {array}
*/
var searchOnMijin = [{
'uri': '',
'location': ''
}];
/**
* The testnet nodes
*
* @type {array}
*/
var testnet = [{
uri: 'http://104.128.226.60'
}, {
uri: 'http://23.228.67.85'
}, {
uri: 'http://192.3.61.243'
}, {
uri: 'http://50.3.87.123'
}, {
uri: 'http://localhost'
}];
/**
* The mainnet nodes
*
* @type {array}
*/
var mainnet = [{
uri: 'http://62.75.171.41'
}, {
uri: 'http://san.nem.ninja'
}, {
uri: 'http://go.nem.ninja'
}, {
uri: 'http://hachi.nem.ninja'
}, {
uri: 'http://jusan.nem.ninja'
}, {
uri: 'http://nijuichi.nem.ninja'
}, {
uri: 'http://alice2.nem.ninja'
}, {
uri: 'http://alice3.nem.ninja'
}, {
uri: 'http://alice4.nem.ninja'
}, {
uri: 'http://alice5.nem.ninja'
}, {
uri: 'http://alice6.nem.ninja'
}, {
uri: 'http://alice7.nem.ninja'
}, {
uri: 'http://localhost'
}];
/**
* The mijin nodes
*
* @type {array}
*/
var mijin = [{
uri: ''
}];
/**
* The server verifying signed apostilles
*
* @type {string}
*/
var apostilleAuditServer = 'http://185.117.22.58:4567/verify';
/**
* The API to get all supernodes
*
* @type {string}
*/
var supernodes = 'https://supernodes.nem.io/nodes';
/**
* The API to get XEM/BTC market data
*
* @type {string}
*/
var marketInfo = 'https://poloniex.com/public';
/**
* The API to get BTC/USD market data
*
* @type {string}
*/
var btcPrice = 'https://blockchain.info/ticker';
/**
* The default endpoint port
*
* @type {number}
*/
var defaultPort = 7890;
/**
* The Mijin endpoint port
*
* @type {number}
*/
var mijinPort = 7895;
/**
* The websocket port
*
* @type {number}
*/
var websocketPort = 7778;
module.exports = {
defaultTestnet: defaultTestnet,
defaultMainnet: defaultMainnet,
defaultMijin: defaultMijin,
mainnetExplorer: mainnetExplorer,
testnetExplorer: testnetExplorer,
mijinExplorer: mijinExplorer,
searchOnTestnet: searchOnTestnet,
searchOnMainnet: searchOnMainnet,
searchOnMijin: searchOnMijin,
testnet: testnet,
mainnet: mainnet,
mijin: mijin,
apostilleAuditServer: apostilleAuditServer,
supernodes: supernodes,
defaultPort: defaultPort,
mijinPort: mijinPort,
websocketPort: websocketPort,
marketInfo: marketInfo,
btcPrice: btcPrice
};
},{}],28:[function(require,module,exports){
'use strict';
var _account = require('./objects/account');
var _account2 = _interopRequireDefault(_account);
var _miscellaneous = require('./objects/miscellaneous');
var _miscellaneous2 = _interopRequireDefault(_miscellaneous);
var _mosaic = require('./objects/mosaic');
var _mosaic2 = _interopRequireDefault(_mosaic);
var _transactions = require('./objects/transactions');
var _transactions2 = _interopRequireDefault(_transactions);
var _qr = require('./objects/qr');
var _qr2 = _interopRequireDefault(_qr);
var _wallet = require('./objects/wallet');
var _wallet2 = _interopRequireDefault(_wallet);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Get an empty object
*
* @param {string} objectName - The name of the object
*
* @return {object} - The desired object
*/
var get = function get(objectName) {
return _fetch(0, objectName);
};
/**
* Create an object
*
* @param {string} objectName - The name of the object
*
* @return {function} - The object creation function corresponding to the object name
*/
var create = function create(objectName) {
return _fetch(1, objectName);
};
/**
* Fetch objects
*
* @param {number} type - 0 for get, 1 for creation
* @param {string} objectName - The name of the object
*
* @return {function|object} - The object creation function corresponding to the object name, or the object
*/
var _fetch = function _fetch(type, objectName) {
switch (objectName) {
case "account":
return !type ? (0, _account2.default)() : _account2.default;
break;
case "accountInfoQR":
return !type ? _qr2.default.accountInfo() : _qr2.default.accountInfo;
break;
case "common":
return !type ? _miscellaneous2.default.common() : _miscellaneous2.default.common;
break;
case "commonTransactionPart":
return !type ? _transactions2.default.commonPart() : _transactions2.default.commonPart;
break;
case "endpoint":
return !type ? _miscellaneous2.default.endpoint() : _miscellaneous2.default.endpoint;
break;
case "mosaicAttachment":
return !type ? _mosaic2.default.attachment() : _mosaic2.default.attachment;
break;
case "mosaicDefinitionMetaDataPair":
return _mosaic2.default.definitionMetaDataPair();
break;
case "mosaicDefinitionTransaction":
return !type ? _transactions2.default.mosaicDefinition() : _transactions2.default.mosaicDefinition;
break;
case "invoice":
return !type ? _qr2.default.invoice() : _qr2.default.invoice;
break;
case "transferTransaction":
return !type ? _transactions2.default.transfer() : _transactions2.default.transfer;
break;
case "signatureTransaction":
return !type ? _transactions2.default.signature() : _transactions2.default.signature;
break;
case "messageTypes":
return _miscellaneous2.default.messageTypes();
break;
case "mosaicSupplyChangeTransaction":
return !type ? _transactions2.default.mosaicSupplyChange() : _transactions2.default.mosaicSupplyChange;
break;
case "multisigAggregateModification":
return !type ? _transactions2.default.multisigAggregateModification() : _transactions2.default.multisigAggregateModification;
break;
case "multisigCosignatoryModification":
return !type ? _miscellaneous2.default.multisigCosignatoryModification() : _miscellaneous2.default.multisigCosignatoryModification;
break;
case "namespaceProvisionTransaction":
return !type ? _transactions2.default.namespaceProvision() : _transactions2.default.namespaceProvision;
break;
case "importanceTransferTransaction":
return !type ? _transactions2.default.importanceTransfer() : _transactions2.default.importanceTransfer;
break;
case "wallet":
return !type ? (0, _wallet2.default)() : _wallet2.default;
break;
case "walletQR":
return !type ? _qr2.default.wallet() : _qr2.default.wallet;
break;
default:
return {};
}
};
module.exports = {
get: get,
create: create
};
},{"./objects/account":29,"./objects/miscellaneous":30,"./objects/mosaic":31,"./objects/qr":32,"./objects/transactions":33,"./objects/wallet":34}],29:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (address, label, child, encrypted, iv) {
return {
"address": address || "",
"label": label || "",
"child": child || "",
"encrypted": encrypted || "",
"iv": iv || ""
};
};
},{}],30:[function(require,module,exports){
"use strict";
/**
* An endpoint object
*
* @param {string} host - A NIS uri
* @param {number} port - A port
*
* @return {object}
*/
var endpoint = function endpoint(host, port) {
return {
"host": host || "",
"port": port || ""
};
};
/**
* A common object
*
* @param {string} password - A password
* @param {string} privateKey - A privateKey
* @param {boolean} isHW - True if hardware wallet, false otherwise
*
* @return {object}
*/
var common = function common(password, privateKey, isHW) {
return {
"password": password || "",
"privateKey": privateKey || "",
"isHW": isHW || false
};
};
/**
* Contains message types with name
*
* @return {array}
*/
var messageTypes = function messageTypes() {
return [{
"value": 0,
"name": "Hexadecimal"
}, {
"value": 1,
"name": "Unencrypted"
}, {
"value": 2,
"name": "Encrypted"
}];
};
/**
* A multisig cosignatory modification object
*
* @param {number} type - 1 if an addition, 2 if deletion
* @param {string} publicKey - An account public key
*
* @return {object}
*/
var multisigCosignatoryModification = function multisigCosignatoryModification(type, publicKey) {
return {
"modificationType": type || 1,
"cosignatoryAccount": publicKey
};
};
module.exports = {
endpoint: endpoint,
common: common,
messageTypes: messageTypes,
multisigCosignatoryModification: multisigCosignatoryModification
};
},{}],31:[function(require,module,exports){
"use strict";
/**
* A mosaic attachment object
*
* @param {string} namespaceId - A namespace name
* @param {string} mosaicName - A mosaic name
* @param {number} quantity - A mosaic quantity (in uXEM)
*
* @return {object}
*/
var attachment = function attachment(namespaceId, mosaicName, quantity) {
return {
"mosaicId": {
"namespaceId": namespaceId || "",
"name": mosaicName || ""
},
"quantity": quantity || 0
};
};
var definitionMetaDataPair = function definitionMetaDataPair() {
return {
"nem:xem": {
"mosaicDefinition": {
"creator": "3e82e1c1e4a75adaa3cba8c101c3cd31d9817a2eb966eb3b511fb2ed45b8e262",
"description": "reserved xem mosaic",
"id": {
"namespaceId": "nem",
"name": "xem"
},
"properties": [{
"name": "divisibility",
"value": "6"
}, {
"name": "initialSupply",
"value": "8999999999"
}, {
"name": "supplyMutable",
"value": "false"
}, {
"name": "transferable",
"value": "true"
}],
"levy": {}
} /*,
"another.namespace:mosaic": {
"mosaicDefinition": {
Add mosaic definitions in this model to simplify transactions for a particular mosaic
}
} ,
"another.namespace.again:mosaic": {
"mosaicDefinition": {
...
}
} */
} };
};
module.exports = {
attachment: attachment,
definitionMetaDataPair: definitionMetaDataPair
};
},{}],32:[function(require,module,exports){
"use strict";
/**
* An account info object for mobile QR
*
* @param {number} version - A version number
* @param {number} type - A type number
* @param {string} address - A NEM address
* @param {string} name - An account name
*
* @return {object} - An account info object
*/
var accountInfo = function accountInfo(version, type, address, name) {
return {
"v": version || "",
"type": 1 || "",
"data": {
"addr": address || "",
"name": name || ""
}
};
};
/**
* A wallet object for mobile QR
*
* @param {number} version - A version number
* @param {number} type - An type number
* @param {string} name - A wallet name
* @param {string} encrypted - An encrypted primary private key
* @param {string} salt - Salt of the encrypted private key
*
* @return {object} - A wallet object
*/
var wallet = function wallet(version, type, name, encrypted, salt) {
return {
"v": version || "",
"type": type || "",
"data": {
"name": name || "",
"priv_key": encrypted || "",
"salt": salt || ""
}
};
};
var invoice = function invoice() {
return {
"v": "v = 1 for testnet, v = 2 for mainnet",
"type": 2,
"data": {
"addr": "",
"amount": 0,
"msg": "",
"name": ""
}
};
};
module.exports = {
accountInfo: accountInfo,
wallet: wallet,
invoice: invoice
};
},{}],33:[function(require,module,exports){
"use strict";
/**
* An un-prepared transfer transaction object
*
* @param {string} recipient - A NEM account address
* @param {number} amount - A number of XEM
* @param {string} message - A message
*
* @return {object}
*/
var transfer = function transfer(recipient, amount, message) {
return {
"amount": amount || 0,
"recipient": recipient || "",
"recipientPublicKey": "",
"isMultisig": false,
"multisigAccount": "",
"message": message || "",
"messageType": 1,
"mosaics": []
};
};
/**
* An un-prepared signature transaction object
*
* @param {string} multisigAccount - The multisig account address
* @param {string} txHash - The multisig transaction hash
*
* @return {object}
*/
var signature = function signature(multisigAccount, txHash) {
var compressedAccount = "";
if (typeof multisigAccount != "undefined" && multisigAccount.length) {
compressedAccount = multisigAccount.toUpperCase().replace(/-/g, "");
}
return {
"otherHash": {
"data": txHash || ""
},
"otherAccount": compressedAccount
};
};
/**
* An un-prepared mosaic definition transaction object
*
* @return {object}
*/
var mosaicDefinition = function mosaicDefinition() {
return {
"mosaicName": "",
"namespaceParent": "",
"mosaicDescription": "",
"properties": {
"initialSupply": 0,
"divisibility": 0,
"transferable": true,
"supplyMutable": true
},
"levy": {
"mosaic": null,
"address": "",
"feeType": 1,
"fee": 5
},
"isMultisig": false,
"multisigAccount": ""
};
};
/**
* An un-prepared mosaic supply change transaction object
*
* @return {object}
*/
var mosaicSupplyChange = function mosaicSupplyChange() {
return {
"mosaic": "",
"supplyType": 1,
"delta": 0,
"isMultisig": false,
"multisigAccount": ""
};
};
/**
* An un-prepared multisig aggregate modification transaction object
*
* @return {object}
*/
var multisigAggregateModification = function multisigAggregateModification() {
return {
"modifications": [],
"relativeChange": null,
"isMultisig": false,
"multisigAccount": ""
};
};
/**
* An un-prepared namespace provision transaction object
*
* @param {string} namespaceName - A namespace name
* @param {string} namespaceParent - A namespace name
*
* @return {object}
*/
var namespaceProvision = function namespaceProvision(namespaceName, namespaceParent) {
return {
"namespaceName": namespaceName || "",
"namespaceParent": namespaceParent || null,
"isMultisig": false,
"multisigAccount": ""
};
};
/**
* An un-prepared importance transfer transaction object
*
* @param {string} remoteAccount - A remote public key
* @param {number} mode - 1 for activating, 2 for deactivating
*
* @return {object}
*/
var importanceTransfer = function importanceTransfer(remoteAccount, mode) {
return {
"remoteAccount": remoteAccount || "",
"mode": mode || "",
"isMultisig": false,
"multisigAccount": ""
};
};
/**
* The common part of transactions
*
* @param {number} txType - A type of transaction
* @param {string} senderPublicKey - A sender public key
* @param {number} timeStamp - A timestamp for the transation
* @param {number} due - A deadline in minutes
* @param {number} version - A network version
* @param {number} network - A network id
*
* @return {object} - A common transaction object
*/
var commonPart = function commonPart(txtype, senderPublicKey, timeStamp, due, version, network) {
return {
'type': txtype || "",
'version': version || "",
'signer': senderPublicKey || "",
'timeStamp': timeStamp || "",
'deadline': timeStamp + due * 60 || ""
};
};
module.exports = {
multisigAggregateModification: multisigAggregateModification,
transfer: transfer,
signature: signature,
mosaicDefinition: mosaicDefinition,
mosaicSupplyChange: mosaicSupplyChange,
namespaceProvision: namespaceProvision,
importanceTransfer: importanceTransfer,
commonPart: commonPart
};
},{}],34:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (walletName, addr, brain, algo, encrypted, network) {
return {
"name": walletName,
"accounts": {
"0": {
"brain": brain,
"algo": algo,
"encrypted": encrypted.ciphertext || "",
"iv": encrypted.iv || "",
"address": addr.toUpperCase().replace(/-/g, ''),
"label": 'Primary',
"network": network
}
}
};
};
},{}],35:[function(require,module,exports){
'use strict';
/**
* The namespace, mosaic and apostille sink accounts
*
* @type {object}
*/
module.exports = {
namespace: {
'-104': 'TAMESP-ACEWH4-MKFMBC-VFERDP-OOP4FK-7MTDJE-YP35',
'104': 'NAMESP-ACEWH4-MKFMBC-VFERDP-OOP4FK-7MTBXD-PZZA',
'96': 'MAMESP-ACEWH4-MKFMBC-VFERDP-OOP4FK-7MTCZT-G5E7'
},
mosaic: {
'-104': 'TBMOSA-ICOD4F-54EE5C-DMR23C-CBGOAM-2XSJBR-5OLC',
'104': 'NBMOSA-ICOD4F-54EE5C-DMR23C-CBGOAM-2XSIUX-6TRS',
'96': 'MBMOSA-ICOD4F-54EE5C-DMR23C-CBGOAM-2XSKYH-TOJD'
},
apostille: {
'-104': 'TC7MCY-5AGJQX-ZQ4BN3-BOPNXU-VIGDJC-OHBPGU-M2GE',
'104': 'NCZSJH-LTIMES-ERVBVK-OW6US6-4YDZG2-PFGQCS-V23J',
'96': 'MCGDK2-J46BOD-GGKMPI-KCBGTB-BIWL6A-L5ZKLK-Q56A'
}
};
},{}],36:[function(require,module,exports){
"use strict";
/**
* The transfer transaction type
*
* @type {string}
*
* @default
*/
var transfer = 0x101; // 257
/**
* The importance transfer type
*
* @type {string}
*
* @default
*/
var importanceTransfer = 0x801; // 2049
/**
* The aggregate modification transaction type
*
* @type {string}
*
* @default
*/
var multisigModification = 0x1001; // 4097
/**
* The multisignature signature transaction type
*
* @type {string}
*
* @default
*/
var multisigSignature = 0x1002; // 4098
/**
* The multisignature transaction type
*
* @type {string}
*
* @default
*/
var multisigTransaction = 0x1004; // 4100
/**
* The provision namespace transaction type
*
* @type {string}
*
* @default
*/
var provisionNamespace = 0x2001; // 8193
/**
* The mosaic definition transaction type
*
* @type {string}
*
* @default
*/
var mosaicDefinition = 0x4001; // 16385
/**
* The mosaic supply change transaction type
*
* @type {string}
*
* @default
*/
var mosaicSupply = 0x4002; // 16386
module.exports = {
transfer: transfer,
importanceTransfer: importanceTransfer,
multisigModification: multisigModification,
multisigSignature: multisigSignature,
multisigTransaction: multisigTransaction,
provisionNamespace: provisionNamespace,
mosaicDefinition: mosaicDefinition,
mosaicSupply: mosaicSupply
};
},{}],37:[function(require,module,exports){
'use strict';
var _transferTransaction = require('./transactions/transferTransaction');
var _transferTransaction2 = _interopRequireDefault(_transferTransaction);
var _signatureTransaction = require('./transactions/signatureTransaction');
var _signatureTransaction2 = _interopRequireDefault(_signatureTransaction);
var _mosaicDefinitionTransaction = require('./transactions/mosaicDefinitionTransaction');
var _mosaicDefinitionTransaction2 = _interopRequireDefault(_mosaicDefinitionTransaction);
var _mosaicSupplyChange = require('./transactions/mosaicSupplyChange');
var _mosaicSupplyChange2 = _interopRequireDefault(_mosaicSupplyChange);
var _multisigAggregateModificationTransaction = require('./transactions/multisigAggregateModificationTransaction');
var _multisigAggregateModificationTransaction2 = _interopRequireDefault(_multisigAggregateModificationTransaction);
var _namespaceProvisionTransaction = require('./transactions/namespaceProvisionTransaction');
var _namespaceProvisionTransaction2 = _interopRequireDefault(_namespaceProvisionTransaction);
var _importanceTransferTransaction = require('./transactions/importanceTransferTransaction');
var _importanceTransferTransaction2 = _interopRequireDefault(_importanceTransferTransaction);
var _send = require('./transactions/send');
var _send2 = _interopRequireDefault(_send);
var _message = require('./transactions/message');
var _message2 = _interopRequireDefault(_message);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Prepare a transaction object
*
* @param {string} objectName - The name of the object to prepare
*
* @retrun {function} - The prepare function corresponding to the object name
*/
var prepare = function prepare(objectName) {
switch (objectName) {
case "transferTransaction":
return _transferTransaction2.default.prepare;
break;
case "mosaicTransferTransaction":
return _transferTransaction2.default.prepareMosaic;
break;
case "mosaicDefinitionTransaction":
return _mosaicDefinitionTransaction2.default.prepare;
break;
case "multisigAggregateModificationTransaction":
return _multisigAggregateModificationTransaction2.default.prepare;
break;
case "namespaceProvisionTransaction":
return _namespaceProvisionTransaction2.default.prepare;
break;
case "signatureTransaction":
return _signatureTransaction2.default.prepare;
break;
case "mosaicSupplyChangeTransaction":
return _mosaicSupplyChange2.default.prepare;
break;
case "importanceTransferTransaction":
return _importanceTransferTransaction2.default.prepare;
break;
default:
return {};
}
};
module.exports = {
prepare: prepare,
send: _send2.default,
prepareMessage: _message2.default.prepare
};
},{"./transactions/importanceTransferTransaction":38,"./transactions/message":39,"./transactions/mosaicDefinitionTransaction":40,"./transactions/mosaicSupplyChange":41,"./transactions/multisigAggregateModificationTransaction":42,"./transactions/namespaceProvisionTransaction":44,"./transactions/send":45,"./transactions/signatureTransaction":46,"./transactions/transferTransaction":47}],38:[function(require,module,exports){
'use strict';
var _network = require('../network');
var _network2 = _interopRequireDefault(_network);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _transactionTypes = require('../transactionTypes');
var _transactionTypes2 = _interopRequireDefault(_transactionTypes);
var _fees = require('../fees');
var _fees2 = _interopRequireDefault(_fees);
var _keyPair = require('../../crypto/keyPair');
var _keyPair2 = _interopRequireDefault(_keyPair);
var _objects = require('../objects');
var _objects2 = _interopRequireDefault(_objects);
var _multisigWrapper = require('./multisigWrapper');
var _multisigWrapper2 = _interopRequireDefault(_multisigWrapper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Prepare an importance transfer transaction object
*
* @param {object} common - A common object
* @param {object} tx - An un-prepared importanceTransferTransaction object
* @param {number} network - A network id
*
* @return {object} - An [ImportanceTransferTransaction]{@link https://bob.nem.ninja/docs/#importanceTransferTransaction} object ready for serialization
*/
var prepare = function prepare(common, tx, network) {
if (!common || !tx || !network) throw new Error('Missing parameter !');
var kp = _keyPair2.default.create(_helpers2.default.fixPrivateKey(common.privateKey));
var actualSender = tx.isMultisig ? tx.multisigAccount.publicKey : kp.publicKey.toString();
var due = network === _network2.default.data.testnet.id ? 60 : 24 * 60;
var entity = _construct(actualSender, tx.remoteAccount, tx.mode, due, network);
if (tx.isMultisig) {
entity = (0, _multisigWrapper2.default)(kp.publicKey.toString(), entity, due, network);
}
return entity;
};
/***
* Create an importance transfer transaction object
*
* @param {string} senderPublicKey - The sender account public key
* @param {string} remotePublicKey - The remote account public key
* @param {number} mode - 1 for activating, 2 for deactivating
* @param {number} due - The deadline in minutes
* @param {number} network - A network id
*
* @return {object} - An [ImportanceTransferTransaction]{@link https://bob.nem.ninja/docs/#importanceTransferTransaction} object
*/
var _construct = function _construct(senderPublicKey, remotePublicKey, mode, due, network) {
var timeStamp = _helpers2.default.createNEMTimeStamp();
var version = _network2.default.getVersion(1, network);
var data = _objects2.default.create("commonTransactionPart")(_transactionTypes2.default.importanceTransfer, senderPublicKey, timeStamp, due, version);
var fee = _fees2.default.importanceTransferTransaction;
var custom = {
'remoteAccount': remotePublicKey,
'mode': mode,
'fee': fee
};
var entity = _helpers2.default.extendObj(data, custom);
return entity;
};
module.exports = {
prepare: prepare
};
},{"../../crypto/keyPair":19,"../../utils/helpers":51,"../fees":25,"../network":26,"../objects":28,"../transactionTypes":36,"./multisigWrapper":43}],39:[function(require,module,exports){
'use strict';
var _cryptoHelpers = require('../../crypto/cryptoHelpers');
var _cryptoHelpers2 = _interopRequireDefault(_cryptoHelpers);
var _convert = require('../../utils/convert');
var _convert2 = _interopRequireDefault(_convert);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Prepare a message object
*
* @param {object} common - A common object
* @param {object} tx - An un-prepared transferTransaction object
*
* @return {object} - A prepared message object
*/
var prepare = function prepare(common, tx) {
if (tx.messageType === 2 && common.privateKey) {
return {
'type': 2,
'payload': _cryptoHelpers2.default.encode(common.privateKey, tx.recipientPublicKey, tx.message.toString())
};
} else if (tx.messageType === 2 && common.isHW) {
return {
'type': 2,
'payload': _convert2.default.utf8ToHex(tx.message.toString()),
'publicKey': tx.recipientPublicKey
};
} else if (tx.messageType === 0 && _helpers2.default.isHexadecimal(tx.message.toString())) {
return {
'type': 1,
'payload': 'fe' + tx.message.toString()
};
} else {
return {
'type': 1,
'payload': _convert2.default.utf8ToHex(tx.message.toString())
};
}
};
module.exports = {
prepare: prepare
};
},{"../../crypto/cryptoHelpers":18,"../../utils/convert":49,"../../utils/helpers":51}],40:[function(require,module,exports){
'use strict';
var _network = require('../network');
var _network2 = _interopRequireDefault(_network);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _transactionTypes = require('../transactionTypes');
var _transactionTypes2 = _interopRequireDefault(_transactionTypes);
var _fees = require('../fees');
var _fees2 = _interopRequireDefault(_fees);
var _keyPair = require('../../crypto/keyPair');
var _keyPair2 = _interopRequireDefault(_keyPair);
var _objects = require('../objects');
var _objects2 = _interopRequireDefault(_objects);
var _sinks = require('../sinks');
var _sinks2 = _interopRequireDefault(_sinks);
var _multisigWrapper = require('./multisigWrapper');
var _multisigWrapper2 = _interopRequireDefault(_multisigWrapper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Prepare a mosaic definition transaction
*
* @param {object} common - A common object
* @param {object} tx - An un-prepared mosaicDefinitionTransaction object
* @param {number} network - A network id
*
* @return {object} - A [MosaicDefinitionCreationTransaction]{@link http://bob.nem.ninja/docs/#mosaicDefinitionCreationTransaction} object ready for serialization
*/
var prepare = function prepare(common, tx, network) {
var kp = _keyPair2.default.create(_helpers2.default.fixPrivateKey(common.privateKey));
var actualSender = tx.isMultisig ? tx.multisigAccount.publicKey : kp.publicKey.toString();
var rentalFeeSink = _sinks2.default.mosaic[network].toUpperCase().replace(/-/g, '');
var rentalFee = _fees2.default.mosaicDefinitionTransaction;
var namespaceParent = tx.namespaceParent.fqn;
var mosaicName = tx.mosaicName.toString();
var mosaicDescription = tx.mosaicDescription.toString();
var mosaicProperties = tx.properties;
var levy = tx.levy.mosaic ? tx.levy : null;
var due = network === _network2.default.data.testnet.id ? 60 : 24 * 60;
var entity = _construct(actualSender, rentalFeeSink, rentalFee, namespaceParent, mosaicName, mosaicDescription, mosaicProperties, levy, due, network);
if (tx.isMultisig) {
entity = (0, _multisigWrapper2.default)(kp.publicKey.toString(), entity, due, network);
}
return entity;
};
/***
* Create a mosaic definition transaction object
*
* @param {string} senderPublicKey - The sender account public key
* @param {string} rentalFeeSink - The rental sink account
* @param {number} rentalFee - The rental fee
* @param {string} namespaceParent - The parent namespace
* @param {string} mosaicName - The mosaic name
* @param {string} mosaicDescription - The mosaic description
* @param {object} mosaicProperties - The mosaic properties object
* @param {object} levy - The levy object
* @param {number} due - The deadline in minutes
* @param {number} network - A network id
*
* @return {object} - A [MosaicDefinitionCreationTransaction]{@link http://bob.nem.ninja/docs/#mosaicDefinitionCreationTransaction} object
*/
var _construct = function _construct(senderPublicKey, rentalFeeSink, rentalFee, namespaceParent, mosaicName, mosaicDescription, mosaicProperties, levy, due, network) {
var timeStamp = _helpers2.default.createNEMTimeStamp();
var version = _network2.default.getVersion(1, network);
var data = _objects2.default.create("commonTransactionPart")(_transactionTypes2.default.mosaicDefinition, senderPublicKey, timeStamp, due, version);
var fee = _fees2.default.namespaceAndMosaicCommon;
var levyData = levy ? {
'type': levy.feeType,
'recipient': levy.address.toUpperCase().replace(/-/g, ''),
'mosaicId': levy.mosaic,
'fee': levy.fee
} : null;
var custom = {
'creationFeeSink': rentalFeeSink.replace(/-/g, ''),
'creationFee': rentalFee,
'mosaicDefinition': {
'creator': senderPublicKey,
'id': {
'namespaceId': namespaceParent,
'name': mosaicName
},
'description': mosaicDescription,
'properties': Object.keys(mosaicProperties).map(function (key, index) {
return { "name": key, "value": mosaicProperties[key].toString() };
}),
'levy': levyData
},
'fee': fee
};
var entity = _helpers2.default.extendObj(data, custom);
return entity;
};
module.exports = {
prepare: prepare
};
},{"../../crypto/keyPair":19,"../../utils/helpers":51,"../fees":25,"../network":26,"../objects":28,"../sinks":35,"../transactionTypes":36,"./multisigWrapper":43}],41:[function(require,module,exports){
'use strict';
var _network = require('../network');
var _network2 = _interopRequireDefault(_network);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _transactionTypes = require('../transactionTypes');
var _transactionTypes2 = _interopRequireDefault(_transactionTypes);
var _fees = require('../fees');
var _fees2 = _interopRequireDefault(_fees);
var _keyPair = require('../../crypto/keyPair');
var _keyPair2 = _interopRequireDefault(_keyPair);
var _objects = require('../objects');
var _objects2 = _interopRequireDefault(_objects);
var _multisigWrapper = require('./multisigWrapper');
var _multisigWrapper2 = _interopRequireDefault(_multisigWrapper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Prepare a mosaic supply change transaction
*
* @param {object} common - A common object
* @param {object} tx - An un-prepared mosaicSupplyChangeTransaction object
* @param {number} network - A network id
*
* @return {object} - A [MosaicSupplyChangeTransaction]{@link http://bob.nem.ninja/docs/#mosaicSupplyChangeTransaction} object ready for serialization
*/
var prepare = function prepare(common, tx, network) {
var kp = _keyPair2.default.create(_helpers2.default.fixPrivateKey(common.privateKey));
var actualSender = tx.isMultisig ? tx.multisigAccount.publicKey : kp.publicKey.toString();
var due = network === _network2.default.data.testnet.id ? 60 : 24 * 60;
var entity = _construct(actualSender, tx.mosaic, tx.supplyType, tx.delta, due, network);
if (tx.isMultisig) {
entity = (0, _multisigWrapper2.default)(kp.publicKey.toString(), entity, due, network);
}
return entity;
};
/***
* Create a mosaic supply change transaction object
*
* @param {string} senderPublicKey - The sender account public key
* @param {object} mosaicId - The mosaic id
* @param {number} supplyType - The type of change
* @param {number} delta - The amount involved in the change
* @param {number} due - The deadline in minutes
* @param {number} network - A network id
*
* @return {object} - A [MosaicSupplyChangeTransaction]{@link http://bob.nem.ninja/docs/#mosaicSupplyChangeTransaction} object
*/
var _construct = function _construct(senderPublicKey, mosaicId, supplyType, delta, due, network) {
var timeStamp = _helpers2.default.createNEMTimeStamp();
var version = _network2.default.getVersion(1, network);
var data = _objects2.default.create("commonTransactionPart")(_transactionTypes2.default.mosaicSupply, senderPublicKey, timeStamp, due, version);
var fee = _fees2.default.namespaceAndMosaicCommon;
var custom = {
'mosaicId': mosaicId,
'supplyType': supplyType,
'delta': delta,
'fee': fee
};
var entity = _helpers2.default.extendObj(data, custom);
return entity;
};
module.exports = {
prepare: prepare
};
},{"../../crypto/keyPair":19,"../../utils/helpers":51,"../fees":25,"../network":26,"../objects":28,"../transactionTypes":36,"./multisigWrapper":43}],42:[function(require,module,exports){
'use strict';
var _network = require('../network');
var _network2 = _interopRequireDefault(_network);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _transactionTypes = require('../transactionTypes');
var _transactionTypes2 = _interopRequireDefault(_transactionTypes);
var _keyPair = require('../../crypto/keyPair');
var _keyPair2 = _interopRequireDefault(_keyPair);
var _fees = require('../fees');
var _fees2 = _interopRequireDefault(_fees);
var _objects = require('../objects');
var _objects2 = _interopRequireDefault(_objects);
var _address = require('../address');
var _address2 = _interopRequireDefault(_address);
var _multisigWrapper = require('./multisigWrapper');
var _multisigWrapper2 = _interopRequireDefault(_multisigWrapper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Prepare a multisig aggregate modification transaction object
*
* @param {object} common - A common object
* @param {object} tx - An un-prepared multisigAggregateModificationTransaction object
* @param {number} network - A network id
*
* @return {object} - A [MultisigAggregateModificationTransaction]{@link http://bob.nem.ninja/docs/#multisigAggregateModificationTransaction} object ready for serialization
*/
var prepare = function prepare(common, tx, network) {
if (!common || !tx || !network) throw new Error('Missing parameter !');
var kp = _keyPair2.default.create(_helpers2.default.fixPrivateKey(common.privateKey));
var actualSender = tx.isMultisig ? tx.multisigAccount.publicKey : kp.publicKey.toString();
var due = network === _network2.default.data.testnet.id ? 60 : 24 * 60;
var entity = _construct(actualSender, tx.modifications, tx.relativeChange, tx.isMultisig, due, network);
if (tx.isMultisig) {
entity = (0, _multisigWrapper2.default)(kp.publicKey.toString(), entity, due, network);
}
return entity;
};
/**
* Create a multisignature aggregate modification transaction object
*
* @param {string} senderPublicKey - The sender account public key
* @param {array} modifications - An array of [MultisigCosignatoryModification]{@link http://bob.nem.ninja/docs/#multisigCosignatoryModification} objects
* @param {number} relativeChange - The number of signature to add or remove (ex: 1 to add +1 or -1 to remove one)
* @param {boolean} isMultisig - True if transaction is multisig, false otherwise
* @param {number} due - The deadline in minutes
* @param {number} network - A network id
*
* @return {object} - A [MultisigAggregateModificationTransaction]{@link http://bob.nem.ninja/docs/#multisigAggregateModificationTransaction} object
*/
var _construct = function _construct(senderPublicKey, modifications, relativeChange, isMultisig, due, network) {
var timeStamp = _helpers2.default.createNEMTimeStamp();
var hasNoRelativeChange = relativeChange === null || relativeChange === 0;
var version = hasNoRelativeChange ? _network2.default.getVersion(1, network) : _network2.default.getVersion(2, network);
var data = _objects2.default.create("commonTransactionPart")(_transactionTypes2.default.multisigModification, senderPublicKey, timeStamp, due, version);
var totalFee = _fees2.default.multisigAggregateModificationTransaction;
var custom = {
'fee': totalFee,
'modifications': modifications,
'minCosignatories': {
'relativeChange': 0
}
// If multisig, it is a modification of an existing contract, otherwise it is a creation
};if (isMultisig) {
// If no relative change, no minCosignatories property
if (hasNoRelativeChange) delete custom.minCosignatories;else custom.minCosignatories.relativeChange = relativeChange;
// Sort modification array
if (custom.modifications.length > 1) {
custom.modifications.sort(function (a, b) {
return a.modificationType - b.modificationType || _address2.default.toAddress(a.cosignatoryAccount, network).localeCompare(_address2.default.toAddress(b.cosignatoryAccount, network));
});
}
} else {
custom.minCosignatories.relativeChange = relativeChange;
// Sort modification array by addresses
if (custom.modifications.length > 1) {
custom.modifications.sort(function (a, b) {
if (_address2.default.toAddress(a.cosignatoryAccount, network) < _address2.default.toAddress(b.cosignatoryAccount, network)) return -1;
if (_address2.default.toAddress(a.cosignatoryAccount, network) > _address2.default.toAddress(b.cosignatoryAccount, network)) return 1;
return 0;
});
}
}
var entity = _helpers2.default.extendObj(data, custom);
return entity;
};
module.exports = {
prepare: prepare
};
},{"../../crypto/keyPair":19,"../../utils/helpers":51,"../address":23,"../fees":25,"../network":26,"../objects":28,"../transactionTypes":36,"./multisigWrapper":43}],43:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _network = require('../network');
var _network2 = _interopRequireDefault(_network);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _transactionTypes = require('../transactionTypes');
var _transactionTypes2 = _interopRequireDefault(_transactionTypes);
var _fees = require('../fees');
var _fees2 = _interopRequireDefault(_fees);
var _objects = require('../objects');
var _objects2 = _interopRequireDefault(_objects);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Wrap a transaction in a multisignature transaction
*
* @param {string} senderPublicKey - The sender public key
* @param {object} innerEntity - The transaction entity to wrap
* @param {number} due - The transaction deadline in minutes
* @param {number} network - A network id
*
* @return {object} - A [MultisigTransaction]{@link http://bob.nem.ninja/docs/#multisigTransaction} object
*/
var multisigWrapper = function multisigWrapper(senderPublicKey, innerEntity, due, network) {
var timeStamp = _helpers2.default.createNEMTimeStamp();
var version = _network2.default.getVersion(1, network);
var data = _objects2.default.create("commonTransactionPart")(_transactionTypes2.default.multisigTransaction, senderPublicKey, timeStamp, due, version, network);
var custom = {
'fee': _fees2.default.multisigTransaction,
'otherTrans': innerEntity
};
var entity = _helpers2.default.extendObj(data, custom);
return entity;
};
exports.default = multisigWrapper;
},{"../../utils/helpers":51,"../fees":25,"../network":26,"../objects":28,"../transactionTypes":36}],44:[function(require,module,exports){
'use strict';
var _network = require('../network');
var _network2 = _interopRequireDefault(_network);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _transactionTypes = require('../transactionTypes');
var _transactionTypes2 = _interopRequireDefault(_transactionTypes);
var _fees = require('../fees');
var _fees2 = _interopRequireDefault(_fees);
var _keyPair = require('../../crypto/keyPair');
var _keyPair2 = _interopRequireDefault(_keyPair);
var _objects = require('../objects');
var _objects2 = _interopRequireDefault(_objects);
var _sinks = require('../sinks');
var _sinks2 = _interopRequireDefault(_sinks);
var _multisigWrapper = require('./multisigWrapper');
var _multisigWrapper2 = _interopRequireDefault(_multisigWrapper);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Prepare a namespace provision transaction object
*
* @param {object} common - A common object
* @param {object} tx - An un-prepared namespaceProvisionTransaction object
* @param {number} network - A network id
*
* @return {object} - A [ProvisionNamespaceTransaction]{@link http://bob.nem.ninja/docs/#provisionNamespaceTransaction} object ready for serialization
*/
var prepare = function prepare(common, tx, network) {
if (!common || !tx || !network) throw new Error('Missing parameter !');
var kp = _keyPair2.default.create(_helpers2.default.fixPrivateKey(common.privateKey));
var actualSender = tx.isMultisig ? tx.multisigAccount.publicKey : kp.publicKey.toString();
var rentalFeeSink = _sinks2.default.namespace[network].toUpperCase().replace(/-/g, '');
var rentalFee = void 0;
// Set fee depending if namespace or sub
if (tx.namespaceParent) {
rentalFee = _fees2.default.subProvisionNamespaceTransaction;
} else {
rentalFee = _fees2.default.rootProvisionNamespaceTransaction;
}
var namespaceParent = tx.namespaceParent ? tx.namespaceParent.fqn : null;
var namespaceName = tx.namespaceName.toString();
var due = network === _network2.default.data.testnet.id ? 60 : 24 * 60;
var entity = _construct(actualSender, rentalFeeSink, rentalFee, namespaceParent, namespaceName, due, network);
if (tx.isMultisig) {
entity = (0, _multisigWrapper2.default)(kp.publicKey.toString(), entity, due, network);
}
return entity;
};
/***
* Create a namespace provision transaction object
*
* @param {string} senderPublicKey - The sender account public key
* @param {string} rentalFeeSink - The rental sink account
* @param {number} rentalFee - The rental fee
* @param {string} namespaceParent - The parent namespace
* @param {string} namespaceName - The namespace name
* @param {number} due - The deadline in minutes
* @param {number} network - A network id
*
* @return {object} - A [ProvisionNamespaceTransaction]{@link http://bob.nem.ninja/docs/#provisionNamespaceTransaction} object
*/
var _construct = function _construct(senderPublicKey, rentalFeeSink, rentalFee, namespaceParent, namespaceName, due, network) {
var timeStamp = _helpers2.default.createNEMTimeStamp();
var version = _network2.default.getVersion(1, network);
var data = _objects2.default.create("commonTransactionPart")(_transactionTypes2.default.provisionNamespace, senderPublicKey, timeStamp, due, version);
var fee = _fees2.default.namespaceAndMosaicCommon;
var custom = {
'rentalFeeSink': rentalFeeSink.toUpperCase().replace(/-/g, ''),
'rentalFee': rentalFee,
'parent': namespaceParent,
'newPart': namespaceName,
'fee': fee
};
var entity = _helpers2.default.extendObj(data, custom);
return entity;
};
module.exports = {
prepare: prepare
};
},{"../../crypto/keyPair":19,"../../utils/helpers":51,"../fees":25,"../network":26,"../objects":28,"../sinks":35,"../transactionTypes":36,"./multisigWrapper":43}],45:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _convert = require('../../utils/convert');
var _convert2 = _interopRequireDefault(_convert);
var _serialization = require('../../utils/serialization');
var _serialization2 = _interopRequireDefault(_serialization);
var _keyPair = require('../../crypto/keyPair');
var _keyPair2 = _interopRequireDefault(_keyPair);
var _requests = require('../../com/requests');
var _requests2 = _interopRequireDefault(_requests);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Serialize a transaction and broadcast it to the network
*
* @param {object} common - A common object
* @param {object} entity - A prepared transaction object
* @param {object} endpoint - An NIS endpoint object
*
* @return {promise} - An announce transaction promise of the com.requests service
*/
var send = function send(common, entity, endpoint) {
if (!endpoint || !entity || !common) throw new Error('Missing parameter !');
if (common.privateKey.length !== 64 && common.privateKey.length !== 66) throw new Error('Invalid private key, length must be 64 or 66 characters !');
if (!_helpers2.default.isHexadecimal(common.privateKey)) throw new Error('Private key must be hexadecimal only !');
var kp = _keyPair2.default.create(_helpers2.default.fixPrivateKey(common.privateKey));
var result = _serialization2.default.serializeTransaction(entity);
var signature = kp.sign(result);
var obj = {
'data': _convert2.default.ua2hex(result),
'signature': signature.toString()
};
return _requests2.default.transaction.announce(endpoint, JSON.stringify(obj));
};
exports.default = send;
},{"../../com/requests":6,"../../crypto/keyPair":19,"../../utils/convert":49,"../../utils/helpers":51,"../../utils/serialization":53}],46:[function(require,module,exports){
'use strict';
var _network = require('../network');
var _network2 = _interopRequireDefault(_network);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _transactionTypes = require('../transactionTypes');
var _transactionTypes2 = _interopRequireDefault(_transactionTypes);
var _fees = require('../fees');
var _fees2 = _interopRequireDefault(_fees);
var _keyPair = require('../../crypto/keyPair');
var _keyPair2 = _interopRequireDefault(_keyPair);
var _objects = require('../objects');
var _objects2 = _interopRequireDefault(_objects);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Prepare a signature transaction object
*
* @param {object} common - A common object
* @param {object} tx - The un-prepared signature transaction object
* @param {number} network - A network id
*
* @return {object} - A [MultisigSignatureTransaction]{@link http://bob.nem.ninja/docs/#multisigSignatureTransaction} object ready for serialization
*/
var prepare = function prepare(common, tx, network) {
if (!common || !tx || !network) throw new Error('Missing parameter !');
var kp = _keyPair2.default.create(_helpers2.default.fixPrivateKey(common.privateKey));
var due = network === _network2.default.data.testnet.id ? 60 : 24 * 60;
var senderPublicKey = kp.publicKey.toString();
var timeStamp = _helpers2.default.createNEMTimeStamp();
var version = _network2.default.getVersion(1, network);
var data = _objects2.default.create("commonTransactionPart")(_transactionTypes2.default.multisigSignature, senderPublicKey, timeStamp, due, version);
var fee = _fees2.default.signatureTransaction;
var custom = {
'fee': fee
};
var entity = _helpers2.default.extendObj(tx, data, custom);
return entity;
};
module.exports = {
prepare: prepare
};
},{"../../crypto/keyPair":19,"../../utils/helpers":51,"../fees":25,"../network":26,"../objects":28,"../transactionTypes":36}],47:[function(require,module,exports){
'use strict';
var _network = require('../network');
var _network2 = _interopRequireDefault(_network);
var _helpers = require('../../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _transactionTypes = require('../transactionTypes');
var _transactionTypes2 = _interopRequireDefault(_transactionTypes);
var _fees = require('../fees');
var _fees2 = _interopRequireDefault(_fees);
var _keyPair = require('../../crypto/keyPair');
var _keyPair2 = _interopRequireDefault(_keyPair);
var _objects = require('../objects');
var _objects2 = _interopRequireDefault(_objects);
var _multisigWrapper = require('./multisigWrapper');
var _multisigWrapper2 = _interopRequireDefault(_multisigWrapper);
var _message = require('./message');
var _message2 = _interopRequireDefault(_message);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Prepare a transfer transaction object
*
* @param {object} common - A common object
* @param {object} tx - The un-prepared transfer transaction object
* @param {number} network - A network id
*
* @return {object} - A [TransferTransaction]{@link http://bob.nem.ninja/docs/#transferTransaction} object ready for serialization
*/
var prepare = function prepare(common, tx, network) {
if (!common || !tx || !network) throw new Error('Missing parameter !');
var kp = _keyPair2.default.create(_helpers2.default.fixPrivateKey(common.privateKey));
var actualSender = tx.isMultisig ? tx.multisigAccount.publicKey : kp.publicKey.toString();
var recipientCompressedKey = tx.recipient.toString();
var amount = Math.round(tx.amount * 1000000);
var message = _message2.default.prepare(common, tx);
var msgFee = _fees2.default.calculateMessage(message, common.isHW);
var due = network === _network2.default.data.testnet.id ? 60 : 24 * 60;
var mosaics = null;
var mosaicsFee = null;
var entity = _construct(actualSender, recipientCompressedKey, amount, message, msgFee, due, mosaics, mosaicsFee, network);
if (tx.isMultisig) {
entity = (0, _multisigWrapper2.default)(kp.publicKey.toString(), entity, due, network);
}
return entity;
};
/**
* Prepare a mosaic transfer transaction object
*
* @param {object} common - A common object
* @param {object} tx - The un-prepared transfer transaction object
* @param {object} mosaicDefinitionMetaDataPair - The mosaicDefinitionMetaDataPair object with properties of mosaics to send
* @param {number} network - A network id
*
* @return {object} - A [TransferTransaction]{@link http://bob.nem.ninja/docs/#transferTransaction} object ready for serialization
*/
var prepareMosaic = function prepareMosaic(common, tx, mosaicDefinitionMetaDataPair, network) {
if (!common || !tx || !mosaicDefinitionMetaDataPair || tx.mosaics === null || !network) throw new Error('Missing parameter !');
var kp = _keyPair2.default.create(_helpers2.default.fixPrivateKey(common.privateKey));
var actualSender = tx.isMultisig ? tx.multisigAccount.publicKey : kp.publicKey.toString();
var recipientCompressedKey = tx.recipient.toString();
var amount = Math.round(tx.amount * 1000000);
var message = _message2.default.prepare(common, tx);
var msgFee = _fees2.default.calculateMessage(message, common.isHW);
var due = network === _network2.default.data.testnet.id ? 60 : 24 * 60;
var mosaics = tx.mosaics;
var mosaicsFee = _fees2.default.calculateMosaics(amount, mosaicDefinitionMetaDataPair, mosaics);
var entity = _construct(actualSender, recipientCompressedKey, amount, message, msgFee, due, mosaics, mosaicsFee, network);
if (tx.isMultisig) {
entity = (0, _multisigWrapper2.default)(kp.publicKey.toString(), entity, due, network);
}
return entity;
};
/***
* Create a transfer transaction object
*
* @param {string} senderPublicKey - The sender account public key
* @param {string} recipientCompressedKey - The recipient account public key
* @param {number} amount - The amount to send in micro XEM
* @param {object} message - The message object
* @param {number} due - The deadline in minutes
* @param {array} mosaics - The array of mosaics to send
* @param {number} mosaicFee - The fees for mosaics included in the transaction
* @param {number} network - A network id
*
* @return {object} - A [TransferTransaction]{@link http://bob.nem.ninja/docs/#transferTransaction} object
*/
var _construct = function _construct(senderPublicKey, recipientCompressedKey, amount, message, msgFee, due, mosaics, mosaicsFee, network) {
var timeStamp = _helpers2.default.createNEMTimeStamp();
var version = mosaics ? _network2.default.getVersion(2, network) : _network2.default.getVersion(1, network);
var data = _objects2.default.create("commonTransactionPart")(_transactionTypes2.default.transfer, senderPublicKey, timeStamp, due, version);
var fee = mosaics ? mosaicsFee : _fees2.default.currentFeeFactor * _fees2.default.calculateMinimum(amount / 1000000);
var totalFee = Math.floor((msgFee + fee) * 1000000);
var custom = {
'recipient': recipientCompressedKey.toUpperCase().replace(/-/g, ''),
'amount': amount,
'fee': totalFee,
'message': message,
'mosaics': mosaics
};
var entity = _helpers2.default.extendObj(data, custom);
return entity;
};
module.exports = {
prepare: prepare,
prepareMosaic: prepareMosaic
};
},{"../../crypto/keyPair":19,"../../utils/helpers":51,"../fees":25,"../network":26,"../objects":28,"../transactionTypes":36,"./message":39,"./multisigWrapper":43}],48:[function(require,module,exports){
'use strict';
var _naclFast = require('../external/nacl-fast');
var _naclFast2 = _interopRequireDefault(_naclFast);
var _convert = require('../utils/convert');
var _convert2 = _interopRequireDefault(_convert);
var _helpers = require('../utils/helpers');
var _helpers2 = _interopRequireDefault(_helpers);
var _keyPair = require('../crypto/keyPair');
var _keyPair2 = _interopRequireDefault(_keyPair);
var _cryptoHelpers = require('../crypto/cryptoHelpers');
var _cryptoHelpers2 = _interopRequireDefault(_cryptoHelpers);
var _address = require('../model/address');
var _address2 = _interopRequireDefault(_address);
var _objects = require('./objects');
var _objects2 = _interopRequireDefault(_objects);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Create a wallet containing a private key generated using a Pseudo Random Number Generator
*
* @param {string} walletName - The wallet name
* @param {string} password - The wallet password
* @param {number} network - The network id
*
* @return {object} - A PRNG wallet object
*/
var createPRNG = function createPRNG(walletName, password, network) {
if (!walletName.length || !password.length || !network) throw new Error('A parameter is missing !');
// Generate keypair from random private key
var privateKey = _convert2.default.ua2hex(_naclFast2.default.randomBytes(32));
var kp = _keyPair2.default.create(privateKey);
// Create address from public key
var addr = _address2.default.toAddress(kp.publicKey.toString(), network);
// Encrypt private key using password
var encrypted = _cryptoHelpers2.default.encodePrivKey(privateKey, password);
return _objects2.default.create("wallet")(walletName, addr, true, "pass:bip32", encrypted, network);
};
/**
* Create a wallet containing a private key generated using a derived passphrase
*
* @param {string} walletName - The wallet name
* @param {string} passphrase - The wallet passphrase
* @param {number} network - The network id
*
* @return {object} - A Brain wallet object
*/
var createBrain = function createBrain(walletName, passphrase, network) {
if (!walletName.length || !passphrase.length || !network) throw new Error('A parameter is missing !');
var privateKey = _cryptoHelpers2.default.derivePassSha(passphrase, 6000).priv;
var kp = _keyPair2.default.create(privateKey);
// Create address from public key
var addr = _address2.default.toAddress(kp.publicKey.toString(), network);
return _objects2.default.create("wallet")(walletName, addr, true, "pass:6k", "", network);
};
/**
* Create a wallet containing any private key
*
* @param {string} walletName - The wallet name
* @param {string} password - The wallet passphrase
* @param {string} privateKey - The private key to import
* @param {number} network - The network id
*
* @return {object} - A private key wallet object
*/
var importPrivateKey = function importPrivateKey(walletName, password, privateKey, network) {
if (!walletName.length || !password.length || !network || !privateKey) throw new Error('A parameter is missing !');
if (!_helpers2.default.isPrivateKeyValid(privateKey)) throw new Error('Private key is not valid !');
// Create address from private key
var kp = _keyPair2.default.create(privateKey);
var addr = _address2.default.toAddress(kp.publicKey.toString(), network);
// Encrypt private key using password
var encrypted = _cryptoHelpers2.default.encodePrivKey(privateKey, password);
return _objects2.default.create("wallet")(walletName, addr, false, "pass:enc", encrypted, network);
};
module.exports = {
createPRNG: createPRNG,
createBrain: createBrain,
importPrivateKey: importPrivateKey
};
},{"../crypto/cryptoHelpers":18,"../crypto/keyPair":19,"../external/nacl-fast":20,"../model/address":23,"../utils/convert":49,"../utils/helpers":51,"./objects":28}],49:[function(require,module,exports){
'use strict';
var _cryptoJs = require('crypto-js');
var _cryptoJs2 = _interopRequireDefault(_cryptoJs);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _hexEncodeArray = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
/**
* Reversed convertion of hex to Uint8Array
*
* @param {string} hexx - An hex string
*
* @return {Uint8Array}
*/
var hex2ua_reversed = function hex2ua_reversed(hexx) {
var hex = hexx.toString(); //force conversion
var ua = new Uint8Array(hex.length / 2);
for (var i = 0; i < hex.length; i += 2) {
ua[ua.length - 1 - i / 2] = parseInt(hex.substr(i, 2), 16);
}
return ua;
};
/**
* Convert hex to Uint8Array
*
* @param {string} hexx - An hex string
*
* @return {Uint8Array}
*/
var hex2ua = function hex2ua(hexx) {
var hex = hexx.toString(); //force conversion
var ua = new Uint8Array(hex.length / 2);
for (var i = 0; i < hex.length; i += 2) {
ua[i / 2] = parseInt(hex.substr(i, 2), 16);
}
return ua;
};
/**
* Convert an Uint8Array to hex
*
* @param {Uint8Array} ua - An Uint8Array
*
* @return {string}
*/
var ua2hex = function ua2hex(ua) {
var s = '';
for (var i = 0; i < ua.length; i++) {
var code = ua[i];
s += _hexEncodeArray[code >>> 4];
s += _hexEncodeArray[code & 0x0F];
}
return s;
};
/**
* Convert hex to string
*
* @param {string} hexx - An hex string
*
* @return {string}
*/
var hex2a = function hex2a(hexx) {
var hex = hexx.toString();
var str = '';
for (var i = 0; i < hex.length; i += 2) {
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
}return str;
};
/**
* Convert UTF-8 to hex
*
* @param {string} str - An UTF-8 string
*
* @return {string}
*/
var utf8ToHex = function utf8ToHex(str) {
var rawString = rstr2utf8(str);
var hex = "";
for (var i = 0; i < rawString.length; i++) {
hex += strlpad(rawString.charCodeAt(i).toString(16), "0", 2);
}
return hex;
};
// Padding helper for above function
var strlpad = function strlpad(str, pad, len) {
while (str.length < len) {
str = pad + str;
}
return str;
};
/**
* Convert an Uint8Array to WordArray
*
* @param {Uint8Array} ua - An Uint8Array
* @param {number} uaLength - The Uint8Array length
*
* @return {WordArray}
*/
var ua2words = function ua2words(ua, uaLength) {
var temp = [];
for (var i = 0; i < uaLength; i += 4) {
var x = ua[i] * 0x1000000 + (ua[i + 1] || 0) * 0x10000 + (ua[i + 2] || 0) * 0x100 + (ua[i + 3] || 0);
temp.push(x > 0x7fffffff ? x - 0x100000000 : x);
}
return _cryptoJs2.default.lib.WordArray.create(temp, uaLength);
};
/**
* Convert a wordArray to Uint8Array
*
* @param {Uint8Array} destUa - A destination Uint8Array
* @param {WordArray} cryptowords - A wordArray
*
* @return {Uint8Array}
*/
var words2ua = function words2ua(destUa, cryptowords) {
for (var i = 0; i < destUa.length; i += 4) {
var v = cryptowords.words[i / 4];
if (v < 0) v += 0x100000000;
destUa[i] = v >>> 24;
destUa[i + 1] = v >>> 16 & 0xff;
destUa[i + 2] = v >>> 8 & 0xff;
destUa[i + 3] = v & 0xff;
}
return destUa;
};
/**
* Converts a raw javascript string into a string of single byte characters using utf8 encoding.
* This makes it easier to perform other encoding operations on the string.
*
* @param {string} input - A raw string
*
* @return {string} - UTF-8 string
*/
var rstr2utf8 = function rstr2utf8(input) {
var output = "";
for (var n = 0; n < input.length; n++) {
var c = input.charCodeAt(n);
if (c < 128) {
output += String.fromCharCode(c);
} else if (c > 127 && c < 2048) {
output += String.fromCharCode(c >> 6 | 192);
output += String.fromCharCode(c & 63 | 128);
} else {
output += String.fromCharCode(c >> 12 | 224);
output += String.fromCharCode(c >> 6 & 63 | 128);
output += String.fromCharCode(c & 63 | 128);
}
}
return output;
};
// Does the reverse of rstr2utf8.
var utf82rstr = function utf82rstr(input) {
var output = "",
i = 0,
c = 0,
c1 = 0,
c2 = 0,
c3 = 0;
while (i < input.length) {
c = input.charCodeAt(i);
if (c < 128) {
output += String.fromCharCode(c);
i++;
} else if (c > 191 && c < 224) {
c2 = input.charCodeAt(i + 1);
output += String.fromCharCode((c & 31) << 6 | c2 & 63);
i += 2;
} else {
c2 = input.charCodeAt(i + 1);
c3 = input.charCodeAt(i + 2);
output += String.fromCharCode((c & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
i += 3;
}
}
return output;
};
module.exports = {
hex2ua_reversed: hex2ua_reversed,
hex2ua: hex2ua,
ua2hex: ua2hex,
hex2a: hex2a,
utf8ToHex: utf8ToHex,
ua2words: ua2words,
words2ua: words2ua,
rstr2utf8: rstr2utf8,
utf82rstr: utf82rstr
};
},{"crypto-js":179}],50:[function(require,module,exports){
'use strict';
var _convert = require('./convert');
var _convert2 = _interopRequireDefault(_convert);
var _address = require('../model/address');
var _address2 = _interopRequireDefault(_address);
var _transactionTypes = require('../model/transactionTypes');
var _transactionTypes2 = _interopRequireDefault(_transactionTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Convert a public key to NEM address
*
* @param {string} input - The account public key
* @param {number} networkId - The current network id
*
* @return {string} - A clean NEM address
*/
var pubToAddress = function pubToAddress(input, networkId) {
return input && _address2.default.toAddress(input, networkId);
};
/**
* Add hyphens to a clean address
*
* @param {string} input - A NEM address
*
* @return {string} - A formatted NEM address
*/
var address = function address(input) {
return input && input.toUpperCase().replace(/-/g, '').match(/.{1,6}/g).join('-');
};
/**
* Format a timestamp to NEM date
*
* @param {number} data - A timestamp
*
* @return {string} - A date string
*/
var nemDate = function nemDate(data) {
var nemesis = Date.UTC(2015, 2, 29, 0, 6, 25);
if (data === undefined) return data;
var o = data;
var t = new Date(nemesis + o * 1000);
return t.toUTCString();
};
var supply = function supply(data, mosaicId, mosaics) {
if (data === undefined) return data;
var mosaicName = mosaicIdToName(mosaicId);
if (!(mosaicName in mosaics)) {
return ['unknown mosaic divisibility', data];
}
var mosaicDefinitionMetaDataPair = mosaics[mosaicName];
var divisibilityProperties = $.grep(mosaicDefinitionMetaDataPair.mosaicDefinition.properties, function (w) {
return w.name === "divisibility";
});
var divisibility = divisibilityProperties.length === 1 ? ~~divisibilityProperties[0].value : 0;
var o = parseInt(data, 10);
if (!o) {
if (divisibility === 0) {
return ["0", ''];
} else {
return ["0", o.toFixed(divisibility).split('.')[1]];
}
}
o = o / Math.pow(10, divisibility);
var b = o.toFixed(divisibility).split('.');
var r = b[0].split(/(?=(?:...)*$)/).join(" ");
return [r, b[1] || ""];
};
var supplyRaw = function supplyRaw(data, _divisibility) {
var divisibility = ~~_divisibility;
var o = parseInt(data, 10);
if (!o) {
if (divisibility === 0) {
return ["0", ''];
} else {
return ["0", o.toFixed(divisibility).split('.')[1]];
}
}
o = o / Math.pow(10, divisibility);
var b = o.toFixed(divisibility).split('.');
var r = b[0].split(/(?=(?:...)*$)/).join(" ");
return [r, b[1] || ""];
};
var levyFee = function levyFee(mosaic, multiplier, levy, mosaics) {
if (mosaic === undefined || mosaics === undefined) return mosaic;
if (levy === undefined || levy.type === undefined) return undefined;
var levyValue = void 0;
if (levy.type === 1) {
levyValue = levy.fee;
} else {
// Note, multiplier is in micro NEM
levyValue = multiplier / 1000000 * mosaic.quantity * levy.fee / 10000;
}
var r = supply(levyValue, levy.mosaicId, mosaics);
return r[0] + "." + r[1];
};
/**
* Format a NEM importance score
*
* @param {number} data - The importance score
*
* @return {array} - A formatted importance score at 10^-4
*/
var nemImportanceScore = function nemImportanceScore(data) {
if (data === undefined) return data;
var o = data;
if (o) {
o *= 10000;
o = o.toFixed(4).split('.');
return [o[0], o[1]];
}
return [o, 0];
};
/**
* Format a value to NEM value
*
* @param {number} data - An amount of XEM
*
* @return {array} - An array with values before and after decimal point
*/
var nemValue = function nemValue(data) {
if (data === undefined) return data;
var o = data;
if (!o) {
return ["0", '000000'];
} else {
o = o / 1000000;
var b = o.toFixed(6).split('.');
var r = b[0].split(/(?=(?:...)*$)/).join(" ");
return [r, b[1]];
}
};
/**
* Return name of an importance transfer mode
*
* @return {string} - An importance transfer mode name
*/
var importanceTransferMode = function importanceTransferMode(data) {
if (data === undefined) return data;
var o = data;
if (o === 1) return "Activation";else if (o === 2) return "Deactivation";else return "Unknown";
};
/**
* Convert hex to utf8
*
* @param {string} data - Hex data
*
* @return {string} result - Utf8 string
*/
var hexToUtf8 = function hexToUtf8(data) {
if (data === undefined) return data;
var o = data;
if (o && o.length > 2 && o[0] === 'f' && o[1] === 'e') {
return "HEX: " + o.slice(2);
}
var result = void 0;
try {
result = decodeURIComponent(escape(_convert2.default.hex2a(o)));
} catch (e) {
//result = "Error, message not properly encoded !";
result = _convert2.default.hex2a(o);
console.log('invalid text input: ' + data);
}
//console.log(decodeURIComponent(escape( convert.hex2a(o) )));*/
//result = convert.hex2a(o);
return result;
};
/**
* Verify if message is not encrypted and return utf8
*
* @param {object} msg - A message object
*
* @return {string} result - Utf8 string
*/
var hexMessage = function hexMessage(msg) {
if (msg === undefined) return msg;
if (msg.type === 1) {
return hexToUtf8(msg.payload);
} else {
return '';
}
};
/**
* Split hex string into 64 characters segments
*
* @param {string} data - An hex string
*
* @return {array} - A segmented hex string
*/
var splitHex = function splitHex(data) {
if (data === undefined) return data;
var parts = data.match(/[\s\S]{1,64}/g) || [];
var r = parts.join("\n");
return r;
};
/**
* Return mosaic name from mosaicId object
*
* @param {object} mosaicId - A mosaicId object
*
* @return {string} - The mosaic name
*/
var mosaicIdToName = function mosaicIdToName(mosaicId) {
if (!mosaicId) return mosaicId;
return mosaicId.namespaceId + ":" + mosaicId.name;
};
/**
* Return the name of a transaction type id
*
* @param {number} id - A transaction type id
*
* @return {string} - The transaction type name
*/
var txTypeToName = function txTypeToName(id) {
switch (id) {
case _transactionTypes2.default.transfer:
return 'Transfer';
case _transactionTypes2.default.importanceTransfer:
return 'ImportanceTransfer';
case _transactionTypes2.default.multisigModification:
return 'MultisigModification';
case _transactionTypes2.default.provisionNamespace:
return 'ProvisionNamespace';
case _transactionTypes2.default.mosaicDefinition:
return 'MosaicDefinition';
case _transactionTypes2.default.mosaicSupply:
return 'MosaicSupply';
default:
return 'Unknown_' + id;
}
};
module.exports = {
splitHex: splitHex,
hexMessage: hexMessage,
hexToUtf8: hexToUtf8,
importanceTransferMode: importanceTransferMode,
nemValue: nemValue,
nemImportanceScore: nemImportanceScore,
levyFee: levyFee,
supplyRaw: supplyRaw,
supply: supply,
nemDate: nemDate,
pubToAddress: pubToAddress,
address: address,
mosaicIdToName: mosaicIdToName,
txTypeToName: txTypeToName
};
},{"../model/address":23,"../model/transactionTypes":36,"./convert":49}],51:[function(require,module,exports){
'use strict';
var _convert = require('./convert');
var _convert2 = _interopRequireDefault(_convert);
var _format = require('./format');
var _format2 = _interopRequireDefault(_format);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Check if a multisig transaction needs signature
*
* @param {object} multisigTransaction - A multisig transaction
* @param {object} data - An account data
*
* @return {boolean} - True if it needs signature, false otherwise
*/
var needsSignature = function needsSignature(multisigTransaction, data) {
if (multisigTransaction.transaction.signer === data.account.publicKey) {
return false;
}
if (multisigTransaction.transaction.otherTrans.signer === data.account.publicKey) {
return false;
}
// Check if we're already on list of signatures
for (var i = 0; i < multisigTransaction.transaction.signatures.length; i++) {
if (multisigTransaction.transaction.signatures[i].signer === data.account.publicKey) {
return false;
}
}
if (!data.meta.cosignatoryOf.length) {
return false;
} else {
for (var k = 0; k < data.meta.cosignatoryOf.length; k++) {
if (data.meta.cosignatoryOf[k].publicKey === multisigTransaction.transaction.otherTrans.signer) {
return true;
} else if (k === data.meta.cosignatoryOf.length - 1) {
return false;
}
}
}
return true;
};
/**
* Check if a transaction is already present in an array of transactions
*
* @param {string} hash - A transaction hash
* @param {array} array - An array of transactions
*
* @return {boolean} - True if present, false otherwise
*/
var haveTx = function haveTx(hash, array) {
var i = null;
for (i = 0; array.length > i; i++) {
if (array[i].meta.hash.data === hash) {
return true;
}
}
return false;
};
/**
* Gets the index of a transaction in an array of transactions.
* It must be present in the array.
*
* @param {string} hash - A transaction hash
* @param {array} array - An array of transactions
*
* @return {number} - The index of the transaction
*/
var getTransactionIndex = function getTransactionIndex(hash, array) {
var i = null;
for (i = 0; array.length > i; i++) {
if (array[i].meta.hash.data === hash) {
return i;
}
}
return 0;
};
/**
* Check if a cosignatory is already present in modifications array
*
* @param {string} pubKey - A cosignatory public key
* @param {array} array - A modifications array
*
* @return {boolean} - True if present, false otherwise
*/
var haveCosig = function haveCosig(pubKey, array) {
var i = null;
for (i = 0; array.length > i; i++) {
if (array[i].cosignatoryAccount === pubKey) {
return true;
}
}
return false;
};
/***
* NEM epoch time
*
* @type {number}
*/
var NEM_EPOCH = Date.UTC(2015, 2, 29, 0, 6, 25, 0);
/**
* Create a time stamp for a NEM transaction
*
* @return {number} - The NEM transaction time stamp in milliseconds
*/
var createNEMTimeStamp = function createNEMTimeStamp() {
return Math.floor(Date.now() / 1000 - NEM_EPOCH / 1000);
};
/**
* Fix a private key
*
* @param {string} privatekey - An hex private key
*
* @return {string} - The fixed hex private key
*/
var fixPrivateKey = function fixPrivateKey(privateKey) {
return ("0000000000000000000000000000000000000000000000000000000000000000" + privateKey.replace(/^00/, '')).slice(-64);
};
/**
* Check if a private key is valid
*
* @param {string} privatekey - A private key
*
* @return {boolean} - True if valid, false otherwise
*/
var isPrivateKeyValid = function isPrivateKeyValid(privateKey) {
if (privateKey.length !== 64 && privateKey.length !== 66) {
console.error('Private key length must be 64 or 66 characters !');
return false;
} else if (!isHexadecimal(privateKey)) {
console.error('Private key must be hexadecimal only !');
return false;
} else {
return true;
}
};
/**
* Check if a public key is valid
*
* @param {string} publicKey - A public key
*
* @return {boolean} - True if valid, false otherwise
*/
var isPublicKeyValid = function isPublicKeyValid(publicKey) {
if (publicKey.length !== 64) {
console.error('Public key length must be 64 or 66 characters !');
return false;
} else if (!isHexadecimal(publicKey)) {
console.error('Public key must be hexadecimal only !');
return false;
} else {
return true;
}
};
/**
* Create a time stamp
*
* @return {object} - A date object
*/
var createTimeStamp = function createTimeStamp() {
return new Date();
};
/**
* Date object to YYYY-MM-DD format
*
* @param {object} date - A date object
*
* @return {string} - The short date
*/
var getTimestampShort = function getTimestampShort(date) {
var dd = date.getDate();
var mm = date.getMonth() + 1; //January is 0!
var yyyy = date.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
return yyyy + '-' + mm + '-' + dd;
};
/**
* Date object to date string
*
* @param {object} date - A date object
*
* @return {string} - The date string
*/
var convertDateToString = function convertDateToString(date) {
return date.toDateString();
};
/**
* Mimics jQuery's extend function
*
* http://stackoverflow.com/a/11197343
*/
var extendObj = function extendObj() {
for (var i = 1; i < arguments.length; i++) {
for (var key in arguments[i]) {
if (arguments[i].hasOwnProperty(key)) {
arguments[0][key] = arguments[i][key];
}
}
}
return arguments[0];
};
/**
* Test if a string is hexadecimal
*
* @param {string} str - A string to test
*
* @return {boolean} - True if correct, false otherwise
*/
var isHexadecimal = function isHexadecimal(str) {
return str.match('^(0x|0X)?[a-fA-F0-9]+$') !== null;
};
/**
* Search for mosaic definition(s) into an array of mosaicDefinition objects
*
* @param {array} mosaicDefinitionArray - An array of mosaicDefinition objects
* @param {array} keys - Array of strings with names of the mosaics to find (['eur', 'usd',...])
*
* @return {object} - An object of mosaicDefinition objects
*/
var searchMosaicDefinitionArray = function searchMosaicDefinitionArray(mosaicDefinitionArray, keys) {
var result = {};
for (var i = 0; i < keys.length; i++) {
for (var k = 0; k < mosaicDefinitionArray.length; k++) {
if (mosaicDefinitionArray[k].mosaic.id.name === keys[i]) {
result[_format2.default.mosaicIdToName(mosaicDefinitionArray[k].mosaic.id)] = mosaicDefinitionArray[k].mosaic;
}
}
}
return result;
};
/**
* Mimics jQuery's grep function
*/
var grep = function grep(items, callback) {
var filtered = [],
len = items.length,
i = 0;
for (i; i < len; i++) {
var item = items[i];
var cond = callback(item);
if (cond) {
filtered.push(item);
}
}
return filtered;
};
/**
* Check if a text input amount is valid
*
* @param {string} n - The number as a string
*
* @return {boolean} - True if valid, false otherwise
*/
var isTextAmountValid = function isTextAmountValid(n) {
// Force n as a string and replace decimal comma by a dot if any
var nn = Number(n.toString().replace(/,/g, '.'));
return !Number.isNaN(nn) && Number.isFinite(nn) && nn >= 0;
};
/**
* Clean a text input amount and return it as number
*
* @param {string} n - The number as a string
*
* @return {number} - The clean amount
*/
var cleanTextAmount = function cleanTextAmount(n) {
return Number(n.toString().replace(/,/g, '.'));
};
/**
* Convert an endpoint object to an endpoint url
*
* @param {object} endpoint - An endpoint object
*
* @return {String} - An endpoint url
*/
var formatEndpoint = function formatEndpoint(endpoint) {
return endpoint.host + ':' + endpoint.port;
};
/**
* Check if data is JSON
*
* @param {anything} data - Data to test
*
* @return {boolean} - True if JSON, false otherwise
*/
var isJSON = function isJSON(data) {
try {
JSON.parse(data);
return true;
} catch (e) {
return false;
}
};
module.exports = {
needsSignature: needsSignature,
haveTx: haveTx,
getTransactionIndex: getTransactionIndex,
haveCosig: haveCosig,
createNEMTimeStamp: createNEMTimeStamp,
fixPrivateKey: fixPrivateKey,
isPrivateKeyValid: isPrivateKeyValid,
isPublicKeyValid: isPublicKeyValid,
createTimeStamp: createTimeStamp,
getTimestampShort: getTimestampShort,
convertDateToString: convertDateToString,
extendObj: extendObj,
isHexadecimal: isHexadecimal,
searchMosaicDefinitionArray: searchMosaicDefinitionArray,
grep: grep,
isTextAmountValid: isTextAmountValid,
cleanTextAmount: cleanTextAmount,
formatEndpoint: formatEndpoint,
isJSON: isJSON
};
},{"./convert":49,"./format":50}],52:[function(require,module,exports){
"use strict";
/**
* Create notary data
*
* @param {string} filename - A file name
* @param {string} tags - File tags
* @param {string} fileHash - File hash
* @param {string} txHash - Transaction hash
* @param {string} txMultisigHash - Multisignature transaction hash
* @param {string} owner - Account address
* @param {string} fromMultisig - Multisig account address
* @param {string} dedicatedAccount - HD account of the file
* @param {string} dedicatedPrivateKey - Private key of the HD account
*
* @return {array} - The notary data
*/
var createNotaryData = function createNotaryData(filename, tags, fileHash, txHash, txMultisigHash, owner, fromMultisig, dedicatedAccount, dedicatedPrivateKey) {
var d = new Date();
return {
"data": [{
"filename": filename,
"tags": tags,
"fileHash": fileHash,
"owner": owner,
"fromMultisig": fromMultisig,
"dedicatedAccount": dedicatedAccount,
"dedicatedPrivateKey": dedicatedPrivateKey,
"txHash": txHash,
"txMultisigHash": txMultisigHash,
"timeStamp": d.toUTCString()
}]
};
};
/**
* Update notary data
*
* @param {array} ntyData - The notary data array
* @param {object} newNtyData - A notary data object
*
* @return {array} - The updated notary data array
*/
var updateNotaryData = function updateNotaryData(ntyData, newNtyData) {
ntyData.data.push(newNtyData.data[0]);
return ntyData;
};
module.exports = {
createNotaryData: createNotaryData,
updateNotaryData: updateNotaryData
};
},{}],53:[function(require,module,exports){
'use strict';
var _convert = require('./convert');
var _convert2 = _interopRequireDefault(_convert);
var _format = require('./format');
var _format2 = _interopRequireDefault(_format);
var _transactionTypes = require('../model/transactionTypes');
var _transactionTypes2 = _interopRequireDefault(_transactionTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/***
* NOTE, related to serialization: Unfortunately we need to create few objects
* and do a bit of copying, as Uint32Array does not allow random offsets
*/
/* safe string - each char is 8 bit */
var _serializeSafeString = function _serializeSafeString(str) {
var r = new ArrayBuffer(132);
var d = new Uint32Array(r);
var b = new Uint8Array(r);
var e = 4;
if (str === null) {
d[0] = 0xffffffff;
} else {
d[0] = str.length;
for (var j = 0; j < str.length; ++j) {
b[e++] = str.charCodeAt(j);
}
}
return new Uint8Array(r, 0, e);
};
var _serializeUaString = function _serializeUaString(str) {
var r = new ArrayBuffer(516);
var d = new Uint32Array(r);
var b = new Uint8Array(r);
var e = 4;
if (str === null) {
d[0] = 0xffffffff;
} else {
d[0] = str.length;
for (var j = 0; j < str.length; ++j) {
b[e++] = str[j];
}
}
return new Uint8Array(r, 0, e);
};
var _serializeLong = function _serializeLong(value) {
var r = new ArrayBuffer(8);
var d = new Uint32Array(r);
d[0] = value;
d[1] = Math.floor(value / 0x100000000);
return new Uint8Array(r, 0, 8);
};
var _serializeMosaicId = function _serializeMosaicId(mosaicId) {
var r = new ArrayBuffer(264);
var serializedNamespaceId = _serializeSafeString(mosaicId.namespaceId);
var serializedName = _serializeSafeString(mosaicId.name);
var b = new Uint8Array(r);
var d = new Uint32Array(r);
d[0] = serializedNamespaceId.length + serializedName.length;
var e = 4;
for (var j = 0; j < serializedNamespaceId.length; ++j) {
b[e++] = serializedNamespaceId[j];
}
for (var j = 0; j < serializedName.length; ++j) {
b[e++] = serializedName[j];
}
return new Uint8Array(r, 0, e);
};
var _serializeMosaicAndQuantity = function _serializeMosaicAndQuantity(mosaic) {
var r = new ArrayBuffer(4 + 264 + 8);
var serializedMosaicId = _serializeMosaicId(mosaic.mosaicId);
var serializedQuantity = _serializeLong(mosaic.quantity);
//$log.info(convert.ua2hex(serializedQuantity), serializedMosaicId, serializedQuantity);
var b = new Uint8Array(r);
var d = new Uint32Array(r);
d[0] = serializedMosaicId.length + serializedQuantity.length;
var e = 4;
for (var j = 0; j < serializedMosaicId.length; ++j) {
b[e++] = serializedMosaicId[j];
}
for (var j = 0; j < serializedQuantity.length; ++j) {
b[e++] = serializedQuantity[j];
}
return new Uint8Array(r, 0, e);
};
var _serializeMosaics = function _serializeMosaics(entity) {
var r = new ArrayBuffer(276 * 10 + 4);
var d = new Uint32Array(r);
var b = new Uint8Array(r);
var i = 0;
var e = 0;
d[i++] = entity.length;
e += 4;
var temporary = [];
for (var j = 0; j < entity.length; ++j) {
temporary.push({
'entity': entity[j],
'value': _format2.default.mosaicIdToName(entity[j].mosaicId) + " : " + entity[j].quantity
});
}
temporary.sort(function (a, b) {
return a.value < b.value ? -1 : a.value > b.value;
});
for (var j = 0; j < temporary.length; ++j) {
var entity = temporary[j].entity;
var serializedMosaic = _serializeMosaicAndQuantity(entity);
for (var k = 0; k < serializedMosaic.length; ++k) {
b[e++] = serializedMosaic[k];
}
}
return new Uint8Array(r, 0, e);
};
var _serializeProperty = function _serializeProperty(entity) {
var r = new ArrayBuffer(1024);
var d = new Uint32Array(r);
var b = new Uint8Array(r);
var serializedName = _serializeSafeString(entity['name']);
var serializedValue = _serializeSafeString(entity['value']);
d[0] = serializedName.length + serializedValue.length;
var e = 4;
for (var j = 0; j < serializedName.length; ++j) {
b[e++] = serializedName[j];
}
for (var j = 0; j < serializedValue.length; ++j) {
b[e++] = serializedValue[j];
}
return new Uint8Array(r, 0, e);
};
var _serializeProperties = function _serializeProperties(entity) {
var r = new ArrayBuffer(1024);
var d = new Uint32Array(r);
var b = new Uint8Array(r);
var i = 0;
var e = 0;
d[i++] = entity.length;
e += 4;
var temporary = entity;
var temporary = [];
for (var j = 0; j < entity.length; ++j) {
temporary.push(entity[j]);
}
var helper = {
'divisibility': 1,
'initialSupply': 2,
'supplyMutable': 3,
'transferable': 4
};
temporary.sort(function (a, b) {
return helper[a.name] < helper[b.name] ? -1 : helper[a.name] > helper[b.name];
});
for (var j = 0; j < temporary.length; ++j) {
var entity = temporary[j];
var serializedProperty = _serializeProperty(entity);
for (var k = 0; k < serializedProperty.length; ++k) {
b[e++] = serializedProperty[k];
}
}
return new Uint8Array(r, 0, e);
};
var _serializeLevy = function _serializeLevy(entity) {
var r = new ArrayBuffer(1024);
var d = new Uint32Array(r);
if (entity === null) {
d[0] = 0;
return new Uint8Array(r, 0, 4);
}
var b = new Uint8Array(r);
d[1] = entity['type'];
var e = 8;
var temp = _serializeSafeString(entity['recipient']);
for (var j = 0; j < temp.length; ++j) {
b[e++] = temp[j];
}
var serializedMosaicId = _serializeMosaicId(entity['mosaicId']);
for (var j = 0; j < serializedMosaicId.length; ++j) {
b[e++] = serializedMosaicId[j];
}
var serializedFee = _serializeLong(entity['fee']);
for (var j = 0; j < serializedFee.length; ++j) {
b[e++] = serializedFee[j];
}
d[0] = 4 + temp.length + serializedMosaicId.length + 8;
return new Uint8Array(r, 0, e);
};
var _serializeMosaicDefinition = function _serializeMosaicDefinition(entity) {
var r = new ArrayBuffer(40 + 264 + 516 + 1024 + 1024);
var d = new Uint32Array(r);
var b = new Uint8Array(r);
var temp = _convert2.default.hex2ua(entity['creator']);
d[0] = temp.length;
var e = 4;
for (var j = 0; j < temp.length; ++j) {
b[e++] = temp[j];
}
var serializedMosaicId = _serializeMosaicId(entity.id);
for (var j = 0; j < serializedMosaicId.length; ++j) {
b[e++] = serializedMosaicId[j];
}
var utf8ToUa = _convert2.default.hex2ua(_convert2.default.utf8ToHex(entity['description']));
var temp = _serializeUaString(utf8ToUa);
for (var j = 0; j < temp.length; ++j) {
b[e++] = temp[j];
}
var temp = _serializeProperties(entity['properties']);
for (var j = 0; j < temp.length; ++j) {
b[e++] = temp[j];
}
var levy = _serializeLevy(entity['levy']);
for (var j = 0; j < levy.length; ++j) {
b[e++] = levy[j];
}
return new Uint8Array(r, 0, e);
};
/**
* Serialize a transaction object
*
* @param {object} entity - A transaction object
*
* @return {Uint8Array} - The serialized transaction
*/
var serializeTransaction = function serializeTransaction(entity) {
var r = new ArrayBuffer(512 + 2764);
var d = new Uint32Array(r);
var b = new Uint8Array(r);
d[0] = entity['type'];
d[1] = entity['version'];
d[2] = entity['timeStamp'];
var temp = _convert2.default.hex2ua(entity['signer']);
d[3] = temp.length;
var e = 16;
for (var j = 0; j < temp.length; ++j) {
b[e++] = temp[j];
}
// Transaction
var i = e / 4;
d[i++] = entity['fee'];
d[i++] = Math.floor(entity['fee'] / 0x100000000);
d[i++] = entity['deadline'];
e += 12;
// TransferTransaction
if (d[0] === _transactionTypes2.default.transfer) {
d[i++] = entity['recipient'].length;
e += 4;
// TODO: check that entity['recipient'].length is always 40 bytes
for (var j = 0; j < entity['recipient'].length; ++j) {
b[e++] = entity['recipient'].charCodeAt(j);
}
i = e / 4;
d[i++] = entity['amount'];
d[i++] = Math.floor(entity['amount'] / 0x100000000);
e += 8;
if (entity['message']['type'] === 1 || entity['message']['type'] === 2) {
var temp = _convert2.default.hex2ua(entity['message']['payload']);
if (temp.length === 0) {
d[i++] = 0;
e += 4;
} else {
// length of a message object
d[i++] = 8 + temp.length;
// object itself
d[i++] = entity['message']['type'];
d[i++] = temp.length;
e += 12;
for (var j = 0; j < temp.length; ++j) {
b[e++] = temp[j];
}
}
}
var entityVersion = d[1] & 0xffffff;
if (entityVersion >= 2) {
var temp = _serializeMosaics(entity['mosaics']);
for (var j = 0; j < temp.length; ++j) {
b[e++] = temp[j];
}
}
// Provision Namespace transaction
} else if (d[0] === _transactionTypes2.default.provisionNamespace) {
d[i++] = entity['rentalFeeSink'].length;
e += 4;
// TODO: check that entity['rentalFeeSink'].length is always 40 bytes
for (var j = 0; j < entity['rentalFeeSink'].length; ++j) {
b[e++] = entity['rentalFeeSink'].charCodeAt(j);
}
i = e / 4;
d[i++] = entity['rentalFee'];
d[i++] = Math.floor(entity['rentalFee'] / 0x100000000);
e += 8;
var temp = _serializeSafeString(entity['newPart']);
for (var j = 0; j < temp.length; ++j) {
b[e++] = temp[j];
}
var temp = _serializeSafeString(entity['parent']);
for (var j = 0; j < temp.length; ++j) {
b[e++] = temp[j];
}
// Mosaic Definition Creation transaction
} else if (d[0] === _transactionTypes2.default.mosaicDefinition) {
var temp = _serializeMosaicDefinition(entity['mosaicDefinition']);
d[i++] = temp.length;
e += 4;
for (var j = 0; j < temp.length; ++j) {
b[e++] = temp[j];
}
temp = _serializeSafeString(entity['creationFeeSink']);
for (var j = 0; j < temp.length; ++j) {
b[e++] = temp[j];
}
temp = _serializeLong(entity['creationFee']);
for (var j = 0; j < temp.length; ++j) {
b[e++] = temp[j];
}
// Mosaic Supply Change transaction
} else if (d[0] === _transactionTypes2.default.mosaicSupply) {
var serializedMosaicId = _serializeMosaicId(entity['mosaicId']);
for (var j = 0; j < serializedMosaicId.length; ++j) {
b[e++] = serializedMosaicId[j];
}
var temp = new ArrayBuffer(4);
d = new Uint32Array(temp);
d[0] = entity['supplyType'];
var serializeSupplyType = new Uint8Array(temp);
for (var j = 0; j < serializeSupplyType.length; ++j) {
b[e++] = serializeSupplyType[j];
}
var serializedDelta = _serializeLong(entity['delta']);
for (var j = 0; j < serializedDelta.length; ++j) {
b[e++] = serializedDelta[j];
}
// Signature transaction
} else if (d[0] === _transactionTypes2.default.multisigSignature) {
var temp = _convert2.default.hex2ua(entity['otherHash']['data']);
// length of a hash object....
d[i++] = 4 + temp.length;
// object itself
d[i++] = temp.length;
e += 8;
for (var j = 0; j < temp.length; ++j) {
b[e++] = temp[j];
}
i = e / 4;
temp = entity['otherAccount'];
d[i++] = temp.length;
e += 4;
for (var j = 0; j < temp.length; ++j) {
b[e++] = temp.charCodeAt(j);
}
// Multisig wrapped transaction
} else if (d[0] === _transactionTypes2.default.multisigTransaction) {
var temp = serializeTransaction(entity['otherTrans']);
d[i++] = temp.length;
e += 4;
for (var j = 0; j < temp.length; ++j) {
b[e++] = temp[j];
}
// Aggregate Modification transaction
} else if (d[0] === _transactionTypes2.default.multisigModification) {
// Number of modifications
var temp = entity['modifications'];
d[i++] = temp.length;
e += 4;
for (var j = 0; j < temp.length; ++j) {
// Length of modification structure
d[i++] = 0x28;
e += 4;
// Modification type
if (temp[j]['modificationType'] == 1) {
d[i++] = 0x01;
} else {
d[i++] = 0x02;
}
e += 4;
// Length of public key
d[i++] = 0x20;
e += 4;
var key2bytes = _convert2.default.hex2ua(entity['modifications'][j]['cosignatoryAccount']);
// Key to Bytes
for (var k = 0; k < key2bytes.length; ++k) {
b[e++] = key2bytes[k];
}
i = e / 4;
}
var entityVersion = d[1] & 0xffffff;
if (entityVersion >= 2) {
d[i++] = 0x04;
e += 4;
// Relative change
d[i++] = entity['minCosignatories']['relativeChange'].toString(16);
e += 4;
} else {
// Version 1 has no modifications
}
} else if (d[0] === _transactionTypes2.default.importanceTransfer) {
d[i++] = entity['mode'];
e += 4;
d[i++] = 0x20;
e += 4;
var key2bytes = _convert2.default.hex2ua(entity['remoteAccount']);
//Key to Bytes
for (var k = 0; k < key2bytes.length; ++k) {
b[e++] = key2bytes[k];
}
}
return new Uint8Array(r, 0, e);
};
module.exports = {
_serializeSafeString: _serializeSafeString,
_serializeUaString: _serializeUaString,
_serializeLong: _serializeLong,
_serializeMosaicId: _serializeMosaicId,
_serializeMosaicAndQuantity: _serializeMosaicAndQuantity,
_serializeMosaics: _serializeMosaics,
_serializeProperty: _serializeProperty,
_serializeProperties: _serializeProperties,
_serializeLevy: _serializeLevy,
_serializeMosaicDefinition: _serializeMosaicDefinition,
serializeTransaction: serializeTransaction
};
},{"../model/transactionTypes":36,"./convert":49,"./format":50}],54:[function(require,module,exports){
'use strict';
var compileSchema = require('./compile')
, resolve = require('./compile/resolve')
, Cache = require('./cache')
, SchemaObject = require('./compile/schema_obj')
, stableStringify = require('json-stable-stringify')
, formats = require('./compile/formats')
, rules = require('./compile/rules')
, v5 = require('./v5')
, util = require('./compile/util')
, async = require('./async')
, co = require('co');
module.exports = Ajv;
Ajv.prototype.compileAsync = async.compile;
var customKeyword = require('./keyword');
Ajv.prototype.addKeyword = customKeyword.add;
Ajv.prototype.getKeyword = customKeyword.get;
Ajv.prototype.removeKeyword = customKeyword.remove;
Ajv.ValidationError = require('./compile/validation_error');
var META_SCHEMA_ID = 'http://json-schema.org/draft-04/schema';
var SCHEMA_URI_FORMAT = /^(?:(?:[a-z][a-z0-9+-.]*:)?\/\/)?[^\s]*$/i;
function SCHEMA_URI_FORMAT_FUNC(str) {
return SCHEMA_URI_FORMAT.test(str);
}
var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes' ];
/**
* Creates validator instance.
* Usage: `Ajv(opts)`
* @param {Object} opts optional options
* @return {Object} ajv instance
*/
function Ajv(opts) {
if (!(this instanceof Ajv)) return new Ajv(opts);
var self = this;
opts = this._opts = util.copy(opts) || {};
this._schemas = {};
this._refs = {};
this._fragments = {};
this._formats = formats(opts.format);
this._cache = opts.cache || new Cache;
this._loadingSchemas = {};
this._compilations = [];
this.RULES = rules();
// this is done on purpose, so that methods are bound to the instance
// (without using bind) so that they can be used without the instance
this.validate = validate;
this.compile = compile;
this.addSchema = addSchema;
this.addMetaSchema = addMetaSchema;
this.validateSchema = validateSchema;
this.getSchema = getSchema;
this.removeSchema = removeSchema;
this.addFormat = addFormat;
this.errorsText = errorsText;
this._addSchema = _addSchema;
this._compile = _compile;
opts.loopRequired = opts.loopRequired || Infinity;
if (opts.async || opts.transpile) async.setup(opts);
if (opts.beautify === true) opts.beautify = { indent_size: 2 };
if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
this._metaOpts = getMetaSchemaOptions();
if (opts.formats) addInitialFormats();
addDraft4MetaSchema();
if (opts.v5) v5.enable(this);
if (typeof opts.meta == 'object') addMetaSchema(opts.meta);
addInitialSchemas();
/**
* Validate data using schema
* Schema will be compiled and cached (using serialized JSON as key. [json-stable-stringify](https://github.com/substack/json-stable-stringify) is used to serialize.
* @param {String|Object} schemaKeyRef key, ref or schema object
* @param {Any} data to be validated
* @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
*/
function validate(schemaKeyRef, data) {
var v;
if (typeof schemaKeyRef == 'string') {
v = getSchema(schemaKeyRef);
if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
} else {
var schemaObj = _addSchema(schemaKeyRef);
v = schemaObj.validate || _compile(schemaObj);
}
var valid = v(data);
if (v.$async === true)
return self._opts.async == '*' ? co(valid) : valid;
self.errors = v.errors;
return valid;
}
/**
* Create validating function for passed schema.
* @param {Object} schema schema object
* @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
* @return {Function} validating function
*/
function compile(schema, _meta) {
var schemaObj = _addSchema(schema, undefined, _meta);
return schemaObj.validate || _compile(schemaObj);
}
/**
* Adds schema to the instance.
* @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
* @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
* @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
* @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
*/
function addSchema(schema, key, _skipValidation, _meta) {
if (Array.isArray(schema)){
for (var i=0; i<schema.length; i++) addSchema(schema[i], undefined, _skipValidation, _meta);
return;
}
// can key/id have # inside?
key = resolve.normalizeId(key || schema.id);
checkUnique(key);
self._schemas[key] = _addSchema(schema, _skipValidation, _meta, true);
}
/**
* Add schema that will be used to validate other schemas
* options in META_IGNORE_OPTIONS are alway set to false
* @param {Object} schema schema object
* @param {String} key optional schema key
* @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
*/
function addMetaSchema(schema, key, skipValidation) {
addSchema(schema, key, skipValidation, true);
}
/**
* Validate schema
* @param {Object} schema schema to validate
* @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
* @return {Boolean} true if schema is valid
*/
function validateSchema(schema, throwOrLogError) {
var $schema = schema.$schema || self._opts.defaultMeta || defaultMeta();
var currentUriFormat = self._formats.uri;
self._formats.uri = typeof currentUriFormat == 'function'
? SCHEMA_URI_FORMAT_FUNC
: SCHEMA_URI_FORMAT;
var valid;
try { valid = validate($schema, schema); }
finally { self._formats.uri = currentUriFormat; }
if (!valid && throwOrLogError) {
var message = 'schema is invalid: ' + errorsText();
if (self._opts.validateSchema == 'log') console.error(message);
else throw new Error(message);
}
return valid;
}
function defaultMeta() {
var meta = self._opts.meta;
self._opts.defaultMeta = typeof meta == 'object'
? meta.id || meta
: self._opts.v5
? v5.META_SCHEMA_ID
: META_SCHEMA_ID;
return self._opts.defaultMeta;
}
/**
* Get compiled schema from the instance by `key` or `ref`.
* @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
* @return {Function} schema validating function (with property `schema`).
*/
function getSchema(keyRef) {
var schemaObj = _getSchemaObj(keyRef);
switch (typeof schemaObj) {
case 'object': return schemaObj.validate || _compile(schemaObj);
case 'string': return getSchema(schemaObj);
case 'undefined': return _getSchemaFragment(keyRef);
}
}
function _getSchemaFragment(ref) {
var res = resolve.schema.call(self, { schema: {} }, ref);
if (res) {
var schema = res.schema
, root = res.root
, baseId = res.baseId;
var v = compileSchema.call(self, schema, root, undefined, baseId);
self._fragments[ref] = new SchemaObject({
ref: ref,
fragment: true,
schema: schema,
root: root,
baseId: baseId,
validate: v
});
return v;
}
}
function _getSchemaObj(keyRef) {
keyRef = resolve.normalizeId(keyRef);
return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
}
/**
* Remove cached schema(s).
* If no parameter is passed all schemas but meta-schemas are removed.
* If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
* Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
* @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
*/
function removeSchema(schemaKeyRef) {
if (schemaKeyRef instanceof RegExp) {
_removeAllSchemas(self._schemas, schemaKeyRef);
_removeAllSchemas(self._refs, schemaKeyRef);
return;
}
switch (typeof schemaKeyRef) {
case 'undefined':
_removeAllSchemas(self._schemas);
_removeAllSchemas(self._refs);
self._cache.clear();
return;
case 'string':
var schemaObj = _getSchemaObj(schemaKeyRef);
if (schemaObj) self._cache.del(schemaObj.jsonStr);
delete self._schemas[schemaKeyRef];
delete self._refs[schemaKeyRef];
return;
case 'object':
var jsonStr = stableStringify(schemaKeyRef);
self._cache.del(jsonStr);
var id = schemaKeyRef.id;
if (id) {
id = resolve.normalizeId(id);
delete self._schemas[id];
delete self._refs[id];
}
}
}
function _removeAllSchemas(schemas, regex) {
for (var keyRef in schemas) {
var schemaObj = schemas[keyRef];
if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
self._cache.del(schemaObj.jsonStr);
delete schemas[keyRef];
}
}
}
function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
if (typeof schema != 'object') throw new Error('schema should be object');
var jsonStr = stableStringify(schema);
var cached = self._cache.get(jsonStr);
if (cached) return cached;
shouldAddSchema = shouldAddSchema || self._opts.addUsedSchema !== false;
var id = resolve.normalizeId(schema.id);
if (id && shouldAddSchema) checkUnique(id);
var willValidate = self._opts.validateSchema !== false && !skipValidation;
var recursiveMeta;
if (willValidate && !(recursiveMeta = schema.id && schema.id == schema.$schema))
validateSchema(schema, true);
var localRefs = resolve.ids.call(self, schema);
var schemaObj = new SchemaObject({
id: id,
schema: schema,
localRefs: localRefs,
jsonStr: jsonStr,
meta: meta
});
if (id[0] != '#' && shouldAddSchema) self._refs[id] = schemaObj;
self._cache.put(jsonStr, schemaObj);
if (willValidate && recursiveMeta) validateSchema(schema, true);
return schemaObj;
}
function _compile(schemaObj, root) {
if (schemaObj.compiling) {
schemaObj.validate = callValidate;
callValidate.schema = schemaObj.schema;
callValidate.errors = null;
callValidate.root = root ? root : callValidate;
if (schemaObj.schema.$async === true)
callValidate.$async = true;
return callValidate;
}
schemaObj.compiling = true;
var currentOpts;
if (schemaObj.meta) {
currentOpts = self._opts;
self._opts = self._metaOpts;
}
var v;
try { v = compileSchema.call(self, schemaObj.schema, root, schemaObj.localRefs); }
finally {
schemaObj.compiling = false;
if (schemaObj.meta) self._opts = currentOpts;
}
schemaObj.validate = v;
schemaObj.refs = v.refs;
schemaObj.refVal = v.refVal;
schemaObj.root = v.root;
return v;
function callValidate() {
var _validate = schemaObj.validate;
var result = _validate.apply(null, arguments);
callValidate.errors = _validate.errors;
return result;
}
}
/**
* Convert array of error message objects to string
* @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
* @param {Object} options optional options with properties `separator` and `dataVar`.
* @return {String} human readable string with all errors descriptions
*/
function errorsText(errors, options) {
errors = errors || self.errors;
if (!errors) return 'No errors';
options = options || {};
var separator = options.separator === undefined ? ', ' : options.separator;
var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
var text = '';
for (var i=0; i<errors.length; i++) {
var e = errors[i];
if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
}
return text.slice(0, -separator.length);
}
/**
* Add custom format
* @param {String} name format name
* @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
*/
function addFormat(name, format) {
if (typeof format == 'string') format = new RegExp(format);
self._formats[name] = format;
}
function addDraft4MetaSchema() {
if (self._opts.meta !== false) {
var metaSchema = require('./refs/json-schema-draft-04.json');
addMetaSchema(metaSchema, META_SCHEMA_ID, true);
self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
}
}
function addInitialSchemas() {
var optsSchemas = self._opts.schemas;
if (!optsSchemas) return;
if (Array.isArray(optsSchemas)) addSchema(optsSchemas);
else for (var key in optsSchemas) addSchema(optsSchemas[key], key);
}
function addInitialFormats() {
for (var name in self._opts.formats) {
var format = self._opts.formats[name];
addFormat(name, format);
}
}
function checkUnique(id) {
if (self._schemas[id] || self._refs[id])
throw new Error('schema with key or id "' + id + '" already exists');
}
function getMetaSchemaOptions() {
var metaOpts = util.copy(self._opts);
for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
delete metaOpts[META_IGNORE_OPTIONS[i]];
return metaOpts;
}
}
},{"./async":55,"./cache":56,"./compile":60,"./compile/formats":59,"./compile/resolve":61,"./compile/rules":62,"./compile/schema_obj":63,"./compile/util":65,"./compile/validation_error":66,"./keyword":91,"./refs/json-schema-draft-04.json":92,"./v5":94,"co":161,"json-stable-stringify":294}],55:[function(require,module,exports){
'use strict';
module.exports = {
setup: setupAsync,
compile: compileAsync
};
var util = require('./compile/util');
var ASYNC = {
'*': checkGenerators,
'co*': checkGenerators,
'es7': checkAsyncFunction
};
var TRANSPILE = {
'nodent': getNodent,
'regenerator': getRegenerator
};
var MODES = [
{ async: 'co*' },
{ async: 'es7', transpile: 'nodent' },
{ async: 'co*', transpile: 'regenerator' }
];
var regenerator, nodent;
function setupAsync(opts, required) {
if (required !== false) required = true;
var async = opts.async
, transpile = opts.transpile
, check;
switch (typeof transpile) {
case 'string':
var get = TRANSPILE[transpile];
if (!get) throw new Error('bad transpiler: ' + transpile);
return (opts._transpileFunc = get(opts, required));
case 'undefined':
case 'boolean':
if (typeof async == 'string') {
check = ASYNC[async];
if (!check) throw new Error('bad async mode: ' + async);
return (opts.transpile = check(opts, required));
}
for (var i=0; i<MODES.length; i++) {
var _opts = MODES[i];
if (setupAsync(_opts, false)) {
util.copy(_opts, opts);
return opts.transpile;
}
}
/* istanbul ignore next */
throw new Error('generators, nodent and regenerator are not available');
case 'function':
return (opts._transpileFunc = opts.transpile);
default:
throw new Error('bad transpiler: ' + transpile);
}
}
function checkGenerators(opts, required) {
/* jshint evil: true */
try {
(new Function('(function*(){})()'))();
return true;
} catch(e) {
/* istanbul ignore next */
if (required) throw new Error('generators not supported');
}
}
function checkAsyncFunction(opts, required) {
/* jshint evil: true */
try {
(new Function('(async function(){})()'))();
/* istanbul ignore next */
return true;
} catch(e) {
if (required) throw new Error('es7 async functions not supported');
}
}
function getRegenerator(opts, required) {
try {
if (!regenerator) {
var name = 'regenerator';
regenerator = require(name);
regenerator.runtime();
}
if (!opts.async || opts.async === true)
opts.async = 'es7';
return regeneratorTranspile;
} catch(e) {
/* istanbul ignore next */
if (required) throw new Error('regenerator not available');
}
}
function regeneratorTranspile(code) {
return regenerator.compile(code).code;
}
function getNodent(opts, required) {
/* jshint evil: true */
try {
if (!nodent) {
var name = 'nodent';
nodent = require(name)({ log: false, dontInstallRequireHook: true });
}
if (opts.async != 'es7') {
if (opts.async && opts.async !== true) console.warn('nodent transpiles only es7 async functions');
opts.async = 'es7';
}
return nodentTranspile;
} catch(e) {
/* istanbul ignore next */
if (required) throw new Error('nodent not available');
}
}
function nodentTranspile(code) {
return nodent.compile(code, '', { promises: true, sourcemap: false }).code;
}
/**
* Creates validating function for passed schema with asynchronous loading of missing schemas.
* `loadSchema` option should be a function that accepts schema uri and node-style callback.
* @this Ajv
* @param {Object} schema schema object
* @param {Function} callback node-style callback, it is always called with 2 parameters: error (or null) and validating function.
*/
function compileAsync(schema, callback) {
/* eslint no-shadow: 0 */
/* jshint validthis: true */
var schemaObj;
var self = this;
try {
schemaObj = this._addSchema(schema);
} catch(e) {
setTimeout(function() { callback(e); });
return;
}
if (schemaObj.validate) {
setTimeout(function() { callback(null, schemaObj.validate); });
} else {
if (typeof this._opts.loadSchema != 'function')
throw new Error('options.loadSchema should be a function');
_compileAsync(schema, callback, true);
}
function _compileAsync(schema, callback, firstCall) {
var validate;
try { validate = self.compile(schema); }
catch(e) {
if (e.missingSchema) loadMissingSchema(e);
else deferCallback(e);
return;
}
deferCallback(null, validate);
function loadMissingSchema(e) {
var ref = e.missingSchema;
if (self._refs[ref] || self._schemas[ref])
return callback(new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'));
var _callbacks = self._loadingSchemas[ref];
if (_callbacks) {
if (typeof _callbacks == 'function')
self._loadingSchemas[ref] = [_callbacks, schemaLoaded];
else
_callbacks[_callbacks.length] = schemaLoaded;
} else {
self._loadingSchemas[ref] = schemaLoaded;
self._opts.loadSchema(ref, function (err, sch) {
var _callbacks = self._loadingSchemas[ref];
delete self._loadingSchemas[ref];
if (typeof _callbacks == 'function') {
_callbacks(err, sch);
} else {
for (var i=0; i<_callbacks.length; i++)
_callbacks[i](err, sch);
}
});
}
function schemaLoaded(err, sch) {
if (err) return callback(err);
if (!(self._refs[ref] || self._schemas[ref])) {
try {
self.addSchema(sch, ref);
} catch(e) {
callback(e);
return;
}
}
_compileAsync(schema, callback);
}
}
function deferCallback(err, validate) {
if (firstCall) setTimeout(function() { callback(err, validate); });
else return callback(err, validate);
}
}
}
},{"./compile/util":65}],56:[function(require,module,exports){
'use strict';
var Cache = module.exports = function Cache() {
this._cache = {};
};
Cache.prototype.put = function Cache_put(key, value) {
this._cache[key] = value;
};
Cache.prototype.get = function Cache_get(key) {
return this._cache[key];
};
Cache.prototype.del = function Cache_del(key) {
delete this._cache[key];
};
Cache.prototype.clear = function Cache_clear() {
this._cache = {};
};
},{}],57:[function(require,module,exports){
'use strict';
//all requires must be explicit because browserify won't work with dynamic requires
module.exports = {
'$ref': require('../dotjs/ref'),
allOf: require('../dotjs/allOf'),
anyOf: require('../dotjs/anyOf'),
dependencies: require('../dotjs/dependencies'),
'enum': require('../dotjs/enum'),
format: require('../dotjs/format'),
items: require('../dotjs/items'),
maximum: require('../dotjs/_limit'),
minimum: require('../dotjs/_limit'),
maxItems: require('../dotjs/_limitItems'),
minItems: require('../dotjs/_limitItems'),
maxLength: require('../dotjs/_limitLength'),
minLength: require('../dotjs/_limitLength'),
maxProperties: require('../dotjs/_limitProperties'),
minProperties: require('../dotjs/_limitProperties'),
multipleOf: require('../dotjs/multipleOf'),
not: require('../dotjs/not'),
oneOf: require('../dotjs/oneOf'),
pattern: require('../dotjs/pattern'),
properties: require('../dotjs/properties'),
required: require('../dotjs/required'),
uniqueItems: require('../dotjs/uniqueItems'),
validate: require('../dotjs/validate')
};
},{"../dotjs/_limit":68,"../dotjs/_limitItems":69,"../dotjs/_limitLength":70,"../dotjs/_limitProperties":71,"../dotjs/allOf":72,"../dotjs/anyOf":73,"../dotjs/dependencies":76,"../dotjs/enum":77,"../dotjs/format":78,"../dotjs/items":79,"../dotjs/multipleOf":80,"../dotjs/not":81,"../dotjs/oneOf":82,"../dotjs/pattern":83,"../dotjs/properties":85,"../dotjs/ref":86,"../dotjs/required":87,"../dotjs/uniqueItems":89,"../dotjs/validate":90}],58:[function(require,module,exports){
'use strict';
/*eslint complexity: 0*/
module.exports = function equal(a, b) {
if (a === b) return true;
var arrA = Array.isArray(a)
, arrB = Array.isArray(b)
, i;
if (arrA && arrB) {
if (a.length != b.length) return false;
for (i = 0; i < a.length; i++)
if (!equal(a[i], b[i])) return false;
return true;
}
if (arrA != arrB) return false;
if (a && b && typeof a === 'object' && typeof b === 'object') {
var keys = Object.keys(a);
if (keys.length !== Object.keys(b).length) return false;
var dateA = a instanceof Date
, dateB = b instanceof Date;
if (dateA && dateB) return a.getTime() == b.getTime();
if (dateA != dateB) return false;
var regexpA = a instanceof RegExp
, regexpB = b instanceof RegExp;
if (regexpA && regexpB) return a.toString() == b.toString();
if (regexpA != regexpB) return false;
for (i = 0; i < keys.length; i++)
if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for (i = 0; i < keys.length; i++)
if(!equal(a[keys[i]], b[keys[i]])) return false;
return true;
}
return false;
};
},{}],59:[function(require,module,exports){
'use strict';
var util = require('./util');
var DATE = /^\d\d\d\d-(\d\d)-(\d\d)$/;
var DAYS = [0,31,29,31,30,31,30,31,31,30,31,30,31];
var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i;
var HOSTNAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i;
var URI = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?$/i;
var UUID = /^(?:urn\:uuid\:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
var JSON_POINTER = /^(?:\/(?:[^~\/]|~0|~1)*)*$|^\#(?:\/(?:[a-z0-9_\-\.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:\#|(?:\/(?:[^~\/]|~0|~1)*)*)$/;
module.exports = formats;
function formats(mode) {
mode = mode == 'full' ? 'full' : 'fast';
var formatDefs = util.copy(formats[mode]);
for (var fName in formats.compare) {
formatDefs[fName] = {
validate: formatDefs[fName],
compare: formats.compare[fName]
};
}
return formatDefs;
}
formats.fast = {
// date: http://tools.ietf.org/html/rfc3339#section-5.6
date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
// date-time: http://tools.ietf.org/html/rfc3339#section-5.6
time: /^[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i,
'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s][0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i,
// uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
uri: /^(?:[a-z][a-z0-9+-.]*)?(?:\:|\/)\/?[^\s]*$/i,
// email (sources from jsen validator):
// http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
// http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
email: /^[a-z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
hostname: HOSTNAME,
// optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
// optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
regex: regex,
// uuid: http://tools.ietf.org/html/rfc4122
uuid: UUID,
// JSON-pointer: https://tools.ietf.org/html/rfc6901
// uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
'json-pointer': JSON_POINTER,
// relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
'relative-json-pointer': RELATIVE_JSON_POINTER
};
formats.full = {
date: date,
time: time,
'date-time': date_time,
uri: uri,
email: /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&''*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
hostname: hostname,
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
regex: regex,
uuid: UUID,
'json-pointer': JSON_POINTER,
'relative-json-pointer': RELATIVE_JSON_POINTER
};
formats.compare = {
date: compareDate,
time: compareTime,
'date-time': compareDateTime
};
function date(str) {
// full-date from http://tools.ietf.org/html/rfc3339#section-5.6
var matches = str.match(DATE);
if (!matches) return false;
var month = +matches[1];
var day = +matches[2];
return month >= 1 && month <= 12 && day >= 1 && day <= DAYS[month];
}
function time(str, full) {
var matches = str.match(TIME);
if (!matches) return false;
var hour = matches[1];
var minute = matches[2];
var second = matches[3];
var timeZone = matches[5];
return hour <= 23 && minute <= 59 && second <= 59 && (!full || timeZone);
}
var DATE_TIME_SEPARATOR = /t|\s/i;
function date_time(str) {
// http://tools.ietf.org/html/rfc3339#section-5.6
var dateTime = str.split(DATE_TIME_SEPARATOR);
return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
}
function hostname(str) {
// https://tools.ietf.org/html/rfc1034#section-3.5
// https://tools.ietf.org/html/rfc1123#section-2
return str.length <= 255 && HOSTNAME.test(str);
}
var NOT_URI_FRAGMENT = /\/|\:/;
function uri(str) {
// http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
return NOT_URI_FRAGMENT.test(str) && URI.test(str);
}
function regex(str) {
try {
new RegExp(str);
return true;
} catch(e) {
return false;
}
}
function compareDate(d1, d2) {
if (!(d1 && d2)) return;
if (d1 > d2) return 1;
if (d1 < d2) return -1;
if (d1 === d2) return 0;
}
function compareTime(t1, t2) {
if (!(t1 && t2)) return;
t1 = t1.match(TIME);
t2 = t2.match(TIME);
if (!(t1 && t2)) return;
t1 = t1[1] + t1[2] + t1[3] + (t1[4]||'');
t2 = t2[1] + t2[2] + t2[3] + (t2[4]||'');
if (t1 > t2) return 1;
if (t1 < t2) return -1;
if (t1 === t2) return 0;
}
function compareDateTime(dt1, dt2) {
if (!(dt1 && dt2)) return;
dt1 = dt1.split(DATE_TIME_SEPARATOR);
dt2 = dt2.split(DATE_TIME_SEPARATOR);
var res = compareDate(dt1[0], dt2[0]);
if (res === undefined) return;
return res || compareTime(dt1[1], dt2[1]);
}
},{"./util":65}],60:[function(require,module,exports){
'use strict';
var resolve = require('./resolve')
, util = require('./util')
, stableStringify = require('json-stable-stringify')
, async = require('../async');
var beautify;
function loadBeautify(){
if (beautify === undefined) {
var name = 'js-beautify';
try { beautify = require(name).js_beautify; }
catch(e) { beautify = false; }
}
}
var validateGenerator = require('../dotjs/validate');
/**
* Functions below are used inside compiled validations function
*/
var co = require('co');
var ucs2length = util.ucs2length;
var equal = require('./equal');
// this error is thrown by async schemas to return validation errors via exception
var ValidationError = require('./validation_error');
module.exports = compile;
/**
* Compiles schema to validation function
* @this Ajv
* @param {Object} schema schema object
* @param {Object} root object with information about the root schema for this schema
* @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
* @param {String} baseId base ID for IDs in the schema
* @return {Function} validation function
*/
function compile(schema, root, localRefs, baseId) {
/* jshint validthis: true, evil: true */
/* eslint no-shadow: 0 */
var self = this
, opts = this._opts
, refVal = [ undefined ]
, refs = {}
, patterns = []
, patternsHash = {}
, defaults = []
, defaultsHash = {}
, customRules = []
, keepSourceCode = opts.sourceCode !== false;
root = root || { schema: schema, refVal: refVal, refs: refs };
var c = checkCompiling.call(this, schema, root, baseId);
var compilation = this._compilations[c.index];
if (c.compiling) return (compilation.callValidate = callValidate);
var formats = this._formats;
var RULES = this.RULES;
try {
var v = localCompile(schema, root, localRefs, baseId);
compilation.validate = v;
var cv = compilation.callValidate;
if (cv) {
cv.schema = v.schema;
cv.errors = null;
cv.refs = v.refs;
cv.refVal = v.refVal;
cv.root = v.root;
cv.$async = v.$async;
if (keepSourceCode) cv.sourceCode = v.sourceCode;
}
return v;
} finally {
endCompiling.call(this, schema, root, baseId);
}
function callValidate() {
var validate = compilation.validate;
var result = validate.apply(null, arguments);
callValidate.errors = validate.errors;
return result;
}
function localCompile(_schema, _root, localRefs, baseId) {
var isRoot = !_root || (_root && _root.schema == _schema);
if (_root.schema != root.schema)
return compile.call(self, _schema, _root, localRefs, baseId);
var $async = _schema.$async === true;
if ($async && !opts.transpile) async.setup(opts);
var sourceCode = validateGenerator({
isTop: true,
schema: _schema,
isRoot: isRoot,
baseId: baseId,
root: _root,
schemaPath: '',
errSchemaPath: '#',
errorPath: '""',
RULES: RULES,
validate: validateGenerator,
util: util,
resolve: resolve,
resolveRef: resolveRef,
usePattern: usePattern,
useDefault: useDefault,
useCustomRule: useCustomRule,
opts: opts,
formats: formats,
self: self
});
sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
+ vars(defaults, defaultCode) + vars(customRules, customRuleCode)
+ sourceCode;
if (opts.beautify) {
loadBeautify();
/* istanbul ignore else */
if (beautify) sourceCode = beautify(sourceCode, opts.beautify);
else console.error('"npm install js-beautify" to use beautify option');
}
// console.log('\n\n\n *** \n', sourceCode);
var validate, validateCode
, transpile = opts._transpileFunc;
try {
validateCode = $async && transpile
? transpile(sourceCode)
: sourceCode;
var makeValidate = new Function(
'self',
'RULES',
'formats',
'root',
'refVal',
'defaults',
'customRules',
'co',
'equal',
'ucs2length',
'ValidationError',
validateCode
);
validate = makeValidate(
self,
RULES,
formats,
root,
refVal,
defaults,
customRules,
co,
equal,
ucs2length,
ValidationError
);
refVal[0] = validate;
} catch(e) {
console.error('Error compiling schema, function code:', validateCode);
throw e;
}
validate.schema = _schema;
validate.errors = null;
validate.refs = refs;
validate.refVal = refVal;
validate.root = isRoot ? validate : _root;
if ($async) validate.$async = true;
if (keepSourceCode) validate.sourceCode = sourceCode;
if (opts.sourceCode === true) {
validate.source = {
patterns: patterns,
defaults: defaults
};
}
return validate;
}
function resolveRef(baseId, ref, isRoot) {
ref = resolve.url(baseId, ref);
var refIndex = refs[ref];
var _refVal, refCode;
if (refIndex !== undefined) {
_refVal = refVal[refIndex];
refCode = 'refVal[' + refIndex + ']';
return resolvedRef(_refVal, refCode);
}
if (!isRoot && root.refs) {
var rootRefId = root.refs[ref];
if (rootRefId !== undefined) {
_refVal = root.refVal[rootRefId];
refCode = addLocalRef(ref, _refVal);
return resolvedRef(_refVal, refCode);
}
}
refCode = addLocalRef(ref);
var v = resolve.call(self, localCompile, root, ref);
if (!v) {
var localSchema = localRefs && localRefs[ref];
if (localSchema) {
v = resolve.inlineRef(localSchema, opts.inlineRefs)
? localSchema
: compile.call(self, localSchema, root, localRefs, baseId);
}
}
if (v) {
replaceLocalRef(ref, v);
return resolvedRef(v, refCode);
}
}
function addLocalRef(ref, v) {
var refId = refVal.length;
refVal[refId] = v;
refs[ref] = refId;
return 'refVal' + refId;
}
function replaceLocalRef(ref, v) {
var refId = refs[ref];
refVal[refId] = v;
}
function resolvedRef(refVal, code) {
return typeof refVal == 'object'
? { code: code, schema: refVal, inline: true }
: { code: code, $async: refVal && refVal.$async };
}
function usePattern(regexStr) {
var index = patternsHash[regexStr];
if (index === undefined) {
index = patternsHash[regexStr] = patterns.length;
patterns[index] = regexStr;
}
return 'pattern' + index;
}
function useDefault(value) {
switch (typeof value) {
case 'boolean':
case 'number':
return '' + value;
case 'string':
return util.toQuotedString(value);
case 'object':
if (value === null) return 'null';
var valueStr = stableStringify(value);
var index = defaultsHash[valueStr];
if (index === undefined) {
index = defaultsHash[valueStr] = defaults.length;
defaults[index] = value;
}
return 'default' + index;
}
}
function useCustomRule(rule, schema, parentSchema, it) {
var validateSchema = rule.definition.validateSchema;
if (validateSchema && self._opts.validateSchema !== false) {
var valid = validateSchema(schema);
if (!valid) {
var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
if (self._opts.validateSchema == 'log') console.error(message);
else throw new Error(message);
}
}
var compile = rule.definition.compile
, inline = rule.definition.inline
, macro = rule.definition.macro;
var validate;
if (compile) {
validate = compile.call(self, schema, parentSchema, it);
} else if (macro) {
validate = macro.call(self, schema, parentSchema, it);
if (opts.validateSchema !== false) self.validateSchema(validate, true);
} else if (inline) {
validate = inline.call(self, it, rule.keyword, schema, parentSchema);
} else {
validate = rule.definition.validate;
}
var index = customRules.length;
customRules[index] = validate;
return {
code: 'customRule' + index,
validate: validate
};
}
}
/**
* Checks if the schema is currently compiled
* @this Ajv
* @param {Object} schema schema to compile
* @param {Object} root root object
* @param {String} baseId base schema ID
* @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
*/
function checkCompiling(schema, root, baseId) {
/* jshint validthis: true */
var index = compIndex.call(this, schema, root, baseId);
if (index >= 0) return { index: index, compiling: true };
index = this._compilations.length;
this._compilations[index] = {
schema: schema,
root: root,
baseId: baseId
};
return { index: index, compiling: false };
}
/**
* Removes the schema from the currently compiled list
* @this Ajv
* @param {Object} schema schema to compile
* @param {Object} root root object
* @param {String} baseId base schema ID
*/
function endCompiling(schema, root, baseId) {
/* jshint validthis: true */
var i = compIndex.call(this, schema, root, baseId);
if (i >= 0) this._compilations.splice(i, 1);
}
/**
* Index of schema compilation in the currently compiled list
* @this Ajv
* @param {Object} schema schema to compile
* @param {Object} root root object
* @param {String} baseId base schema ID
* @return {Integer} compilation index
*/
function compIndex(schema, root, baseId) {
/* jshint validthis: true */
for (var i=0; i<this._compilations.length; i++) {
var c = this._compilations[i];
if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
}
return -1;
}
function patternCode(i, patterns) {
return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
}
function defaultCode(i) {
return 'var default' + i + ' = defaults[' + i + '];';
}
function refValCode(i, refVal) {
return refVal[i] ? 'var refVal' + i + ' = refVal[' + i + '];' : '';
}
function customRuleCode(i) {
return 'var customRule' + i + ' = customRules[' + i + '];';
}
function vars(arr, statement) {
if (!arr.length) return '';
var code = '';
for (var i=0; i<arr.length; i++)
code += statement(i, arr);
return code;
}
},{"../async":55,"../dotjs/validate":90,"./equal":58,"./resolve":61,"./util":65,"./validation_error":66,"co":161,"json-stable-stringify":294}],61:[function(require,module,exports){
'use strict';
var url = require('url')
, equal = require('./equal')
, util = require('./util')
, SchemaObject = require('./schema_obj');
module.exports = resolve;
resolve.normalizeId = normalizeId;
resolve.fullPath = getFullPath;
resolve.url = resolveUrl;
resolve.ids = resolveIds;
resolve.inlineRef = inlineRef;
resolve.schema = resolveSchema;
/**
* [resolve and compile the references ($ref)]
* @this Ajv
* @param {Function} compile reference to schema compilation funciton (localCompile)
* @param {Object} root object with information about the root schema for the current schema
* @param {String} ref reference to resolve
* @return {Object|Function} schema object (if the schema can be inlined) or validation function
*/
function resolve(compile, root, ref) {
/* jshint validthis: true */
var refVal = this._refs[ref];
if (typeof refVal == 'string') {
if (this._refs[refVal]) refVal = this._refs[refVal];
else return resolve.call(this, compile, root, refVal);
}
refVal = refVal || this._schemas[ref];
if (refVal instanceof SchemaObject) {
return inlineRef(refVal.schema, this._opts.inlineRefs)
? refVal.schema
: refVal.validate || this._compile(refVal);
}
var res = resolveSchema.call(this, root, ref);
var schema, v, baseId;
if (res) {
schema = res.schema;
root = res.root;
baseId = res.baseId;
}
if (schema instanceof SchemaObject) {
v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
} else if (schema) {
v = inlineRef(schema, this._opts.inlineRefs)
? schema
: compile.call(this, schema, root, undefined, baseId);
}
return v;
}
/**
* Resolve schema, its root and baseId
* @this Ajv
* @param {Object} root root object with properties schema, refVal, refs
* @param {String} ref reference to resolve
* @return {Object} object with properties schema, root, baseId
*/
function resolveSchema(root, ref) {
/* jshint validthis: true */
var p = url.parse(ref, false, true)
, refPath = _getFullPath(p)
, baseId = getFullPath(root.schema.id);
if (refPath !== baseId) {
var id = normalizeId(refPath);
var refVal = this._refs[id];
if (typeof refVal == 'string') {
return resolveRecursive.call(this, root, refVal, p);
} else if (refVal instanceof SchemaObject) {
if (!refVal.validate) this._compile(refVal);
root = refVal;
} else {
refVal = this._schemas[id];
if (refVal instanceof SchemaObject) {
if (!refVal.validate) this._compile(refVal);
if (id == normalizeId(ref))
return { schema: refVal, root: root, baseId: baseId };
root = refVal;
} else {
return;
}
}
if (!root.schema) return;
baseId = getFullPath(root.schema.id);
}
return getJsonPointer.call(this, p, baseId, root.schema, root);
}
/* @this Ajv */
function resolveRecursive(root, ref, parsedRef) {
/* jshint validthis: true */
var res = resolveSchema.call(this, root, ref);
if (res) {
var schema = res.schema;
var baseId = res.baseId;
root = res.root;
if (schema.id) baseId = resolveUrl(baseId, schema.id);
return getJsonPointer.call(this, parsedRef, baseId, schema, root);
}
}
var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']);
/* @this Ajv */
function getJsonPointer(parsedRef, baseId, schema, root) {
/* jshint validthis: true */
parsedRef.hash = parsedRef.hash || '';
if (parsedRef.hash.slice(0,2) != '#/') return;
var parts = parsedRef.hash.split('/');
for (var i = 1; i < parts.length; i++) {
var part = parts[i];
if (part) {
part = util.unescapeFragment(part);
schema = schema[part];
if (!schema) break;
if (schema.id && !PREVENT_SCOPE_CHANGE[part]) baseId = resolveUrl(baseId, schema.id);
if (schema.$ref) {
var $ref = resolveUrl(baseId, schema.$ref);
var res = resolveSchema.call(this, root, $ref);
if (res) {
schema = res.schema;
root = res.root;
baseId = res.baseId;
}
}
}
}
if (schema && schema != root.schema)
return { schema: schema, root: root, baseId: baseId };
}
var SIMPLE_INLINED = util.toHash([
'type', 'format', 'pattern',
'maxLength', 'minLength',
'maxProperties', 'minProperties',
'maxItems', 'minItems',
'maximum', 'minimum',
'uniqueItems', 'multipleOf',
'required', 'enum'
]);
function inlineRef(schema, limit) {
if (limit === false) return false;
if (limit === undefined || limit === true) return checkNoRef(schema);
else if (limit) return countKeys(schema) <= limit;
}
function checkNoRef(schema) {
var item;
if (Array.isArray(schema)) {
for (var i=0; i<schema.length; i++) {
item = schema[i];
if (typeof item == 'object' && !checkNoRef(item)) return false;
}
} else {
for (var key in schema) {
if (key == '$ref') return false;
item = schema[key];
if (typeof item == 'object' && !checkNoRef(item)) return false;
}
}
return true;
}
function countKeys(schema) {
var count = 0, item;
if (Array.isArray(schema)) {
for (var i=0; i<schema.length; i++) {
item = schema[i];
if (typeof item == 'object') count += countKeys(item);
if (count == Infinity) return Infinity;
}
} else {
for (var key in schema) {
if (key == '$ref') return Infinity;
if (SIMPLE_INLINED[key]) {
count++;
} else {
item = schema[key];
if (typeof item == 'object') count += countKeys(item) + 1;
if (count == Infinity) return Infinity;
}
}
}
return count;
}
function getFullPath(id, normalize) {
if (normalize !== false) id = normalizeId(id);
var p = url.parse(id, false, true);
return _getFullPath(p);
}
function _getFullPath(p) {
var protocolSeparator = p.protocol || p.href.slice(0,2) == '//' ? '//' : '';
return (p.protocol||'') + protocolSeparator + (p.host||'') + (p.path||'') + '#';
}
var TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
}
function resolveUrl(baseId, id) {
id = normalizeId(id);
return url.resolve(baseId, id);
}
/* @this Ajv */
function resolveIds(schema) {
/* eslint no-shadow: 0 */
/* jshint validthis: true */
var id = normalizeId(schema.id);
var localRefs = {};
_resolveIds.call(this, schema, getFullPath(id, false), id);
return localRefs;
/* @this Ajv */
function _resolveIds(schema, fullPath, baseId) {
/* jshint validthis: true */
if (Array.isArray(schema)) {
for (var i=0; i<schema.length; i++)
_resolveIds.call(this, schema[i], fullPath+'/'+i, baseId);
} else if (schema && typeof schema == 'object') {
if (typeof schema.id == 'string') {
var id = baseId = baseId
? url.resolve(baseId, schema.id)
: schema.id;
id = normalizeId(id);
var refVal = this._refs[id];
if (typeof refVal == 'string') refVal = this._refs[refVal];
if (refVal && refVal.schema) {
if (!equal(schema, refVal.schema))
throw new Error('id "' + id + '" resolves to more than one schema');
} else if (id != normalizeId(fullPath)) {
if (id[0] == '#') {
if (localRefs[id] && !equal(schema, localRefs[id]))
throw new Error('id "' + id + '" resolves to more than one schema');
localRefs[id] = schema;
} else {
this._refs[id] = fullPath;
}
}
}
for (var key in schema)
_resolveIds.call(this, schema[key], fullPath+'/'+util.escapeFragment(key), baseId);
}
}
}
},{"./equal":58,"./schema_obj":63,"./util":65,"url":486}],62:[function(require,module,exports){
'use strict';
var ruleModules = require('./_rules')
, toHash = require('./util').toHash;
module.exports = function rules() {
var RULES = [
{ type: 'number',
rules: [ 'maximum', 'minimum', 'multipleOf'] },
{ type: 'string',
rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] },
{ type: 'array',
rules: [ 'maxItems', 'minItems', 'uniqueItems', 'items' ] },
{ type: 'object',
rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'properties' ] },
{ rules: [ '$ref', 'enum', 'not', 'anyOf', 'oneOf', 'allOf' ] }
];
var ALL = [ 'type', 'additionalProperties', 'patternProperties' ];
var KEYWORDS = [ 'additionalItems', '$schema', 'id', 'title', 'description', 'default' ];
var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ];
RULES.all = toHash(ALL);
RULES.forEach(function (group) {
group.rules = group.rules.map(function (keyword) {
ALL.push(keyword);
var rule = RULES.all[keyword] = {
keyword: keyword,
code: ruleModules[keyword]
};
return rule;
});
});
RULES.keywords = toHash(ALL.concat(KEYWORDS));
RULES.types = toHash(TYPES);
RULES.custom = {};
return RULES;
};
},{"./_rules":57,"./util":65}],63:[function(require,module,exports){
'use strict';
var util = require('./util');
module.exports = SchemaObject;
function SchemaObject(obj) {
util.copy(obj, this);
}
},{"./util":65}],64:[function(require,module,exports){
'use strict';
// https://mathiasbynens.be/notes/javascript-encoding
// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
module.exports = function ucs2length(str) {
var length = 0
, len = str.length
, pos = 0
, value;
while (pos < len) {
length++;
value = str.charCodeAt(pos++);
if (value >= 0xD800 && value <= 0xDBFF && pos < len) {
// high surrogate, and there is a next character
value = str.charCodeAt(pos);
if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate
}
}
return length;
};
},{}],65:[function(require,module,exports){
'use strict';
module.exports = {
copy: copy,
checkDataType: checkDataType,
checkDataTypes: checkDataTypes,
coerceToTypes: coerceToTypes,
toHash: toHash,
getProperty: getProperty,
escapeQuotes: escapeQuotes,
ucs2length: require('./ucs2length'),
varOccurences: varOccurences,
varReplace: varReplace,
cleanUpCode: cleanUpCode,
cleanUpVarErrors: cleanUpVarErrors,
schemaHasRules: schemaHasRules,
schemaHasRulesExcept: schemaHasRulesExcept,
stableStringify: require('json-stable-stringify'),
toQuotedString: toQuotedString,
getPathExpr: getPathExpr,
getPath: getPath,
getData: getData,
unescapeFragment: unescapeFragment,
escapeFragment: escapeFragment,
escapeJsonPointer: escapeJsonPointer
};
function copy(o, to) {
to = to || {};
for (var key in o) to[key] = o[key];
return to;
}
function checkDataType(dataType, data, negate) {
var EQUAL = negate ? ' !== ' : ' === '
, AND = negate ? ' || ' : ' && '
, OK = negate ? '!' : ''
, NOT = negate ? '' : '!';
switch (dataType) {
case 'null': return data + EQUAL + 'null';
case 'array': return OK + 'Array.isArray(' + data + ')';
case 'object': return '(' + OK + data + AND +
'typeof ' + data + EQUAL + '"object"' + AND +
NOT + 'Array.isArray(' + data + '))';
case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
NOT + '(' + data + ' % 1)' +
AND + data + EQUAL + data + ')';
default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
}
}
function checkDataTypes(dataTypes, data) {
switch (dataTypes.length) {
case 1: return checkDataType(dataTypes[0], data, true);
default:
var code = '';
var types = toHash(dataTypes);
if (types.array && types.object) {
code = types.null ? '(': '(!' + data + ' || ';
code += 'typeof ' + data + ' !== "object")';
delete types.null;
delete types.array;
delete types.object;
}
if (types.number) delete types.integer;
for (var t in types)
code += (code ? ' && ' : '' ) + checkDataType(t, data, true);
return code;
}
}
var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
function coerceToTypes(optionCoerceTypes, dataTypes) {
if (Array.isArray(dataTypes)) {
var types = [];
for (var i=0; i<dataTypes.length; i++) {
var t = dataTypes[i];
if (COERCE_TO_TYPES[t]) types[types.length] = t;
else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
}
if (types.length) return types;
} else if (COERCE_TO_TYPES[dataTypes]) {
return [dataTypes];
} else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
return ['array'];
}
}
function toHash(arr) {
var hash = {};
for (var i=0; i<arr.length; i++) hash[arr[i]] = true;
return hash;
}
var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
var SINGLE_QUOTE = /'|\\/g;
function getProperty(key) {
return typeof key == 'number'
? '[' + key + ']'
: IDENTIFIER.test(key)
? '.' + key
: "['" + escapeQuotes(key) + "']";
}
function escapeQuotes(str) {
return str.replace(SINGLE_QUOTE, '\\$&')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\f/g, '\\f')
.replace(/\t/g, '\\t');
}
function varOccurences(str, dataVar) {
dataVar += '[^0-9]';
var matches = str.match(new RegExp(dataVar, 'g'));
return matches ? matches.length : 0;
}
function varReplace(str, dataVar, expr) {
dataVar += '([^0-9])';
expr = expr.replace(/\$/g, '$$$$');
return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
}
var EMPTY_ELSE = /else\s*{\s*}/g
, EMPTY_IF_NO_ELSE = /if\s*\([^)]+\)\s*\{\s*\}(?!\s*else)/g
, EMPTY_IF_WITH_ELSE = /if\s*\(([^)]+)\)\s*\{\s*\}\s*else(?!\s*if)/g;
function cleanUpCode(out) {
return out.replace(EMPTY_ELSE, '')
.replace(EMPTY_IF_NO_ELSE, '')
.replace(EMPTY_IF_WITH_ELSE, 'if (!($1))');
}
var ERRORS_REGEXP = /[^v\.]errors/g
, REMOVE_ERRORS = /var errors = 0;|var vErrors = null;|validate.errors = vErrors;/g
, REMOVE_ERRORS_ASYNC = /var errors = 0;|var vErrors = null;/g
, RETURN_VALID = 'return errors === 0;'
, RETURN_TRUE = 'validate.errors = null; return true;'
, RETURN_ASYNC = /if \(errors === 0\) return true;\s*else throw new ValidationError\(vErrors\);/
, RETURN_TRUE_ASYNC = 'return true;';
function cleanUpVarErrors(out, async) {
var matches = out.match(ERRORS_REGEXP);
if (!matches || matches.length !== 2) return out;
return async
? out.replace(REMOVE_ERRORS_ASYNC, '')
.replace(RETURN_ASYNC, RETURN_TRUE_ASYNC)
: out.replace(REMOVE_ERRORS, '')
.replace(RETURN_VALID, RETURN_TRUE);
}
function schemaHasRules(schema, rules) {
for (var key in schema) if (rules[key]) return true;
}
function schemaHasRulesExcept(schema, rules, exceptKeyword) {
for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
}
function toQuotedString(str) {
return '\'' + escapeQuotes(str) + '\'';
}
function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
var path = jsonPointers // false by default
? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
: (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
return joinPaths(currentPath, path);
}
function getPath(currentPath, prop, jsonPointers) {
var path = jsonPointers // false by default
? toQuotedString('/' + escapeJsonPointer(prop))
: toQuotedString(getProperty(prop));
return joinPaths(currentPath, path);
}
var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, lvl, paths) {
var up, jsonPointer, data, matches;
if ($data === '') return 'rootData';
if ($data[0] == '/') {
if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
jsonPointer = $data;
data = 'rootData';
} else {
matches = $data.match(RELATIVE_JSON_POINTER);
if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
up = +matches[1];
jsonPointer = matches[2];
if (jsonPointer == '#') {
if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
return paths[lvl - up];
}
if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
data = 'data' + ((lvl - up) || '');
if (!jsonPointer) return data;
}
var expr = data;
var segments = jsonPointer.split('/');
for (var i=0; i<segments.length; i++) {
var segment = segments[i];
if (segment) {
data += getProperty(unescapeJsonPointer(segment));
expr += ' && ' + data;
}
}
return expr;
}
function joinPaths (a, b) {
if (a == '""') return b;
return (a + ' + ' + b).replace(/' \+ '/g, '');
}
function unescapeFragment(str) {
return unescapeJsonPointer(decodeURIComponent(str));
}
function escapeFragment(str) {
return encodeURIComponent(escapeJsonPointer(str));
}
function escapeJsonPointer(str) {
return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
function unescapeJsonPointer(str) {
return str.replace(/~1/g, '/').replace(/~0/g, '~');
}
},{"./ucs2length":64,"json-stable-stringify":294}],66:[function(require,module,exports){
'use strict';
module.exports = ValidationError;
function ValidationError(errors) {
this.message = 'validation failed';
this.errors = errors;
this.ajv = this.validation = true;
}
ValidationError.prototype = Object.create(Error.prototype);
ValidationError.prototype.constructor = ValidationError;
},{}],67:[function(require,module,exports){
'use strict';
module.exports = function generate__formatLimit(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
out += 'var ' + ($valid) + ' = undefined;';
if (it.opts.format === false) {
out += ' ' + ($valid) + ' = true; ';
return out;
}
var $schemaFormat = it.schema.format,
$isDataFormat = it.opts.v5 && $schemaFormat.$data,
$closingBraces = '';
if ($isDataFormat) {
var $schemaValueFormat = it.util.getData($schemaFormat.$data, $dataLvl, it.dataPathArr),
$format = 'format' + $lvl,
$compare = 'compare' + $lvl;
out += ' var ' + ($format) + ' = formats[' + ($schemaValueFormat) + '] , ' + ($compare) + ' = ' + ($format) + ' && ' + ($format) + '.compare;';
} else {
var $format = it.formats[$schemaFormat];
if (!($format && $format.compare)) {
out += ' ' + ($valid) + ' = true; ';
return out;
}
var $compare = 'formats' + it.util.getProperty($schemaFormat) + '.compare';
}
var $isMax = $keyword == 'formatMaximum',
$exclusiveKeyword = 'formatExclusive' + ($isMax ? 'Maximum' : 'Minimum'),
$schemaExcl = it.schema[$exclusiveKeyword],
$isDataExcl = it.opts.v5 && $schemaExcl && $schemaExcl.$data,
$op = $isMax ? '<' : '>',
$result = 'result' + $lvl;
var $isData = it.opts.v5 && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
if ($isDataExcl) {
var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
$exclusive = 'exclusive' + $lvl,
$opExpr = 'op' + $lvl,
$opStr = '\' + ' + $opExpr + ' + \'';
out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
$schemaValueExcl = 'schemaExcl' + $lvl;
out += ' if (typeof ' + ($schemaValueExcl) + ' != \'boolean\' && ' + ($schemaValueExcl) + ' !== undefined) { ' + ($valid) + ' = false; ';
var $errorKeyword = $exclusiveKeyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || '_formatExclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
if (it.opts.messages !== false) {
out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } ';
if ($breakOnError) {
$closingBraces += '}';
out += ' else { ';
}
if ($isData) {
out += ' if (' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'string\') ' + ($valid) + ' = false; else { ';
$closingBraces += '}';
}
if ($isDataFormat) {
out += ' if (!' + ($compare) + ') ' + ($valid) + ' = true; else { ';
$closingBraces += '}';
}
out += ' var ' + ($result) + ' = ' + ($compare) + '(' + ($data) + ', ';
if ($isData) {
out += '' + ($schemaValue);
} else {
out += '' + (it.util.toQuotedString($schema));
}
out += ' ); if (' + ($result) + ' === undefined) ' + ($valid) + ' = false; var ' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true; if (' + ($valid) + ' === undefined) { ' + ($valid) + ' = ' + ($exclusive) + ' ? ' + ($result) + ' ' + ($op) + ' 0 : ' + ($result) + ' ' + ($op) + '= 0; } if (!' + ($valid) + ') var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';';
} else {
var $exclusive = $schemaExcl === true,
$opStr = $op;
if (!$exclusive) $opStr += '=';
var $opExpr = '\'' + $opStr + '\'';
if ($isData) {
out += ' if (' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'string\') ' + ($valid) + ' = false; else { ';
$closingBraces += '}';
}
if ($isDataFormat) {
out += ' if (!' + ($compare) + ') ' + ($valid) + ' = true; else { ';
$closingBraces += '}';
}
out += ' var ' + ($result) + ' = ' + ($compare) + '(' + ($data) + ', ';
if ($isData) {
out += '' + ($schemaValue);
} else {
out += '' + (it.util.toQuotedString($schema));
}
out += ' ); if (' + ($result) + ' === undefined) ' + ($valid) + ' = false; if (' + ($valid) + ' === undefined) ' + ($valid) + ' = ' + ($result) + ' ' + ($op);
if (!$exclusive) {
out += '=';
}
out += ' 0;';
}
out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { ';
var $errorKeyword = $keyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || '_formatLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ';
if ($isData) {
out += '' + ($schemaValue);
} else {
out += '' + (it.util.toQuotedString($schema));
}
out += ' , exclusive: ' + ($exclusive) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should be ' + ($opStr) + ' "';
if ($isData) {
out += '\' + ' + ($schemaValue) + ' + \'';
} else {
out += '' + (it.util.escapeQuotes($schema));
}
out += '"\' ';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) {
out += 'validate.schema' + ($schemaPath);
} else {
out += '' + (it.util.toQuotedString($schema));
}
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += '}';
return out;
}
},{}],68:[function(require,module,exports){
'use strict';
module.exports = function generate__limit(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $isData = it.opts.v5 && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
var $isMax = $keyword == 'maximum',
$exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum',
$schemaExcl = it.schema[$exclusiveKeyword],
$isDataExcl = it.opts.v5 && $schemaExcl && $schemaExcl.$data,
$op = $isMax ? '<' : '>',
$notOp = $isMax ? '>' : '<';
if ($isDataExcl) {
var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
$exclusive = 'exclusive' + $lvl,
$opExpr = 'op' + $lvl,
$opStr = '\' + ' + $opExpr + ' + \'';
out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
$schemaValueExcl = 'schemaExcl' + $lvl;
out += ' var exclusive' + ($lvl) + '; if (typeof ' + ($schemaValueExcl) + ' != \'boolean\' && typeof ' + ($schemaValueExcl) + ' != \'undefined\') { ';
var $errorKeyword = $exclusiveKeyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
if (it.opts.messages !== false) {
out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } else if( ';
if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
}
out += ' ((exclusive' + ($lvl) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ') || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = exclusive' + ($lvl) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';';
} else {
var $exclusive = $schemaExcl === true,
$opStr = $op;
if (!$exclusive) $opStr += '=';
var $opExpr = '\'' + $opStr + '\'';
out += ' if ( ';
if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
}
out += ' ' + ($data) + ' ' + ($notOp);
if ($exclusive) {
out += '=';
}
out += ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') {';
}
var $errorKeyword = $keyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should be ' + ($opStr) + ' ';
if ($isData) {
out += '\' + ' + ($schemaValue);
} else {
out += '' + ($schema) + '\'';
}
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) {
out += 'validate.schema' + ($schemaPath);
} else {
out += '' + ($schema);
}
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } ';
if ($breakOnError) {
out += ' else { ';
}
return out;
}
},{}],69:[function(require,module,exports){
'use strict';
module.exports = function generate__limitItems(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $isData = it.opts.v5 && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
var $op = $keyword == 'maxItems' ? '>' : '<';
out += 'if ( ';
if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
}
out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { ';
var $errorKeyword = $keyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should NOT have ';
if ($keyword == 'maxItems') {
out += 'more';
} else {
out += 'less';
}
out += ' than ';
if ($isData) {
out += '\' + ' + ($schemaValue) + ' + \'';
} else {
out += '' + ($schema);
}
out += ' items\' ';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) {
out += 'validate.schema' + ($schemaPath);
} else {
out += '' + ($schema);
}
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += '} ';
if ($breakOnError) {
out += ' else { ';
}
return out;
}
},{}],70:[function(require,module,exports){
'use strict';
module.exports = function generate__limitLength(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $isData = it.opts.v5 && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
var $op = $keyword == 'maxLength' ? '>' : '<';
out += 'if ( ';
if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
}
if (it.opts.unicode === false) {
out += ' ' + ($data) + '.length ';
} else {
out += ' ucs2length(' + ($data) + ') ';
}
out += ' ' + ($op) + ' ' + ($schemaValue) + ') { ';
var $errorKeyword = $keyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should NOT be ';
if ($keyword == 'maxLength') {
out += 'longer';
} else {
out += 'shorter';
}
out += ' than ';
if ($isData) {
out += '\' + ' + ($schemaValue) + ' + \'';
} else {
out += '' + ($schema);
}
out += ' characters\' ';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) {
out += 'validate.schema' + ($schemaPath);
} else {
out += '' + ($schema);
}
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += '} ';
if ($breakOnError) {
out += ' else { ';
}
return out;
}
},{}],71:[function(require,module,exports){
'use strict';
module.exports = function generate__limitProperties(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $isData = it.opts.v5 && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
var $op = $keyword == 'maxProperties' ? '>' : '<';
out += 'if ( ';
if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
}
out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { ';
var $errorKeyword = $keyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should NOT have ';
if ($keyword == 'maxProperties') {
out += 'more';
} else {
out += 'less';
}
out += ' than ';
if ($isData) {
out += '\' + ' + ($schemaValue) + ' + \'';
} else {
out += '' + ($schema);
}
out += ' properties\' ';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) {
out += 'validate.schema' + ($schemaPath);
} else {
out += '' + ($schema);
}
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += '} ';
if ($breakOnError) {
out += ' else { ';
}
return out;
}
},{}],72:[function(require,module,exports){
'use strict';
module.exports = function generate_allOf(it, $keyword) {
var out = ' ';
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $currentBaseId = $it.baseId,
$allSchemasEmpty = true;
var arr1 = $schema;
if (arr1) {
var $sch, $i = -1,
l1 = arr1.length - 1;
while ($i < l1) {
$sch = arr1[$i += 1];
if (it.util.schemaHasRules($sch, it.RULES.all)) {
$allSchemasEmpty = false;
$it.schema = $sch;
$it.schemaPath = $schemaPath + '[' + $i + ']';
$it.errSchemaPath = $errSchemaPath + '/' + $i;
out += ' ' + (it.validate($it)) + ' ';
$it.baseId = $currentBaseId;
if ($breakOnError) {
out += ' if (' + ($nextValid) + ') { ';
$closingBraces += '}';
}
}
}
}
if ($breakOnError) {
if ($allSchemasEmpty) {
out += ' if (true) { ';
} else {
out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
}
}
out = it.util.cleanUpCode(out);
return out;
}
},{}],73:[function(require,module,exports){
'use strict';
module.exports = function generate_anyOf(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $noEmptySchema = $schema.every(function($sch) {
return it.util.schemaHasRules($sch, it.RULES.all);
});
if ($noEmptySchema) {
var $currentBaseId = $it.baseId;
out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; ';
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
var arr1 = $schema;
if (arr1) {
var $sch, $i = -1,
l1 = arr1.length - 1;
while ($i < l1) {
$sch = arr1[$i += 1];
$it.schema = $sch;
$it.schemaPath = $schemaPath + '[' + $i + ']';
$it.errSchemaPath = $errSchemaPath + '/' + $i;
out += ' ' + (it.validate($it)) + ' ';
$it.baseId = $currentBaseId;
out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { ';
$closingBraces += '}';
}
}
it.compositeRule = $it.compositeRule = $wasComposite;
out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
if (it.opts.messages !== false) {
out += ' , message: \'should match some schema in anyOf\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
if (it.opts.allErrors) {
out += ' } ';
}
out = it.util.cleanUpCode(out);
} else {
if ($breakOnError) {
out += ' if (true) { ';
}
}
return out;
}
},{}],74:[function(require,module,exports){
'use strict';
module.exports = function generate_constant(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $isData = it.opts.v5 && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
if (!$isData) {
out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';';
}
out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('constant') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
if (it.opts.messages !== false) {
out += ' , message: \'should be equal to constant\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' }';
return out;
}
},{}],75:[function(require,module,exports){
'use strict';
module.exports = function generate_custom(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
var $isData = it.opts.v5 && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
var $rule = this,
$definition = 'definition' + $lvl,
$rDef = $rule.definition;
var $compile, $inline, $macro, $ruleValidate, $validateCode;
if ($isData && $rDef.$data) {
$validateCode = 'keywordValidate' + $lvl;
var $validateSchema = $rDef.validateSchema;
out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;';
} else {
$ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
$schemaValue = 'validate.schema' + $schemaPath;
$validateCode = $ruleValidate.code;
$compile = $rDef.compile;
$inline = $rDef.inline;
$macro = $rDef.macro;
}
var $ruleErrs = $validateCode + '.errors',
$i = 'i' + $lvl,
$ruleErr = 'ruleErr' + $lvl,
$asyncKeyword = $rDef.async;
if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema');
if (!($inline || $macro)) {
out += '' + ($ruleErrs) + ' = null;';
}
out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
if ($validateSchema) {
out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') {';
}
if ($inline) {
if ($rDef.statements) {
out += ' ' + ($ruleValidate.validate) + ' ';
} else {
out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; ';
}
} else if ($macro) {
var $it = it.util.copy(it);
$it.level++;
var $nextValid = 'valid' + $it.level;
$it.schema = $ruleValidate.validate;
$it.schemaPath = '';
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
it.compositeRule = $it.compositeRule = $wasComposite;
out += ' ' + ($code);
} else {
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
out += ' ' + ($validateCode) + '.call( ';
if (it.opts.passContext) {
out += 'this';
} else {
out += 'self';
}
if ($compile || $rDef.schema === false) {
out += ' , ' + ($data) + ' ';
} else {
out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' ';
}
out += ' , (dataPath || \'\')';
if (it.errorPath != '""') {
out += ' + ' + (it.errorPath);
}
var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
$parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) ';
var def_callRuleValidate = out;
out = $$outStack.pop();
if ($rDef.errors === false) {
out += ' ' + ($valid) + ' = ';
if ($asyncKeyword) {
out += '' + (it.yieldAwait);
}
out += '' + (def_callRuleValidate) + '; ';
} else {
if ($asyncKeyword) {
$ruleErrs = 'customErrors' + $lvl;
out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = ' + (it.yieldAwait) + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } ';
} else {
out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; ';
}
}
}
if ($rDef.modifying) {
out += ' ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];';
}
if ($validateSchema) {
out += ' }';
}
if ($rDef.valid) {
if ($breakOnError) {
out += ' if (true) { ';
}
} else {
out += ' if ( ';
if ($rDef.valid === undefined) {
out += ' !';
if ($macro) {
out += '' + ($nextValid);
} else {
out += '' + ($valid);
}
} else {
out += ' ' + (!$rDef.valid) + ' ';
}
out += ') { ';
$errorKeyword = $rule.keyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
var def_customError = out;
out = $$outStack.pop();
if ($inline) {
if ($rDef.errors) {
if ($rDef.errors != 'full') {
out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
if (it.opts.verbose) {
out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
}
out += ' } ';
}
} else {
if ($rDef.errors === false) {
out += ' ' + (def_customError) + ' ';
} else {
out += ' if (' + ($errs) + ' == errors) { ' + (def_customError) + ' } else { for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } ';
if (it.opts.verbose) {
out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
}
out += ' } } ';
}
}
} else if ($macro) {
out += ' var err = '; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError(vErrors); ';
} else {
out += ' validate.errors = vErrors; return false; ';
}
}
} else {
if ($rDef.errors === false) {
out += ' ' + (def_customError) + ' ';
} else {
out += ' if (Array.isArray(' + ($ruleErrs) + ')) { if (vErrors === null) vErrors = ' + ($ruleErrs) + '; else vErrors = vErrors.concat(' + ($ruleErrs) + '); errors = vErrors.length; for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; ';
if (it.opts.verbose) {
out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
}
out += ' } } else { ' + (def_customError) + ' } ';
}
}
out += ' } ';
if ($breakOnError) {
out += ' else { ';
}
}
return out;
}
},{}],76:[function(require,module,exports){
'use strict';
module.exports = function generate_dependencies(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $schemaDeps = {},
$propertyDeps = {};
for ($property in $schema) {
var $sch = $schema[$property];
var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
$deps[$property] = $sch;
}
out += 'var ' + ($errs) + ' = errors;';
var $currentErrorPath = it.errorPath;
out += 'var missing' + ($lvl) + ';';
for (var $property in $propertyDeps) {
$deps = $propertyDeps[$property];
out += ' if (' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
if ($breakOnError) {
out += ' && ( ';
var arr1 = $deps;
if (arr1) {
var _$property, $i = -1,
l1 = arr1.length - 1;
while ($i < l1) {
_$property = arr1[$i += 1];
if ($i) {
out += ' || ';
}
var $prop = it.util.getProperty(_$property);
out += ' ( ' + ($data) + ($prop) + ' === undefined && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? _$property : $prop)) + ') ) ';
}
}
out += ')) { ';
var $propertyPath = 'missing' + $lvl,
$missingProperty = '\' + ' + $propertyPath + ' + \'';
if (it.opts._errorDataPathProperty) {
it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
}
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should have ';
if ($deps.length == 1) {
out += 'property ' + (it.util.escapeQuotes($deps[0]));
} else {
out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
}
out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
} else {
out += ' ) { ';
var arr2 = $deps;
if (arr2) {
var $reqProperty, i2 = -1,
l2 = arr2.length - 1;
while (i2 < l2) {
$reqProperty = arr2[i2 += 1];
var $prop = it.util.getProperty($reqProperty),
$missingProperty = it.util.escapeQuotes($reqProperty);
if (it.opts._errorDataPathProperty) {
it.errorPath = it.util.getPath($currentErrorPath, $reqProperty, it.opts.jsonPointers);
}
out += ' if (' + ($data) + ($prop) + ' === undefined) { var err = '; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should have ';
if ($deps.length == 1) {
out += 'property ' + (it.util.escapeQuotes($deps[0]));
} else {
out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
}
out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
}
}
}
out += ' } ';
if ($breakOnError) {
$closingBraces += '}';
out += ' else { ';
}
}
it.errorPath = $currentErrorPath;
var $currentBaseId = $it.baseId;
for (var $property in $schemaDeps) {
var $sch = $schemaDeps[$property];
if (it.util.schemaHasRules($sch, it.RULES.all)) {
out += ' ' + ($nextValid) + ' = true; if (' + ($data) + (it.util.getProperty($property)) + ' !== undefined) { ';
$it.schema = $sch;
$it.schemaPath = $schemaPath + it.util.getProperty($property);
$it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
out += ' ' + (it.validate($it)) + ' ';
$it.baseId = $currentBaseId;
out += ' } ';
if ($breakOnError) {
out += ' if (' + ($nextValid) + ') { ';
$closingBraces += '}';
}
}
}
if ($breakOnError) {
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
}
out = it.util.cleanUpCode(out);
return out;
}
},{}],77:[function(require,module,exports){
'use strict';
module.exports = function generate_enum(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $isData = it.opts.v5 && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
var $i = 'i' + $lvl,
$vSchema = 'schema' + $lvl;
if (!$isData) {
out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';';
}
out += 'var ' + ($valid) + ';';
if ($isData) {
out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
}
out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }';
if ($isData) {
out += ' } ';
}
out += ' if (!' + ($valid) + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should be equal to one of the allowed values\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' }';
if ($breakOnError) {
out += ' else { ';
}
return out;
}
},{}],78:[function(require,module,exports){
'use strict';
module.exports = function generate_format(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
if (it.opts.format === false) {
if ($breakOnError) {
out += ' if (true) { ';
}
return out;
}
var $isData = it.opts.v5 && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
var $unknownFormats = it.opts.unknownFormats,
$allowUnknown = Array.isArray($unknownFormats);
if ($isData) {
var $format = 'format' + $lvl;
out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var isObject' + ($lvl) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; if (isObject' + ($lvl) + ') { ';
if (it.async) {
out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; ';
}
out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( ';
if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
}
out += ' (';
if ($unknownFormats === true || $allowUnknown) {
out += ' (' + ($schemaValue) + ' && !' + ($format) + ' ';
if ($allowUnknown) {
out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 ';
}
out += ') || ';
}
out += ' (' + ($format) + ' && !(typeof ' + ($format) + ' == \'function\' ? ';
if (it.async) {
out += ' (async' + ($lvl) + ' ? ' + (it.yieldAwait) + ' ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
} else {
out += ' ' + ($format) + '(' + ($data) + ') ';
}
out += ' : ' + ($format) + '.test(' + ($data) + '))))) {';
} else {
var $format = it.formats[$schema];
if (!$format) {
if ($unknownFormats === true || ($allowUnknown && $unknownFormats.indexOf($schema) == -1)) {
throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
} else {
if (!$allowUnknown) {
console.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
if ($unknownFormats !== 'ignore') console.warn('In the next major version it will throw exception. See option unknownFormats for more information');
}
if ($breakOnError) {
out += ' if (true) { ';
}
return out;
}
}
var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;
if ($isObject) {
var $async = $format.async === true;
$format = $format.validate;
}
if ($async) {
if (!it.async) throw new Error('async format in sync schema');
var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
out += ' if (!(' + (it.yieldAwait) + ' ' + ($formatRef) + '(' + ($data) + '))) { ';
} else {
out += ' if (! ';
var $formatRef = 'formats' + it.util.getProperty($schema);
if ($isObject) $formatRef += '.validate';
if (typeof $format == 'function') {
out += ' ' + ($formatRef) + '(' + ($data) + ') ';
} else {
out += ' ' + ($formatRef) + '.test(' + ($data) + ') ';
}
out += ') { ';
}
}
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: ';
if ($isData) {
out += '' + ($schemaValue);
} else {
out += '' + (it.util.toQuotedString($schema));
}
out += ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should match format "';
if ($isData) {
out += '\' + ' + ($schemaValue) + ' + \'';
} else {
out += '' + (it.util.escapeQuotes($schema));
}
out += '"\' ';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) {
out += 'validate.schema' + ($schemaPath);
} else {
out += '' + (it.util.toQuotedString($schema));
}
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } ';
if ($breakOnError) {
out += ' else { ';
}
return out;
}
},{}],79:[function(require,module,exports){
'use strict';
module.exports = function generate_items(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $idx = 'i' + $lvl,
$dataNxt = $it.dataLevel = it.dataLevel + 1,
$nextData = 'data' + $dataNxt,
$currentBaseId = it.baseId;
out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
if (Array.isArray($schema)) {
var $additionalItems = it.schema.additionalItems;
if ($additionalItems === false) {
out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; ';
var $currErrSchemaPath = $errSchemaPath;
$errSchemaPath = it.errSchemaPath + '/additionalItems';
out += ' if (!' + ($valid) + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' ';
}
if (it.opts.verbose) {
out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } ';
$errSchemaPath = $currErrSchemaPath;
if ($breakOnError) {
$closingBraces += '}';
out += ' else { ';
}
}
var arr1 = $schema;
if (arr1) {
var $sch, $i = -1,
l1 = arr1.length - 1;
while ($i < l1) {
$sch = arr1[$i += 1];
if (it.util.schemaHasRules($sch, it.RULES.all)) {
out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { ';
var $passData = $data + '[' + $i + ']';
$it.schema = $sch;
$it.schemaPath = $schemaPath + '[' + $i + ']';
$it.errSchemaPath = $errSchemaPath + '/' + $i;
$it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
$it.dataPathArr[$dataNxt] = $i;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) {
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
} else {
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
}
out += ' } ';
if ($breakOnError) {
out += ' if (' + ($nextValid) + ') { ';
$closingBraces += '}';
}
}
}
}
if (typeof $additionalItems == 'object' && it.util.schemaHasRules($additionalItems, it.RULES.all)) {
$it.schema = $additionalItems;
$it.schemaPath = it.schemaPath + '.additionalItems';
$it.errSchemaPath = it.errSchemaPath + '/additionalItems';
out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
var $passData = $data + '[' + $idx + ']';
$it.dataPathArr[$dataNxt] = $idx;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) {
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
} else {
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
}
if ($breakOnError) {
out += ' if (!' + ($nextValid) + ') break; ';
}
out += ' } } ';
if ($breakOnError) {
out += ' if (' + ($nextValid) + ') { ';
$closingBraces += '}';
}
}
} else if (it.util.schemaHasRules($schema, it.RULES.all)) {
$it.schema = $schema;
$it.schemaPath = $schemaPath;
$it.errSchemaPath = $errSchemaPath;
out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
var $passData = $data + '[' + $idx + ']';
$it.dataPathArr[$dataNxt] = $idx;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) {
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
} else {
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
}
if ($breakOnError) {
out += ' if (!' + ($nextValid) + ') break; ';
}
out += ' } ';
if ($breakOnError) {
out += ' if (' + ($nextValid) + ') { ';
$closingBraces += '}';
}
}
if ($breakOnError) {
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
}
out = it.util.cleanUpCode(out);
return out;
}
},{}],80:[function(require,module,exports){
'use strict';
module.exports = function generate_multipleOf(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $isData = it.opts.v5 && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
out += 'var division' + ($lvl) + ';if (';
if ($isData) {
out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || ';
}
out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', ';
if (it.opts.multipleOfPrecision) {
out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' ';
} else {
out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') ';
}
out += ' ) ';
if ($isData) {
out += ' ) ';
}
out += ' ) { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should be multiple of ';
if ($isData) {
out += '\' + ' + ($schemaValue);
} else {
out += '' + ($schema) + '\'';
}
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) {
out += 'validate.schema' + ($schemaPath);
} else {
out += '' + ($schema);
}
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += '} ';
if ($breakOnError) {
out += ' else { ';
}
return out;
}
},{}],81:[function(require,module,exports){
'use strict';
module.exports = function generate_not(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
$it.level++;
var $nextValid = 'valid' + $it.level;
if (it.util.schemaHasRules($schema, it.RULES.all)) {
$it.schema = $schema;
$it.schemaPath = $schemaPath;
$it.errSchemaPath = $errSchemaPath;
out += ' var ' + ($errs) + ' = errors; ';
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
$it.createErrors = false;
var $allErrorsOption;
if ($it.opts.allErrors) {
$allErrorsOption = $it.opts.allErrors;
$it.opts.allErrors = false;
}
out += ' ' + (it.validate($it)) + ' ';
$it.createErrors = true;
if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
it.compositeRule = $it.compositeRule = $wasComposite;
out += ' if (' + ($nextValid) + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
if (it.opts.messages !== false) {
out += ' , message: \'should NOT be valid\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
if (it.opts.allErrors) {
out += ' } ';
}
} else {
out += ' var err = '; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
if (it.opts.messages !== false) {
out += ' , message: \'should NOT be valid\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if ($breakOnError) {
out += ' if (false) { ';
}
}
return out;
}
},{}],82:[function(require,module,exports){
'use strict';
module.exports = function generate_oneOf(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
out += 'var ' + ($errs) + ' = errors;var prevValid' + ($lvl) + ' = false;var ' + ($valid) + ' = false;';
var $currentBaseId = $it.baseId;
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
var arr1 = $schema;
if (arr1) {
var $sch, $i = -1,
l1 = arr1.length - 1;
while ($i < l1) {
$sch = arr1[$i += 1];
if (it.util.schemaHasRules($sch, it.RULES.all)) {
$it.schema = $sch;
$it.schemaPath = $schemaPath + '[' + $i + ']';
$it.errSchemaPath = $errSchemaPath + '/' + $i;
out += ' ' + (it.validate($it)) + ' ';
$it.baseId = $currentBaseId;
} else {
out += ' var ' + ($nextValid) + ' = true; ';
}
if ($i) {
out += ' if (' + ($nextValid) + ' && prevValid' + ($lvl) + ') ' + ($valid) + ' = false; else { ';
$closingBraces += '}';
}
out += ' if (' + ($nextValid) + ') ' + ($valid) + ' = prevValid' + ($lvl) + ' = true;';
}
}
it.compositeRule = $it.compositeRule = $wasComposite;
out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
if (it.opts.messages !== false) {
out += ' , message: \'should match exactly one schema in oneOf\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }';
if (it.opts.allErrors) {
out += ' } ';
}
return out;
}
},{}],83:[function(require,module,exports){
'use strict';
module.exports = function generate_pattern(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $isData = it.opts.v5 && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema);
out += 'if ( ';
if ($isData) {
out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
}
out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: ';
if ($isData) {
out += '' + ($schemaValue);
} else {
out += '' + (it.util.toQuotedString($schema));
}
out += ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should match pattern "';
if ($isData) {
out += '\' + ' + ($schemaValue) + ' + \'';
} else {
out += '' + (it.util.escapeQuotes($schema));
}
out += '"\' ';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) {
out += 'validate.schema' + ($schemaPath);
} else {
out += '' + (it.util.toQuotedString($schema));
}
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += '} ';
if ($breakOnError) {
out += ' else { ';
}
return out;
}
},{}],84:[function(require,module,exports){
'use strict';
module.exports = function generate_patternRequired(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $key = 'key' + $lvl,
$matched = 'patternMatched' + $lvl,
$closingBraces = '',
$ownProperties = it.opts.ownProperties;
out += 'var ' + ($valid) + ' = true;';
var arr1 = $schema;
if (arr1) {
var $pProperty, i1 = -1,
l1 = arr1.length - 1;
while (i1 < l1) {
$pProperty = arr1[i1 += 1];
out += ' var ' + ($matched) + ' = false; for (var ' + ($key) + ' in ' + ($data) + ') { ';
if ($ownProperties) {
out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; ';
}
out += ' ' + ($matched) + ' = ' + (it.usePattern($pProperty)) + '.test(' + ($key) + '); if (' + ($matched) + ') break; } ';
var $missingPattern = it.util.escapeQuotes($pProperty);
out += ' if (!' + ($matched) + ') { ' + ($valid) + ' = false; var err = '; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('patternRequired') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingPattern: \'' + ($missingPattern) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should have property matching pattern \\\'' + ($missingPattern) + '\\\'\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
if ($breakOnError) {
$closingBraces += '}';
out += ' else { ';
}
}
}
out += '' + ($closingBraces);
return out;
}
},{}],85:[function(require,module,exports){
'use strict';
module.exports = function generate_properties(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $key = 'key' + $lvl,
$dataNxt = $it.dataLevel = it.dataLevel + 1,
$nextData = 'data' + $dataNxt;
var $schemaKeys = Object.keys($schema || {}),
$pProperties = it.schema.patternProperties || {},
$pPropertyKeys = Object.keys($pProperties),
$aProperties = it.schema.additionalProperties,
$someProperties = $schemaKeys.length || $pPropertyKeys.length,
$noAdditional = $aProperties === false,
$additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length,
$removeAdditional = it.opts.removeAdditional,
$checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional,
$ownProperties = it.opts.ownProperties,
$currentBaseId = it.baseId;
var $required = it.schema.required;
if ($required && !(it.opts.v5 && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required);
if (it.opts.v5) {
var $pgProperties = it.schema.patternGroups || {},
$pgPropertyKeys = Object.keys($pgProperties);
}
out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
if ($checkAdditional) {
out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
if ($ownProperties) {
out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; ';
}
if ($someProperties) {
out += ' var isAdditional' + ($lvl) + ' = !(false ';
if ($schemaKeys.length) {
if ($schemaKeys.length > 5) {
out += ' || validate.schema' + ($schemaPath) + '[' + ($key) + '] ';
} else {
var arr1 = $schemaKeys;
if (arr1) {
var $propertyKey, i1 = -1,
l1 = arr1.length - 1;
while (i1 < l1) {
$propertyKey = arr1[i1 += 1];
out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' ';
}
}
}
}
if ($pPropertyKeys.length) {
var arr2 = $pPropertyKeys;
if (arr2) {
var $pProperty, $i = -1,
l2 = arr2.length - 1;
while ($i < l2) {
$pProperty = arr2[$i += 1];
out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') ';
}
}
}
if (it.opts.v5 && $pgPropertyKeys && $pgPropertyKeys.length) {
var arr3 = $pgPropertyKeys;
if (arr3) {
var $pgProperty, $i = -1,
l3 = arr3.length - 1;
while ($i < l3) {
$pgProperty = arr3[$i += 1];
out += ' || ' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ') ';
}
}
}
out += ' ); if (isAdditional' + ($lvl) + ') { ';
}
if ($removeAdditional == 'all') {
out += ' delete ' + ($data) + '[' + ($key) + ']; ';
} else {
var $currentErrorPath = it.errorPath;
var $additionalProperty = '\' + ' + $key + ' + \'';
if (it.opts._errorDataPathProperty) {
it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
}
if ($noAdditional) {
if ($removeAdditional) {
out += ' delete ' + ($data) + '[' + ($key) + ']; ';
} else {
out += ' ' + ($nextValid) + ' = false; ';
var $currErrSchemaPath = $errSchemaPath;
$errSchemaPath = it.errSchemaPath + '/additionalProperties';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should NOT have additional properties\' ';
}
if (it.opts.verbose) {
out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
$errSchemaPath = $currErrSchemaPath;
if ($breakOnError) {
out += ' break; ';
}
}
} else if ($additionalIsSchema) {
if ($removeAdditional == 'failing') {
out += ' var ' + ($errs) + ' = errors; ';
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
$it.schema = $aProperties;
$it.schemaPath = it.schemaPath + '.additionalProperties';
$it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
$it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
var $passData = $data + '[' + $key + ']';
$it.dataPathArr[$dataNxt] = $key;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) {
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
} else {
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
}
out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } ';
it.compositeRule = $it.compositeRule = $wasComposite;
} else {
$it.schema = $aProperties;
$it.schemaPath = it.schemaPath + '.additionalProperties';
$it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
$it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
var $passData = $data + '[' + $key + ']';
$it.dataPathArr[$dataNxt] = $key;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) {
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
} else {
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
}
if ($breakOnError) {
out += ' if (!' + ($nextValid) + ') break; ';
}
}
}
it.errorPath = $currentErrorPath;
}
if ($someProperties) {
out += ' } ';
}
out += ' } ';
if ($breakOnError) {
out += ' if (' + ($nextValid) + ') { ';
$closingBraces += '}';
}
}
var $useDefaults = it.opts.useDefaults && !it.compositeRule;
if ($schemaKeys.length) {
var arr4 = $schemaKeys;
if (arr4) {
var $propertyKey, i4 = -1,
l4 = arr4.length - 1;
while (i4 < l4) {
$propertyKey = arr4[i4 += 1];
var $sch = $schema[$propertyKey];
if (it.util.schemaHasRules($sch, it.RULES.all)) {
var $prop = it.util.getProperty($propertyKey),
$passData = $data + $prop,
$hasDefault = $useDefaults && $sch.default !== undefined;
$it.schema = $sch;
$it.schemaPath = $schemaPath + $prop;
$it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
$it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
$it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) {
$code = it.util.varReplace($code, $nextData, $passData);
var $useData = $passData;
} else {
var $useData = $nextData;
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ';
}
if ($hasDefault) {
out += ' ' + ($code) + ' ';
} else {
if ($requiredHash && $requiredHash[$propertyKey]) {
out += ' if (' + ($useData) + ' === undefined) { ' + ($nextValid) + ' = false; ';
var $currentErrorPath = it.errorPath,
$currErrSchemaPath = $errSchemaPath,
$missingProperty = it.util.escapeQuotes($propertyKey);
if (it.opts._errorDataPathProperty) {
it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
}
$errSchemaPath = it.errSchemaPath + '/required';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'';
if (it.opts._errorDataPathProperty) {
out += 'is a required property';
} else {
out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
}
out += '\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
$errSchemaPath = $currErrSchemaPath;
it.errorPath = $currentErrorPath;
out += ' } else { ';
} else {
if ($breakOnError) {
out += ' if (' + ($useData) + ' === undefined) { ' + ($nextValid) + ' = true; } else { ';
} else {
out += ' if (' + ($useData) + ' !== undefined) { ';
}
}
out += ' ' + ($code) + ' } ';
}
}
if ($breakOnError) {
out += ' if (' + ($nextValid) + ') { ';
$closingBraces += '}';
}
}
}
}
var arr5 = $pPropertyKeys;
if (arr5) {
var $pProperty, i5 = -1,
l5 = arr5.length - 1;
while (i5 < l5) {
$pProperty = arr5[i5 += 1];
var $sch = $pProperties[$pProperty];
if (it.util.schemaHasRules($sch, it.RULES.all)) {
$it.schema = $sch;
$it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
$it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty);
out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
if ($ownProperties) {
out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; ';
}
out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { ';
$it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
var $passData = $data + '[' + $key + ']';
$it.dataPathArr[$dataNxt] = $key;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) {
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
} else {
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
}
if ($breakOnError) {
out += ' if (!' + ($nextValid) + ') break; ';
}
out += ' } ';
if ($breakOnError) {
out += ' else ' + ($nextValid) + ' = true; ';
}
out += ' } ';
if ($breakOnError) {
out += ' if (' + ($nextValid) + ') { ';
$closingBraces += '}';
}
}
}
}
if (it.opts.v5) {
var arr6 = $pgPropertyKeys;
if (arr6) {
var $pgProperty, i6 = -1,
l6 = arr6.length - 1;
while (i6 < l6) {
$pgProperty = arr6[i6 += 1];
var $pgSchema = $pgProperties[$pgProperty],
$sch = $pgSchema.schema;
if (it.util.schemaHasRules($sch, it.RULES.all)) {
$it.schema = $sch;
$it.schemaPath = it.schemaPath + '.patternGroups' + it.util.getProperty($pgProperty) + '.schema';
$it.errSchemaPath = it.errSchemaPath + '/patternGroups/' + it.util.escapeFragment($pgProperty) + '/schema';
out += ' var pgPropCount' + ($lvl) + ' = 0; for (var ' + ($key) + ' in ' + ($data) + ') { ';
if ($ownProperties) {
out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; ';
}
out += ' if (' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ')) { pgPropCount' + ($lvl) + '++; ';
$it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
var $passData = $data + '[' + $key + ']';
$it.dataPathArr[$dataNxt] = $key;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) {
out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
} else {
out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
}
if ($breakOnError) {
out += ' if (!' + ($nextValid) + ') break; ';
}
out += ' } ';
if ($breakOnError) {
out += ' else ' + ($nextValid) + ' = true; ';
}
out += ' } ';
if ($breakOnError) {
out += ' if (' + ($nextValid) + ') { ';
$closingBraces += '}';
}
var $pgMin = $pgSchema.minimum,
$pgMax = $pgSchema.maximum;
if ($pgMin !== undefined || $pgMax !== undefined) {
out += ' var ' + ($valid) + ' = true; ';
var $currErrSchemaPath = $errSchemaPath;
if ($pgMin !== undefined) {
var $limit = $pgMin,
$reason = 'minimum',
$moreOrLess = 'less';
out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' >= ' + ($pgMin) + '; ';
$errSchemaPath = it.errSchemaPath + '/patternGroups/minimum';
out += ' if (!' + ($valid) + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } ';
if ($pgMax !== undefined) {
out += ' else ';
}
}
if ($pgMax !== undefined) {
var $limit = $pgMax,
$reason = 'maximum',
$moreOrLess = 'more';
out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' <= ' + ($pgMax) + '; ';
$errSchemaPath = it.errSchemaPath + '/patternGroups/maximum';
out += ' if (!' + ($valid) + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } ';
}
$errSchemaPath = $currErrSchemaPath;
if ($breakOnError) {
out += ' if (' + ($valid) + ') { ';
$closingBraces += '}';
}
}
}
}
}
}
if ($breakOnError) {
out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
}
out = it.util.cleanUpCode(out);
return out;
}
},{}],86:[function(require,module,exports){
'use strict';
module.exports = function generate_ref(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $async, $refCode;
if ($schema == '#' || $schema == '#/') {
if (it.isRoot) {
$async = it.async;
$refCode = 'validate';
} else {
$async = it.root.schema.$async === true;
$refCode = 'root.refVal[0]';
}
} else {
var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot);
if ($refVal === undefined) {
var $message = 'can\'t resolve reference ' + $schema + ' from id ' + it.baseId;
if (it.opts.missingRefs == 'fail') {
console.log($message);
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' ';
}
if (it.opts.verbose) {
out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
if ($breakOnError) {
out += ' if (false) { ';
}
} else if (it.opts.missingRefs == 'ignore') {
console.log($message);
if ($breakOnError) {
out += ' if (true) { ';
}
} else {
var $error = new Error($message);
$error.missingRef = it.resolve.url(it.baseId, $schema);
$error.missingSchema = it.resolve.normalizeId(it.resolve.fullPath($error.missingRef));
throw $error;
}
} else if ($refVal.inline) {
var $it = it.util.copy(it);
$it.level++;
var $nextValid = 'valid' + $it.level;
$it.schema = $refVal.schema;
$it.schemaPath = '';
$it.errSchemaPath = $schema;
var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
out += ' ' + ($code) + ' ';
if ($breakOnError) {
out += ' if (' + ($nextValid) + ') { ';
}
} else {
$async = $refVal.$async === true;
$refCode = $refVal.code;
}
}
if ($refCode) {
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (it.opts.passContext) {
out += ' ' + ($refCode) + '.call(this, ';
} else {
out += ' ' + ($refCode) + '( ';
}
out += ' ' + ($data) + ', (dataPath || \'\')';
if (it.errorPath != '""') {
out += ' + ' + (it.errorPath);
}
var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
$parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData) ';
var __callValidate = out;
out = $$outStack.pop();
if ($async) {
if (!it.async) throw new Error('async schema referenced by sync schema');
out += ' try { ';
if ($breakOnError) {
out += 'var ' + ($valid) + ' =';
}
out += ' ' + (it.yieldAwait) + ' ' + (__callValidate) + '; } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; } ';
if ($breakOnError) {
out += ' if (' + ($valid) + ') { ';
}
} else {
out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } ';
if ($breakOnError) {
out += ' else { ';
}
}
}
return out;
}
},{}],87:[function(require,module,exports){
'use strict';
module.exports = function generate_required(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $isData = it.opts.v5 && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
var $vSchema = 'schema' + $lvl;
if (!$isData) {
if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
var $required = [];
var arr1 = $schema;
if (arr1) {
var $property, i1 = -1,
l1 = arr1.length - 1;
while (i1 < l1) {
$property = arr1[i1 += 1];
var $propertySch = it.schema.properties[$property];
if (!($propertySch && it.util.schemaHasRules($propertySch, it.RULES.all))) {
$required[$required.length] = $property;
}
}
}
} else {
var $required = $schema;
}
}
if ($isData || $required.length) {
var $currentErrorPath = it.errorPath,
$loopRequired = $isData || $required.length >= it.opts.loopRequired;
if ($breakOnError) {
out += ' var missing' + ($lvl) + '; ';
if ($loopRequired) {
if (!$isData) {
out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
}
var $i = 'i' + $lvl,
$propertyPath = 'schema' + $lvl + '[' + $i + ']',
$missingProperty = '\' + ' + $propertyPath + ' + \'';
if (it.opts._errorDataPathProperty) {
it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
}
out += ' var ' + ($valid) + ' = true; ';
if ($isData) {
out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
}
out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined; if (!' + ($valid) + ') break; } ';
if ($isData) {
out += ' } ';
}
out += ' if (!' + ($valid) + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'';
if (it.opts._errorDataPathProperty) {
out += 'is a required property';
} else {
out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
}
out += '\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } else { ';
} else {
out += ' if ( ';
var arr2 = $required;
if (arr2) {
var _$property, $i = -1,
l2 = arr2.length - 1;
while ($i < l2) {
_$property = arr2[$i += 1];
if ($i) {
out += ' || ';
}
var $prop = it.util.getProperty(_$property);
out += ' ( ' + ($data) + ($prop) + ' === undefined && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? _$property : $prop)) + ') ) ';
}
}
out += ') { ';
var $propertyPath = 'missing' + $lvl,
$missingProperty = '\' + ' + $propertyPath + ' + \'';
if (it.opts._errorDataPathProperty) {
it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
}
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'';
if (it.opts._errorDataPathProperty) {
out += 'is a required property';
} else {
out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
}
out += '\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } else { ';
}
} else {
if ($loopRequired) {
if (!$isData) {
out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
}
var $i = 'i' + $lvl,
$propertyPath = 'schema' + $lvl + '[' + $i + ']',
$missingProperty = '\' + ' + $propertyPath + ' + \'';
if (it.opts._errorDataPathProperty) {
it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
}
if ($isData) {
out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'';
if (it.opts._errorDataPathProperty) {
out += 'is a required property';
} else {
out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
}
out += '\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { ';
}
out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined) { var err = '; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'';
if (it.opts._errorDataPathProperty) {
out += 'is a required property';
} else {
out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
}
out += '\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ';
if ($isData) {
out += ' } ';
}
} else {
var arr3 = $required;
if (arr3) {
var $reqProperty, i3 = -1,
l3 = arr3.length - 1;
while (i3 < l3) {
$reqProperty = arr3[i3 += 1];
var $prop = it.util.getProperty($reqProperty),
$missingProperty = it.util.escapeQuotes($reqProperty);
if (it.opts._errorDataPathProperty) {
it.errorPath = it.util.getPath($currentErrorPath, $reqProperty, it.opts.jsonPointers);
}
out += ' if (' + ($data) + ($prop) + ' === undefined) { var err = '; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'';
if (it.opts._errorDataPathProperty) {
out += 'is a required property';
} else {
out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
}
out += '\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
}
}
}
}
it.errorPath = $currentErrorPath;
} else if ($breakOnError) {
out += ' if (true) {';
}
return out;
}
},{}],88:[function(require,module,exports){
'use strict';
module.exports = function generate_switch(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $ifPassed = 'ifPassed' + it.level,
$currentBaseId = $it.baseId,
$shouldContinue;
out += 'var ' + ($ifPassed) + ';';
var arr1 = $schema;
if (arr1) {
var $sch, $caseIndex = -1,
l1 = arr1.length - 1;
while ($caseIndex < l1) {
$sch = arr1[$caseIndex += 1];
if ($caseIndex && !$shouldContinue) {
out += ' if (!' + ($ifPassed) + ') { ';
$closingBraces += '}';
}
if ($sch.if && it.util.schemaHasRules($sch.if, it.RULES.all)) {
out += ' var ' + ($errs) + ' = errors; ';
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
$it.createErrors = false;
$it.schema = $sch.if;
$it.schemaPath = $schemaPath + '[' + $caseIndex + '].if';
$it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/if';
out += ' ' + (it.validate($it)) + ' ';
$it.baseId = $currentBaseId;
$it.createErrors = true;
it.compositeRule = $it.compositeRule = $wasComposite;
out += ' ' + ($ifPassed) + ' = ' + ($nextValid) + '; if (' + ($ifPassed) + ') { ';
if (typeof $sch.then == 'boolean') {
if ($sch.then === false) {
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('switch') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { caseIndex: ' + ($caseIndex) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should pass "switch" keyword validation\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
}
out += ' var ' + ($nextValid) + ' = ' + ($sch.then) + '; ';
} else {
$it.schema = $sch.then;
$it.schemaPath = $schemaPath + '[' + $caseIndex + '].then';
$it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/then';
out += ' ' + (it.validate($it)) + ' ';
$it.baseId = $currentBaseId;
}
out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } } ';
} else {
out += ' ' + ($ifPassed) + ' = true; ';
if (typeof $sch.then == 'boolean') {
if ($sch.then === false) {
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('switch') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { caseIndex: ' + ($caseIndex) + ' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should pass "switch" keyword validation\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
}
out += ' var ' + ($nextValid) + ' = ' + ($sch.then) + '; ';
} else {
$it.schema = $sch.then;
$it.schemaPath = $schemaPath + '[' + $caseIndex + '].then';
$it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/then';
out += ' ' + (it.validate($it)) + ' ';
$it.baseId = $currentBaseId;
}
}
$shouldContinue = $sch.continue
}
}
out += '' + ($closingBraces) + 'var ' + ($valid) + ' = ' + ($nextValid) + '; ';
out = it.util.cleanUpCode(out);
return out;
}
},{}],89:[function(require,module,exports){
'use strict';
module.exports = function generate_uniqueItems(it, $keyword) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $isData = it.opts.v5 && $schema && $schema.$data,
$schemaValue;
if ($isData) {
out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
$schemaValue = 'schema' + $lvl;
} else {
$schemaValue = $schema;
}
if (($schema || $isData) && it.opts.uniqueItems !== false) {
if ($isData) {
out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { ';
}
out += ' var ' + ($valid) + ' = true; if (' + ($data) + '.length > 1) { var i = ' + ($data) + '.length, j; outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } } ';
if ($isData) {
out += ' } ';
}
out += ' if (!' + ($valid) + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } ';
if (it.opts.messages !== false) {
out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' ';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) {
out += 'validate.schema' + ($schemaPath);
} else {
out += '' + ($schema);
}
out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } ';
if ($breakOnError) {
out += ' else { ';
}
} else {
if ($breakOnError) {
out += ' if (true) { ';
}
}
return out;
}
},{}],90:[function(require,module,exports){
'use strict';
module.exports = function generate_validate(it, $keyword) {
var out = '';
var $async = it.schema.$async === true;
if (it.isTop) {
var $top = it.isTop,
$lvl = it.level = 0,
$dataLvl = it.dataLevel = 0,
$data = 'data';
it.rootId = it.resolve.fullPath(it.root.schema.id);
it.baseId = it.baseId || it.rootId;
if ($async) {
it.async = true;
var $es7 = it.opts.async == 'es7';
it.yieldAwait = $es7 ? 'await' : 'yield';
}
delete it.isTop;
it.dataPathArr = [undefined];
out += ' var validate = ';
if ($async) {
if ($es7) {
out += ' (async function ';
} else {
if (it.opts.async == 'co*') {
out += 'co.wrap';
}
out += '(function* ';
}
} else {
out += ' (function ';
}
out += ' (data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; var vErrors = null; ';
out += ' var errors = 0; ';
out += ' if (rootData === undefined) rootData = data;';
} else {
var $lvl = it.level,
$dataLvl = it.dataLevel,
$data = 'data' + ($dataLvl || '');
if (it.schema.id) it.baseId = it.resolve.url(it.baseId, it.schema.id);
if ($async && !it.async) throw new Error('async schema in sync schema');
out += ' var errs_' + ($lvl) + ' = errors;';
}
var $valid = 'valid' + $lvl,
$breakOnError = !it.opts.allErrors,
$closingBraces1 = '',
$closingBraces2 = '';
var $typeSchema = it.schema.type,
$typeIsArray = Array.isArray($typeSchema);
if ($typeSchema && it.opts.coerceTypes) {
var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
if ($coerceToTypes) {
var $schemaPath = it.schemaPath + '.type',
$errSchemaPath = it.errSchemaPath + '/type',
$method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { ';
var $dataType = 'dataType' + $lvl,
$coerced = 'coerced' + $lvl;
out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; ';
if (it.opts.coerceTypes == 'array') {
out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; ';
}
out += ' var ' + ($coerced) + ' = undefined; ';
var $bracesCoercion = '';
var arr1 = $coerceToTypes;
if (arr1) {
var $type, $i = -1,
l1 = arr1.length - 1;
while ($i < l1) {
$type = arr1[$i += 1];
if ($i) {
out += ' if (' + ($coerced) + ' === undefined) { ';
$bracesCoercion += '}';
}
if (it.opts.coerceTypes == 'array' && $type != 'array') {
out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; } ';
}
if ($type == 'string') {
out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; ';
} else if ($type == 'number' || $type == 'integer') {
out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' ';
if ($type == 'integer') {
out += ' && !(' + ($data) + ' % 1)';
}
out += ')) ' + ($coerced) + ' = +' + ($data) + '; ';
} else if ($type == 'boolean') {
out += ' if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; ';
} else if ($type == 'null') {
out += ' if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; ';
} else if (it.opts.coerceTypes == 'array' && $type == 'array') {
out += ' if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; ';
}
}
}
out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
if ($typeIsArray) {
out += '' + ($typeSchema.join(","));
} else {
out += '' + ($typeSchema);
}
out += '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should be ';
if ($typeIsArray) {
out += '' + ($typeSchema.join(","));
} else {
out += '' + ($typeSchema);
}
out += '\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } else { ';
var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
$parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
out += ' ' + ($data) + ' = ' + ($coerced) + '; ';
if (!$dataLvl) {
out += 'if (' + ($parentData) + ' !== undefined)';
}
out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } } ';
}
}
var $refKeywords;
if (it.schema.$ref && ($refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'))) {
if (it.opts.extendRefs == 'fail') {
throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '"');
} else if (it.opts.extendRefs == 'ignore') {
$refKeywords = false;
console.log('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
} else if (it.opts.extendRefs !== true) {
console.log('$ref: all keywords used in schema at path "' + it.errSchemaPath + '". It will change in the next major version, see issue #260. Use option { extendRefs: true } to keep current behaviour');
}
}
if (it.schema.$ref && !$refKeywords) {
out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' ';
if ($breakOnError) {
out += ' } if (errors === ';
if ($top) {
out += '0';
} else {
out += 'errs_' + ($lvl);
}
out += ') { ';
$closingBraces2 += '}';
}
} else {
var arr2 = it.RULES;
if (arr2) {
var $rulesGroup, i2 = -1,
l2 = arr2.length - 1;
while (i2 < l2) {
$rulesGroup = arr2[i2 += 1];
if ($shouldUseGroup($rulesGroup)) {
if ($rulesGroup.type) {
out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { ';
}
if (it.opts.useDefaults && !it.compositeRule) {
if ($rulesGroup.type == 'object' && it.schema.properties) {
var $schema = it.schema.properties,
$schemaKeys = Object.keys($schema);
var arr3 = $schemaKeys;
if (arr3) {
var $propertyKey, i3 = -1,
l3 = arr3.length - 1;
while (i3 < l3) {
$propertyKey = arr3[i3 += 1];
var $sch = $schema[$propertyKey];
if ($sch.default !== undefined) {
var $passData = $data + it.util.getProperty($propertyKey);
out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = ';
if (it.opts.useDefaults == 'shared') {
out += ' ' + (it.useDefault($sch.default)) + ' ';
} else {
out += ' ' + (JSON.stringify($sch.default)) + ' ';
}
out += '; ';
}
}
}
} else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {
var arr4 = it.schema.items;
if (arr4) {
var $sch, $i = -1,
l4 = arr4.length - 1;
while ($i < l4) {
$sch = arr4[$i += 1];
if ($sch.default !== undefined) {
var $passData = $data + '[' + $i + ']';
out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = ';
if (it.opts.useDefaults == 'shared') {
out += ' ' + (it.useDefault($sch.default)) + ' ';
} else {
out += ' ' + (JSON.stringify($sch.default)) + ' ';
}
out += '; ';
}
}
}
}
}
var arr5 = $rulesGroup.rules;
if (arr5) {
var $rule, i5 = -1,
l5 = arr5.length - 1;
while (i5 < l5) {
$rule = arr5[i5 += 1];
if ($shouldUseRule($rule)) {
out += ' ' + ($rule.code(it, $rule.keyword)) + ' ';
if ($breakOnError) {
$closingBraces1 += '}';
}
}
}
}
if ($breakOnError) {
out += ' ' + ($closingBraces1) + ' ';
$closingBraces1 = '';
}
if ($rulesGroup.type) {
out += ' } ';
if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
var $typeChecked = true;
out += ' else { ';
var $schemaPath = it.schemaPath + '.type',
$errSchemaPath = it.errSchemaPath + '/type';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
if ($typeIsArray) {
out += '' + ($typeSchema.join(","));
} else {
out += '' + ($typeSchema);
}
out += '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should be ';
if ($typeIsArray) {
out += '' + ($typeSchema.join(","));
} else {
out += '' + ($typeSchema);
}
out += '\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } ';
}
}
if ($breakOnError) {
out += ' if (errors === ';
if ($top) {
out += '0';
} else {
out += 'errs_' + ($lvl);
}
out += ') { ';
$closingBraces2 += '}';
}
}
}
}
}
if ($typeSchema && !$typeChecked && !$coerceToTypes) {
var $schemaPath = it.schemaPath + '.type',
$errSchemaPath = it.errSchemaPath + '/type',
$method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
if ($typeIsArray) {
out += '' + ($typeSchema.join(","));
} else {
out += '' + ($typeSchema);
}
out += '\' } ';
if (it.opts.messages !== false) {
out += ' , message: \'should be ';
if ($typeIsArray) {
out += '' + ($typeSchema.join(","));
} else {
out += '' + ($typeSchema);
}
out += '\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' }';
}
if ($breakOnError) {
out += ' ' + ($closingBraces2) + ' ';
}
if ($top) {
if ($async) {
out += ' if (errors === 0) return true; ';
out += ' else throw new ValidationError(vErrors); ';
} else {
out += ' validate.errors = vErrors; ';
out += ' return errors === 0; ';
}
out += ' }); return validate;';
} else {
out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
}
out = it.util.cleanUpCode(out);
if ($top && $breakOnError) {
out = it.util.cleanUpVarErrors(out, $async);
}
function $shouldUseGroup($rulesGroup) {
for (var i = 0; i < $rulesGroup.rules.length; i++)
if ($shouldUseRule($rulesGroup.rules[i])) return true;
}
function $shouldUseRule($rule) {
return it.schema[$rule.keyword] !== undefined || ($rule.keyword == 'properties' && (it.schema.additionalProperties === false || typeof it.schema.additionalProperties == 'object' || (it.schema.patternProperties && Object.keys(it.schema.patternProperties).length) || (it.opts.v5 && it.schema.patternGroups && Object.keys(it.schema.patternGroups).length)));
}
return out;
}
},{}],91:[function(require,module,exports){
'use strict';
var IDENTIFIER = /^[a-z_$][a-z0-9_$\-]*$/i;
var customRuleCode = require('./dotjs/custom');
module.exports = {
add: addKeyword,
get: getKeyword,
remove: removeKeyword
};
/**
* Define custom keyword
* @this Ajv
* @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).
* @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
*/
function addKeyword(keyword, definition) {
/* jshint validthis: true */
/* eslint no-shadow: 0 */
var RULES = this.RULES;
if (RULES.keywords[keyword])
throw new Error('Keyword ' + keyword + ' is already defined');
if (!IDENTIFIER.test(keyword))
throw new Error('Keyword ' + keyword + ' is not a valid identifier');
if (definition) {
if (definition.macro && definition.valid !== undefined)
throw new Error('"valid" option cannot be used with macro keywords');
var dataType = definition.type;
if (Array.isArray(dataType)) {
var i, len = dataType.length;
for (i=0; i<len; i++) checkDataType(dataType[i]);
for (i=0; i<len; i++) _addRule(keyword, dataType[i], definition);
} else {
if (dataType) checkDataType(dataType);
_addRule(keyword, dataType, definition);
}
var $data = definition.$data === true && this._opts.v5;
if ($data && !definition.validate)
throw new Error('$data support: "validate" function is not defined');
var metaSchema = definition.metaSchema;
if (metaSchema) {
if ($data) {
metaSchema = {
anyOf: [
metaSchema,
{ '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#/definitions/$data' }
]
};
}
definition.validateSchema = this.compile(metaSchema, true);
}
}
RULES.keywords[keyword] = RULES.all[keyword] = true;
function _addRule(keyword, dataType, definition) {
var ruleGroup;
for (var i=0; i<RULES.length; i++) {
var rg = RULES[i];
if (rg.type == dataType) {
ruleGroup = rg;
break;
}
}
if (!ruleGroup) {
ruleGroup = { type: dataType, rules: [] };
RULES.push(ruleGroup);
}
var rule = {
keyword: keyword,
definition: definition,
custom: true,
code: customRuleCode
};
ruleGroup.rules.push(rule);
RULES.custom[keyword] = rule;
}
function checkDataType(dataType) {
if (!RULES.types[dataType]) throw new Error('Unknown type ' + dataType);
}
}
/**
* Get keyword
* @this Ajv
* @param {String} keyword pre-defined or custom keyword.
* @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
*/
function getKeyword(keyword) {
/* jshint validthis: true */
var rule = this.RULES.custom[keyword];
return rule ? rule.definition : this.RULES.keywords[keyword] || false;
}
/**
* Remove keyword
* @this Ajv
* @param {String} keyword pre-defined or custom keyword.
*/
function removeKeyword(keyword) {
/* jshint validthis: true */
var RULES = this.RULES;
delete RULES.keywords[keyword];
delete RULES.all[keyword];
delete RULES.custom[keyword];
for (var i=0; i<RULES.length; i++) {
var rules = RULES[i].rules;
for (var j=0; j<rules.length; j++) {
if (rules[j].keyword == keyword) {
rules.splice(j, 1);
break;
}
}
}
}
},{"./dotjs/custom":75}],92:[function(require,module,exports){
module.exports={
"id": "http://json-schema.org/draft-04/schema#",
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "Core schema meta-schema",
"definitions": {
"schemaArray": {
"type": "array",
"minItems": 1,
"items": { "$ref": "#" }
},
"positiveInteger": {
"type": "integer",
"minimum": 0
},
"positiveIntegerDefault0": {
"allOf": [ { "$ref": "#/definitions/positiveInteger" }, { "default": 0 } ]
},
"simpleTypes": {
"enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ]
},
"stringArray": {
"type": "array",
"items": { "type": "string" },
"minItems": 1,
"uniqueItems": true
}
},
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uri"
},
"$schema": {
"type": "string",
"format": "uri"
},
"title": {
"type": "string"
},
"description": {
"type": "string"
},
"default": {},
"multipleOf": {
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
},
"maximum": {
"type": "number"
},
"exclusiveMaximum": {
"type": "boolean",
"default": false
},
"minimum": {
"type": "number"
},
"exclusiveMinimum": {
"type": "boolean",
"default": false
},
"maxLength": { "$ref": "#/definitions/positiveInteger" },
"minLength": { "$ref": "#/definitions/positiveIntegerDefault0" },
"pattern": {
"type": "string",
"format": "regex"
},
"additionalItems": {
"anyOf": [
{ "type": "boolean" },
{ "$ref": "#" }
],
"default": {}
},
"items": {
"anyOf": [
{ "$ref": "#" },
{ "$ref": "#/definitions/schemaArray" }
],
"default": {}
},
"maxItems": { "$ref": "#/definitions/positiveInteger" },
"minItems": { "$ref": "#/definitions/positiveIntegerDefault0" },
"uniqueItems": {
"type": "boolean",
"default": false
},
"maxProperties": { "$ref": "#/definitions/positiveInteger" },
"minProperties": { "$ref": "#/definitions/positiveIntegerDefault0" },
"required": { "$ref": "#/definitions/stringArray" },
"additionalProperties": {
"anyOf": [
{ "type": "boolean" },
{ "$ref": "#" }
],
"default": {}
},
"definitions": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"properties": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"patternProperties": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"dependencies": {
"type": "object",
"additionalProperties": {
"anyOf": [
{ "$ref": "#" },
{ "$ref": "#/definitions/stringArray" }
]
}
},
"enum": {
"type": "array",
"minItems": 1,
"uniqueItems": true
},
"type": {
"anyOf": [
{ "$ref": "#/definitions/simpleTypes" },
{
"type": "array",
"items": { "$ref": "#/definitions/simpleTypes" },
"minItems": 1,
"uniqueItems": true
}
]
},
"allOf": { "$ref": "#/definitions/schemaArray" },
"anyOf": { "$ref": "#/definitions/schemaArray" },
"oneOf": { "$ref": "#/definitions/schemaArray" },
"not": { "$ref": "#" }
},
"dependencies": {
"exclusiveMaximum": [ "maximum" ],
"exclusiveMinimum": [ "minimum" ]
},
"default": {}
}
},{}],93:[function(require,module,exports){
module.exports={
"id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#",
"$schema": "http://json-schema.org/draft-04/schema#",
"description": "Core schema meta-schema (v5 proposals)",
"definitions": {
"schemaArray": {
"type": "array",
"minItems": 1,
"items": { "$ref": "#" }
},
"positiveInteger": {
"type": "integer",
"minimum": 0
},
"positiveIntegerDefault0": {
"allOf": [ { "$ref": "#/definitions/positiveInteger" }, { "default": 0 } ]
},
"simpleTypes": {
"enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ]
},
"stringArray": {
"type": "array",
"items": { "type": "string" },
"minItems": 1,
"uniqueItems": true
},
"$data": {
"type": "object",
"required": [ "$data" ],
"properties": {
"$data": {
"type": "string",
"anyOf": [
{ "format": "relative-json-pointer" },
{ "format": "json-pointer" }
]
}
},
"additionalProperties": false
}
},
"type": "object",
"properties": {
"id": {
"type": "string",
"format": "uri"
},
"$schema": {
"type": "string",
"format": "uri"
},
"title": {
"type": "string"
},
"description": {
"type": "string"
},
"default": {},
"multipleOf": {
"anyOf": [
{
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
},
{ "$ref": "#/definitions/$data" }
]
},
"maximum": {
"anyOf": [
{ "type": "number" },
{ "$ref": "#/definitions/$data" }
]
},
"exclusiveMaximum": {
"anyOf": [
{
"type": "boolean",
"default": false
},
{ "$ref": "#/definitions/$data" }
]
},
"minimum": {
"anyOf": [
{ "type": "number" },
{ "$ref": "#/definitions/$data" }
]
},
"exclusiveMinimum": {
"anyOf": [
{
"type": "boolean",
"default": false
},
{ "$ref": "#/definitions/$data" }
]
},
"maxLength": {
"anyOf": [
{ "$ref": "#/definitions/positiveInteger" },
{ "$ref": "#/definitions/$data" }
]
},
"minLength": {
"anyOf": [
{ "$ref": "#/definitions/positiveIntegerDefault0" },
{ "$ref": "#/definitions/$data" }
]
},
"pattern": {
"anyOf": [
{
"type": "string",
"format": "regex"
},
{ "$ref": "#/definitions/$data" }
]
},
"additionalItems": {
"anyOf": [
{ "type": "boolean" },
{ "$ref": "#" },
{ "$ref": "#/definitions/$data" }
],
"default": {}
},
"items": {
"anyOf": [
{ "$ref": "#" },
{ "$ref": "#/definitions/schemaArray" }
],
"default": {}
},
"maxItems": {
"anyOf": [
{ "$ref": "#/definitions/positiveInteger" },
{ "$ref": "#/definitions/$data" }
]
},
"minItems": {
"anyOf": [
{ "$ref": "#/definitions/positiveIntegerDefault0" },
{ "$ref": "#/definitions/$data" }
]
},
"uniqueItems": {
"anyOf": [
{
"type": "boolean",
"default": false
},
{ "$ref": "#/definitions/$data" }
]
},
"maxProperties": {
"anyOf": [
{ "$ref": "#/definitions/positiveInteger" },
{ "$ref": "#/definitions/$data" }
]
},
"minProperties": {
"anyOf": [
{ "$ref": "#/definitions/positiveIntegerDefault0" },
{ "$ref": "#/definitions/$data" }
]
},
"required": {
"anyOf": [
{ "$ref": "#/definitions/stringArray" },
{ "$ref": "#/definitions/$data" }
]
},
"additionalProperties": {
"anyOf": [
{ "type": "boolean" },
{ "$ref": "#" },
{ "$ref": "#/definitions/$data" }
],
"default": {}
},
"definitions": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"properties": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"patternProperties": {
"type": "object",
"additionalProperties": { "$ref": "#" },
"default": {}
},
"dependencies": {
"type": "object",
"additionalProperties": {
"anyOf": [
{ "$ref": "#" },
{ "$ref": "#/definitions/stringArray" }
]
}
},
"enum": {
"anyOf": [
{
"type": "array",
"minItems": 1,
"uniqueItems": true
},
{ "$ref": "#/definitions/$data" }
]
},
"type": {
"anyOf": [
{ "$ref": "#/definitions/simpleTypes" },
{
"type": "array",
"items": { "$ref": "#/definitions/simpleTypes" },
"minItems": 1,
"uniqueItems": true
}
]
},
"allOf": { "$ref": "#/definitions/schemaArray" },
"anyOf": { "$ref": "#/definitions/schemaArray" },
"oneOf": { "$ref": "#/definitions/schemaArray" },
"not": { "$ref": "#" },
"format": {
"anyOf": [
{ "type": "string" },
{ "$ref": "#/definitions/$data" }
]
},
"formatMaximum": {
"anyOf": [
{ "type": "string" },
{ "$ref": "#/definitions/$data" }
]
},
"formatMinimum": {
"anyOf": [
{ "type": "string" },
{ "$ref": "#/definitions/$data" }
]
},
"formatExclusiveMaximum": {
"anyOf": [
{
"type": "boolean",
"default": false
},
{ "$ref": "#/definitions/$data" }
]
},
"formatExclusiveMinimum": {
"anyOf": [
{
"type": "boolean",
"default": false
},
{ "$ref": "#/definitions/$data" }
]
},
"constant": {
"anyOf": [
{},
{ "$ref": "#/definitions/$data" }
]
},
"contains": { "$ref": "#" },
"patternGroups": {
"type": "object",
"additionalProperties": {
"type": "object",
"required": [ "schema" ],
"properties": {
"maximum": {
"anyOf": [
{ "$ref": "#/definitions/positiveInteger" },
{ "$ref": "#/definitions/$data" }
]
},
"minimum": {
"anyOf": [
{ "$ref": "#/definitions/positiveIntegerDefault0" },
{ "$ref": "#/definitions/$data" }
]
},
"schema": { "$ref": "#" }
},
"additionalProperties": false
},
"default": {}
},
"switch": {
"type": "array",
"items": {
"required": [ "then" ],
"properties": {
"if": { "$ref": "#" },
"then": {
"anyOf": [
{ "type": "boolean" },
{ "$ref": "#" }
]
},
"continue": { "type": "boolean" }
},
"additionalProperties": false,
"dependencies": {
"continue": [ "if" ]
}
}
}
},
"dependencies": {
"exclusiveMaximum": [ "maximum" ],
"exclusiveMinimum": [ "minimum" ],
"formatMaximum": [ "format" ],
"formatMinimum": [ "format" ],
"formatExclusiveMaximum": [ "formatMaximum" ],
"formatExclusiveMinimum": [ "formatMinimum" ]
},
"default": {}
}
},{}],94:[function(require,module,exports){
'use strict';
var META_SCHEMA_ID = 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json';
module.exports = {
enable: enableV5,
META_SCHEMA_ID: META_SCHEMA_ID
};
function enableV5(ajv) {
var inlineFunctions = {
'switch': require('./dotjs/switch'),
'constant': require('./dotjs/constant'),
'_formatLimit': require('./dotjs/_formatLimit'),
'patternRequired': require('./dotjs/patternRequired')
};
if (ajv._opts.meta !== false) {
var metaSchema = require('./refs/json-schema-v5.json');
ajv.addMetaSchema(metaSchema, META_SCHEMA_ID);
}
_addKeyword('constant');
ajv.addKeyword('contains', { type: 'array', macro: containsMacro });
_addKeyword('formatMaximum', 'string', inlineFunctions._formatLimit);
_addKeyword('formatMinimum', 'string', inlineFunctions._formatLimit);
ajv.addKeyword('formatExclusiveMaximum');
ajv.addKeyword('formatExclusiveMinimum');
ajv.addKeyword('patternGroups'); // implemented in properties.jst
_addKeyword('patternRequired', 'object');
_addKeyword('switch');
function _addKeyword(keyword, types, inlineFunc) {
var definition = {
inline: inlineFunc || inlineFunctions[keyword],
statements: true,
errors: 'full'
};
if (types) definition.type = types;
ajv.addKeyword(keyword, definition);
}
}
function containsMacro(schema) {
return {
not: { items: { not: schema } }
};
}
},{"./dotjs/_formatLimit":67,"./dotjs/constant":74,"./dotjs/patternRequired":84,"./dotjs/switch":88,"./refs/json-schema-v5.json":93}],95:[function(require,module,exports){
var asn1 = exports;
asn1.bignum = require('bn.js');
asn1.define = require('./asn1/api').define;
asn1.base = require('./asn1/base');
asn1.constants = require('./asn1/constants');
asn1.decoders = require('./asn1/decoders');
asn1.encoders = require('./asn1/encoders');
},{"./asn1/api":96,"./asn1/base":98,"./asn1/constants":102,"./asn1/decoders":104,"./asn1/encoders":107,"bn.js":122}],96:[function(require,module,exports){
var asn1 = require('../asn1');
var inherits = require('inherits');
var api = exports;
api.define = function define(name, body) {
return new Entity(name, body);
};
function Entity(name, body) {
this.name = name;
this.body = body;
this.decoders = {};
this.encoders = {};
};
Entity.prototype._createNamed = function createNamed(base) {
var named;
try {
named = require('vm').runInThisContext(
'(function ' + this.name + '(entity) {\n' +
' this._initNamed(entity);\n' +
'})'
);
} catch (e) {
named = function (entity) {
this._initNamed(entity);
};
}
inherits(named, base);
named.prototype._initNamed = function initnamed(entity) {
base.call(this, entity);
};
return new named(this);
};
Entity.prototype._getDecoder = function _getDecoder(enc) {
enc = enc || 'der';
// Lazily create decoder
if (!this.decoders.hasOwnProperty(enc))
this.decoders[enc] = this._createNamed(asn1.decoders[enc]);
return this.decoders[enc];
};
Entity.prototype.decode = function decode(data, enc, options) {
return this._getDecoder(enc).decode(data, options);
};
Entity.prototype._getEncoder = function _getEncoder(enc) {
enc = enc || 'der';
// Lazily create encoder
if (!this.encoders.hasOwnProperty(enc))
this.encoders[enc] = this._createNamed(asn1.encoders[enc]);
return this.encoders[enc];
};
Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
return this._getEncoder(enc).encode(data, reporter);
};
},{"../asn1":95,"inherits":287,"vm":499}],97:[function(require,module,exports){
var inherits = require('inherits');
var Reporter = require('../base').Reporter;
var Buffer = require('buffer').Buffer;
function DecoderBuffer(base, options) {
Reporter.call(this, options);
if (!Buffer.isBuffer(base)) {
this.error('Input not Buffer');
return;
}
this.base = base;
this.offset = 0;
this.length = base.length;
}
inherits(DecoderBuffer, Reporter);
exports.DecoderBuffer = DecoderBuffer;
DecoderBuffer.prototype.save = function save() {
return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
};
DecoderBuffer.prototype.restore = function restore(save) {
// Return skipped data
var res = new DecoderBuffer(this.base);
res.offset = save.offset;
res.length = this.offset;
this.offset = save.offset;
Reporter.prototype.restore.call(this, save.reporter);
return res;
};
DecoderBuffer.prototype.isEmpty = function isEmpty() {
return this.offset === this.length;
};
DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
if (this.offset + 1 <= this.length)
return this.base.readUInt8(this.offset++, true);
else
return this.error(fail || 'DecoderBuffer overrun');
}
DecoderBuffer.prototype.skip = function skip(bytes, fail) {
if (!(this.offset + bytes <= this.length))
return this.error(fail || 'DecoderBuffer overrun');
var res = new DecoderBuffer(this.base);
// Share reporter state
res._reporterState = this._reporterState;
res.offset = this.offset;
res.length = this.offset + bytes;
this.offset += bytes;
return res;
}
DecoderBuffer.prototype.raw = function raw(save) {
return this.base.slice(save ? save.offset : this.offset, this.length);
}
function EncoderBuffer(value, reporter) {
if (Array.isArray(value)) {
this.length = 0;
this.value = value.map(function(item) {
if (!(item instanceof EncoderBuffer))
item = new EncoderBuffer(item, reporter);
this.length += item.length;
return item;
}, this);
} else if (typeof value === 'number') {
if (!(0 <= value && value <= 0xff))
return reporter.error('non-byte EncoderBuffer value');
this.value = value;
this.length = 1;
} else if (typeof value === 'string') {
this.value = value;
this.length = Buffer.byteLength(value);
} else if (Buffer.isBuffer(value)) {
this.value = value;
this.length = value.length;
} else {
return reporter.error('Unsupported type: ' + typeof value);
}
}
exports.EncoderBuffer = EncoderBuffer;
EncoderBuffer.prototype.join = function join(out, offset) {
if (!out)
out = new Buffer(this.length);
if (!offset)
offset = 0;
if (this.length === 0)
return out;
if (Array.isArray(this.value)) {
this.value.forEach(function(item) {
item.join(out, offset);
offset += item.length;
});
} else {
if (typeof this.value === 'number')
out[offset] = this.value;
else if (typeof this.value === 'string')
out.write(this.value, offset);
else if (Buffer.isBuffer(this.value))
this.value.copy(out, offset);
offset += this.length;
}
return out;
};
},{"../base":98,"buffer":157,"inherits":287}],98:[function(require,module,exports){
var base = exports;
base.Reporter = require('./reporter').Reporter;
base.DecoderBuffer = require('./buffer').DecoderBuffer;
base.EncoderBuffer = require('./buffer').EncoderBuffer;
base.Node = require('./node');
},{"./buffer":97,"./node":99,"./reporter":100}],99:[function(require,module,exports){
var Reporter = require('../base').Reporter;
var EncoderBuffer = require('../base').EncoderBuffer;
var DecoderBuffer = require('../base').DecoderBuffer;
var assert = require('minimalistic-assert');
// Supported tags
var tags = [
'seq', 'seqof', 'set', 'setof', 'objid', 'bool',
'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc',
'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str',
'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr'
];
// Public methods list
var methods = [
'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',
'any', 'contains'
].concat(tags);
// Overrided methods list
var overrided = [
'_peekTag', '_decodeTag', '_use',
'_decodeStr', '_decodeObjid', '_decodeTime',
'_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',
'_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',
'_encodeNull', '_encodeInt', '_encodeBool'
];
function Node(enc, parent) {
var state = {};
this._baseState = state;
state.enc = enc;
state.parent = parent || null;
state.children = null;
// State
state.tag = null;
state.args = null;
state.reverseArgs = null;
state.choice = null;
state.optional = false;
state.any = false;
state.obj = false;
state.use = null;
state.useDecoder = null;
state.key = null;
state['default'] = null;
state.explicit = null;
state.implicit = null;
state.contains = null;
// Should create new instance on each method
if (!state.parent) {
state.children = [];
this._wrap();
}
}
module.exports = Node;
var stateProps = [
'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',
'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',
'implicit', 'contains'
];
Node.prototype.clone = function clone() {
var state = this._baseState;
var cstate = {};
stateProps.forEach(function(prop) {
cstate[prop] = state[prop];
});
var res = new this.constructor(cstate.parent);
res._baseState = cstate;
return res;
};
Node.prototype._wrap = function wrap() {
var state = this._baseState;
methods.forEach(function(method) {
this[method] = function _wrappedMethod() {
var clone = new this.constructor(this);
state.children.push(clone);
return clone[method].apply(clone, arguments);
};
}, this);
};
Node.prototype._init = function init(body) {
var state = this._baseState;
assert(state.parent === null);
body.call(this);
// Filter children
state.children = state.children.filter(function(child) {
return child._baseState.parent === this;
}, this);
assert.equal(state.children.length, 1, 'Root node can have only one child');
};
Node.prototype._useArgs = function useArgs(args) {
var state = this._baseState;
// Filter children and args
var children = args.filter(function(arg) {
return arg instanceof this.constructor;
}, this);
args = args.filter(function(arg) {
return !(arg instanceof this.constructor);
}, this);
if (children.length !== 0) {
assert(state.children === null);
state.children = children;
// Replace parent to maintain backward link
children.forEach(function(child) {
child._baseState.parent = this;
}, this);
}
if (args.length !== 0) {
assert(state.args === null);
state.args = args;
state.reverseArgs = args.map(function(arg) {
if (typeof arg !== 'object' || arg.constructor !== Object)
return arg;
var res = {};
Object.keys(arg).forEach(function(key) {
if (key == (key | 0))
key |= 0;
var value = arg[key];
res[value] = key;
});
return res;
});
}
};
//
// Overrided methods
//
overrided.forEach(function(method) {
Node.prototype[method] = function _overrided() {
var state = this._baseState;
throw new Error(method + ' not implemented for encoding: ' + state.enc);
};
});
//
// Public methods
//
tags.forEach(function(tag) {
Node.prototype[tag] = function _tagMethod() {
var state = this._baseState;
var args = Array.prototype.slice.call(arguments);
assert(state.tag === null);
state.tag = tag;
this._useArgs(args);
return this;
};
});
Node.prototype.use = function use(item) {
assert(item);
var state = this._baseState;
assert(state.use === null);
state.use = item;
return this;
};
Node.prototype.optional = function optional() {
var state = this._baseState;
state.optional = true;
return this;
};
Node.prototype.def = function def(val) {
var state = this._baseState;
assert(state['default'] === null);
state['default'] = val;
state.optional = true;
return this;
};
Node.prototype.explicit = function explicit(num) {
var state = this._baseState;
assert(state.explicit === null && state.implicit === null);
state.explicit = num;
return this;
};
Node.prototype.implicit = function implicit(num) {
var state = this._baseState;
assert(state.explicit === null && state.implicit === null);
state.implicit = num;
return this;
};
Node.prototype.obj = function obj() {
var state = this._baseState;
var args = Array.prototype.slice.call(arguments);
state.obj = true;
if (args.length !== 0)
this._useArgs(args);
return this;
};
Node.prototype.key = function key(newKey) {
var state = this._baseState;
assert(state.key === null);
state.key = newKey;
return this;
};
Node.prototype.any = function any() {
var state = this._baseState;
state.any = true;
return this;
};
Node.prototype.choice = function choice(obj) {
var state = this._baseState;
assert(state.choice === null);
state.choice = obj;
this._useArgs(Object.keys(obj).map(function(key) {
return obj[key];
}));
return this;
};
Node.prototype.contains = function contains(item) {
var state = this._baseState;
assert(state.use === null);
state.contains = item;
return this;
};
//
// Decoding
//
Node.prototype._decode = function decode(input, options) {
var state = this._baseState;
// Decode root node
if (state.parent === null)
return input.wrapResult(state.children[0]._decode(input, options));
var result = state['default'];
var present = true;
var prevKey = null;
if (state.key !== null)
prevKey = input.enterKey(state.key);
// Check if tag is there
if (state.optional) {
var tag = null;
if (state.explicit !== null)
tag = state.explicit;
else if (state.implicit !== null)
tag = state.implicit;
else if (state.tag !== null)
tag = state.tag;
if (tag === null && !state.any) {
// Trial and Error
var save = input.save();
try {
if (state.choice === null)
this._decodeGeneric(state.tag, input, options);
else
this._decodeChoice(input, options);
present = true;
} catch (e) {
present = false;
}
input.restore(save);
} else {
present = this._peekTag(input, tag, state.any);
if (input.isError(present))
return present;
}
}
// Push object on stack
var prevObj;
if (state.obj && present)
prevObj = input.enterObject();
if (present) {
// Unwrap explicit values
if (state.explicit !== null) {
var explicit = this._decodeTag(input, state.explicit);
if (input.isError(explicit))
return explicit;
input = explicit;
}
var start = input.offset;
// Unwrap implicit and normal values
if (state.use === null && state.choice === null) {
if (state.any)
var save = input.save();
var body = this._decodeTag(
input,
state.implicit !== null ? state.implicit : state.tag,
state.any
);
if (input.isError(body))
return body;
if (state.any)
result = input.raw(save);
else
input = body;
}
if (options && options.track && state.tag !== null)
options.track(input.path(), start, input.length, 'tagged');
if (options && options.track && state.tag !== null)
options.track(input.path(), input.offset, input.length, 'content');
// Select proper method for tag
if (state.any)
result = result;
else if (state.choice === null)
result = this._decodeGeneric(state.tag, input, options);
else
result = this._decodeChoice(input, options);
if (input.isError(result))
return result;
// Decode children
if (!state.any && state.choice === null && state.children !== null) {
state.children.forEach(function decodeChildren(child) {
// NOTE: We are ignoring errors here, to let parser continue with other
// parts of encoded data
child._decode(input, options);
});
}
// Decode contained/encoded by schema, only in bit or octet strings
if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) {
var data = new DecoderBuffer(result);
result = this._getUse(state.contains, input._reporterState.obj)
._decode(data, options);
}
}
// Pop object
if (state.obj && present)
result = input.leaveObject(prevObj);
// Set key
if (state.key !== null && (result !== null || present === true))
input.leaveKey(prevKey, state.key, result);
else if (prevKey !== null)
input.exitKey(prevKey);
return result;
};
Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) {
var state = this._baseState;
if (tag === 'seq' || tag === 'set')
return null;
if (tag === 'seqof' || tag === 'setof')
return this._decodeList(input, tag, state.args[0], options);
else if (/str$/.test(tag))
return this._decodeStr(input, tag, options);
else if (tag === 'objid' && state.args)
return this._decodeObjid(input, state.args[0], state.args[1], options);
else if (tag === 'objid')
return this._decodeObjid(input, null, null, options);
else if (tag === 'gentime' || tag === 'utctime')
return this._decodeTime(input, tag, options);
else if (tag === 'null_')
return this._decodeNull(input, options);
else if (tag === 'bool')
return this._decodeBool(input, options);
else if (tag === 'objDesc')
return this._decodeStr(input, tag, options);
else if (tag === 'int' || tag === 'enum')
return this._decodeInt(input, state.args && state.args[0], options);
if (state.use !== null) {
return this._getUse(state.use, input._reporterState.obj)
._decode(input, options);
} else {
return input.error('unknown tag: ' + tag);
}
};
Node.prototype._getUse = function _getUse(entity, obj) {
var state = this._baseState;
// Create altered use decoder if implicit is set
state.useDecoder = this._use(entity, obj);
assert(state.useDecoder._baseState.parent === null);
state.useDecoder = state.useDecoder._baseState.children[0];
if (state.implicit !== state.useDecoder._baseState.implicit) {
state.useDecoder = state.useDecoder.clone();
state.useDecoder._baseState.implicit = state.implicit;
}
return state.useDecoder;
};
Node.prototype._decodeChoice = function decodeChoice(input, options) {
var state = this._baseState;
var result = null;
var match = false;
Object.keys(state.choice).some(function(key) {
var save = input.save();
var node = state.choice[key];
try {
var value = node._decode(input, options);
if (input.isError(value))
return false;
result = { type: key, value: value };
match = true;
} catch (e) {
input.restore(save);
return false;
}
return true;
}, this);
if (!match)
return input.error('Choice not matched');
return result;
};
//
// Encoding
//
Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) {
return new EncoderBuffer(data, this.reporter);
};
Node.prototype._encode = function encode(data, reporter, parent) {
var state = this._baseState;
if (state['default'] !== null && state['default'] === data)
return;
var result = this._encodeValue(data, reporter, parent);
if (result === undefined)
return;
if (this._skipDefault(result, reporter, parent))
return;
return result;
};
Node.prototype._encodeValue = function encode(data, reporter, parent) {
var state = this._baseState;
// Decode root node
if (state.parent === null)
return state.children[0]._encode(data, reporter || new Reporter());
var result = null;
// Set reporter to share it with a child class
this.reporter = reporter;
// Check if data is there
if (state.optional && data === undefined) {
if (state['default'] !== null)
data = state['default']
else
return;
}
// Encode children first
var content = null;
var primitive = false;
if (state.any) {
// Anything that was given is translated to buffer
result = this._createEncoderBuffer(data);
} else if (state.choice) {
result = this._encodeChoice(data, reporter);
} else if (state.contains) {
content = this._getUse(state.contains, parent)._encode(data, reporter);
primitive = true;
} else if (state.children) {
content = state.children.map(function(child) {
if (child._baseState.tag === 'null_')
return child._encode(null, reporter, data);
if (child._baseState.key === null)
return reporter.error('Child should have a key');
var prevKey = reporter.enterKey(child._baseState.key);
if (typeof data !== 'object')
return reporter.error('Child expected, but input is not object');
var res = child._encode(data[child._baseState.key], reporter, data);
reporter.leaveKey(prevKey);
return res;
}, this).filter(function(child) {
return child;
});
content = this._createEncoderBuffer(content);
} else {
if (state.tag === 'seqof' || state.tag === 'setof') {
// TODO(indutny): this should be thrown on DSL level
if (!(state.args && state.args.length === 1))
return reporter.error('Too many args for : ' + state.tag);
if (!Array.isArray(data))
return reporter.error('seqof/setof, but data is not Array');
var child = this.clone();
child._baseState.implicit = null;
content = this._createEncoderBuffer(data.map(function(item) {
var state = this._baseState;
return this._getUse(state.args[0], data)._encode(item, reporter);
}, child));
} else if (state.use !== null) {
result = this._getUse(state.use, parent)._encode(data, reporter);
} else {
content = this._encodePrimitive(state.tag, data);
primitive = true;
}
}
// Encode data itself
var result;
if (!state.any && state.choice === null) {
var tag = state.implicit !== null ? state.implicit : state.tag;
var cls = state.implicit === null ? 'universal' : 'context';
if (tag === null) {
if (state.use === null)
reporter.error('Tag could be omitted only for .use()');
} else {
if (state.use === null)
result = this._encodeComposite(tag, primitive, cls, content);
}
}
// Wrap in explicit
if (state.explicit !== null)
result = this._encodeComposite(state.explicit, false, 'context', result);
return result;
};
Node.prototype._encodeChoice = function encodeChoice(data, reporter) {
var state = this._baseState;
var node = state.choice[data.type];
if (!node) {
assert(
false,
data.type + ' not found in ' +
JSON.stringify(Object.keys(state.choice)));
}
return node._encode(data.value, reporter);
};
Node.prototype._encodePrimitive = function encodePrimitive(tag, data) {
var state = this._baseState;
if (/str$/.test(tag))
return this._encodeStr(data, tag);
else if (tag === 'objid' && state.args)
return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);
else if (tag === 'objid')
return this._encodeObjid(data, null, null);
else if (tag === 'gentime' || tag === 'utctime')
return this._encodeTime(data, tag);
else if (tag === 'null_')
return this._encodeNull();
else if (tag === 'int' || tag === 'enum')
return this._encodeInt(data, state.args && state.reverseArgs[0]);
else if (tag === 'bool')
return this._encodeBool(data);
else if (tag === 'objDesc')
return this._encodeStr(data, tag);
else
throw new Error('Unsupported tag: ' + tag);
};
Node.prototype._isNumstr = function isNumstr(str) {
return /^[0-9 ]*$/.test(str);
};
Node.prototype._isPrintstr = function isPrintstr(str) {
return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str);
};
},{"../base":98,"minimalistic-assert":308}],100:[function(require,module,exports){
var inherits = require('inherits');
function Reporter(options) {
this._reporterState = {
obj: null,
path: [],
options: options || {},
errors: []
};
}
exports.Reporter = Reporter;
Reporter.prototype.isError = function isError(obj) {
return obj instanceof ReporterError;
};
Reporter.prototype.save = function save() {
var state = this._reporterState;
return { obj: state.obj, pathLen: state.path.length };
};
Reporter.prototype.restore = function restore(data) {
var state = this._reporterState;
state.obj = data.obj;
state.path = state.path.slice(0, data.pathLen);
};
Reporter.prototype.enterKey = function enterKey(key) {
return this._reporterState.path.push(key);
};
Reporter.prototype.exitKey = function exitKey(index) {
var state = this._reporterState;
state.path = state.path.slice(0, index - 1);
};
Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
var state = this._reporterState;
this.exitKey(index);
if (state.obj !== null)
state.obj[key] = value;
};
Reporter.prototype.path = function path() {
return this._reporterState.path.join('/');
};
Reporter.prototype.enterObject = function enterObject() {
var state = this._reporterState;
var prev = state.obj;
state.obj = {};
return prev;
};
Reporter.prototype.leaveObject = function leaveObject(prev) {
var state = this._reporterState;
var now = state.obj;
state.obj = prev;
return now;
};
Reporter.prototype.error = function error(msg) {
var err;
var state = this._reporterState;
var inherited = msg instanceof ReporterError;
if (inherited) {
err = msg;
} else {
err = new ReporterError(state.path.map(function(elem) {
return '[' + JSON.stringify(elem) + ']';
}).join(''), msg.message || msg, msg.stack);
}
if (!state.options.partial)
throw err;
if (!inherited)
state.errors.push(err);
return err;
};
Reporter.prototype.wrapResult = function wrapResult(result) {
var state = this._reporterState;
if (!state.options.partial)
return result;
return {
result: this.isError(result) ? null : result,
errors: state.errors
};
};
function ReporterError(path, msg) {
this.path = path;
this.rethrow(msg);
};
inherits(ReporterError, Error);
ReporterError.prototype.rethrow = function rethrow(msg) {
this.message = msg + ' at: ' + (this.path || '(shallow)');
if (Error.captureStackTrace)
Error.captureStackTrace(this, ReporterError);
if (!this.stack) {
try {
// IE only adds stack when thrown
throw new Error(this.message);
} catch (e) {
this.stack = e.stack;
}
}
return this;
};
},{"inherits":287}],101:[function(require,module,exports){
var constants = require('../constants');
exports.tagClass = {
0: 'universal',
1: 'application',
2: 'context',
3: 'private'
};
exports.tagClassByName = constants._reverse(exports.tagClass);
exports.tag = {
0x00: 'end',
0x01: 'bool',
0x02: 'int',
0x03: 'bitstr',
0x04: 'octstr',
0x05: 'null_',
0x06: 'objid',
0x07: 'objDesc',
0x08: 'external',
0x09: 'real',
0x0a: 'enum',
0x0b: 'embed',
0x0c: 'utf8str',
0x0d: 'relativeOid',
0x10: 'seq',
0x11: 'set',
0x12: 'numstr',
0x13: 'printstr',
0x14: 't61str',
0x15: 'videostr',
0x16: 'ia5str',
0x17: 'utctime',
0x18: 'gentime',
0x19: 'graphstr',
0x1a: 'iso646str',
0x1b: 'genstr',
0x1c: 'unistr',
0x1d: 'charstr',
0x1e: 'bmpstr'
};
exports.tagByName = constants._reverse(exports.tag);
},{"../constants":102}],102:[function(require,module,exports){
var constants = exports;
// Helper
constants._reverse = function reverse(map) {
var res = {};
Object.keys(map).forEach(function(key) {
// Convert key to integer if it is stringified
if ((key | 0) == key)
key = key | 0;
var value = map[key];
res[value] = key;
});
return res;
};
constants.der = require('./der');
},{"./der":101}],103:[function(require,module,exports){
var inherits = require('inherits');
var asn1 = require('../../asn1');
var base = asn1.base;
var bignum = asn1.bignum;
// Import DER constants
var der = asn1.constants.der;
function DERDecoder(entity) {
this.enc = 'der';
this.name = entity.name;
this.entity = entity;
// Construct base tree
this.tree = new DERNode();
this.tree._init(entity.body);
};
module.exports = DERDecoder;
DERDecoder.prototype.decode = function decode(data, options) {
if (!(data instanceof base.DecoderBuffer))
data = new base.DecoderBuffer(data, options);
return this.tree._decode(data, options);
};
// Tree methods
function DERNode(parent) {
base.Node.call(this, 'der', parent);
}
inherits(DERNode, base.Node);
DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
if (buffer.isEmpty())
return false;
var state = buffer.save();
var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
if (buffer.isError(decodedTag))
return decodedTag;
buffer.restore(state);
return decodedTag.tag === tag || decodedTag.tagStr === tag ||
(decodedTag.tagStr + 'of') === tag || any;
};
DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
var decodedTag = derDecodeTag(buffer,
'Failed to decode tag of "' + tag + '"');
if (buffer.isError(decodedTag))
return decodedTag;
var len = derDecodeLen(buffer,
decodedTag.primitive,
'Failed to get length of "' + tag + '"');
// Failure
if (buffer.isError(len))
return len;
if (!any &&
decodedTag.tag !== tag &&
decodedTag.tagStr !== tag &&
decodedTag.tagStr + 'of' !== tag) {
return buffer.error('Failed to match tag: "' + tag + '"');
}
if (decodedTag.primitive || len !== null)
return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
// Indefinite length... find END tag
var state = buffer.save();
var res = this._skipUntilEnd(
buffer,
'Failed to skip indefinite length body: "' + this.tag + '"');
if (buffer.isError(res))
return res;
len = buffer.offset - state.offset;
buffer.restore(state);
return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
};
DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
while (true) {
var tag = derDecodeTag(buffer, fail);
if (buffer.isError(tag))
return tag;
var len = derDecodeLen(buffer, tag.primitive, fail);
if (buffer.isError(len))
return len;
var res;
if (tag.primitive || len !== null)
res = buffer.skip(len)
else
res = this._skipUntilEnd(buffer, fail);
// Failure
if (buffer.isError(res))
return res;
if (tag.tagStr === 'end')
break;
}
};
DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder,
options) {
var result = [];
while (!buffer.isEmpty()) {
var possibleEnd = this._peekTag(buffer, 'end');
if (buffer.isError(possibleEnd))
return possibleEnd;
var res = decoder.decode(buffer, 'der', options);
if (buffer.isError(res) && possibleEnd)
break;
result.push(res);
}
return result;
};
DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
if (tag === 'bitstr') {
var unused = buffer.readUInt8();
if (buffer.isError(unused))
return unused;
return { unused: unused, data: buffer.raw() };
} else if (tag === 'bmpstr') {
var raw = buffer.raw();
if (raw.length % 2 === 1)
return buffer.error('Decoding of string type: bmpstr length mismatch');
var str = '';
for (var i = 0; i < raw.length / 2; i++) {
str += String.fromCharCode(raw.readUInt16BE(i * 2));
}
return str;
} else if (tag === 'numstr') {
var numstr = buffer.raw().toString('ascii');
if (!this._isNumstr(numstr)) {
return buffer.error('Decoding of string type: ' +
'numstr unsupported characters');
}
return numstr;
} else if (tag === 'octstr') {
return buffer.raw();
} else if (tag === 'objDesc') {
return buffer.raw();
} else if (tag === 'printstr') {
var printstr = buffer.raw().toString('ascii');
if (!this._isPrintstr(printstr)) {
return buffer.error('Decoding of string type: ' +
'printstr unsupported characters');
}
return printstr;
} else if (/str$/.test(tag)) {
return buffer.raw().toString();
} else {
return buffer.error('Decoding of string type: ' + tag + ' unsupported');
}
};
DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {
var result;
var identifiers = [];
var ident = 0;
while (!buffer.isEmpty()) {
var subident = buffer.readUInt8();
ident <<= 7;
ident |= subident & 0x7f;
if ((subident & 0x80) === 0) {
identifiers.push(ident);
ident = 0;
}
}
if (subident & 0x80)
identifiers.push(ident);
var first = (identifiers[0] / 40) | 0;
var second = identifiers[0] % 40;
if (relative)
result = identifiers;
else
result = [first, second].concat(identifiers.slice(1));
if (values) {
var tmp = values[result.join(' ')];
if (tmp === undefined)
tmp = values[result.join('.')];
if (tmp !== undefined)
result = tmp;
}
return result;
};
DERNode.prototype._decodeTime = function decodeTime(buffer, tag) {
var str = buffer.raw().toString();
if (tag === 'gentime') {
var year = str.slice(0, 4) | 0;
var mon = str.slice(4, 6) | 0;
var day = str.slice(6, 8) | 0;
var hour = str.slice(8, 10) | 0;
var min = str.slice(10, 12) | 0;
var sec = str.slice(12, 14) | 0;
} else if (tag === 'utctime') {
var year = str.slice(0, 2) | 0;
var mon = str.slice(2, 4) | 0;
var day = str.slice(4, 6) | 0;
var hour = str.slice(6, 8) | 0;
var min = str.slice(8, 10) | 0;
var sec = str.slice(10, 12) | 0;
if (year < 70)
year = 2000 + year;
else
year = 1900 + year;
} else {
return buffer.error('Decoding ' + tag + ' time is not supported yet');
}
return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
};
DERNode.prototype._decodeNull = function decodeNull(buffer) {
return null;
};
DERNode.prototype._decodeBool = function decodeBool(buffer) {
var res = buffer.readUInt8();
if (buffer.isError(res))
return res;
else
return res !== 0;
};
DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
// Bigint, return as it is (assume big endian)
var raw = buffer.raw();
var res = new bignum(raw);
if (values)
res = values[res.toString(10)] || res;
return res;
};
DERNode.prototype._use = function use(entity, obj) {
if (typeof entity === 'function')
entity = entity(obj);
return entity._getDecoder('der').tree;
};
// Utility methods
function derDecodeTag(buf, fail) {
var tag = buf.readUInt8(fail);
if (buf.isError(tag))
return tag;
var cls = der.tagClass[tag >> 6];
var primitive = (tag & 0x20) === 0;
// Multi-octet tag - load
if ((tag & 0x1f) === 0x1f) {
var oct = tag;
tag = 0;
while ((oct & 0x80) === 0x80) {
oct = buf.readUInt8(fail);
if (buf.isError(oct))
return oct;
tag <<= 7;
tag |= oct & 0x7f;
}
} else {
tag &= 0x1f;
}
var tagStr = der.tag[tag];
return {
cls: cls,
primitive: primitive,
tag: tag,
tagStr: tagStr
};
}
function derDecodeLen(buf, primitive, fail) {
var len = buf.readUInt8(fail);
if (buf.isError(len))
return len;
// Indefinite form
if (!primitive && len === 0x80)
return null;
// Definite form
if ((len & 0x80) === 0) {
// Short form
return len;
}
// Long form
var num = len & 0x7f;
if (num > 4)
return buf.error('length octect is too long');
len = 0;
for (var i = 0; i < num; i++) {
len <<= 8;
var j = buf.readUInt8(fail);
if (buf.isError(j))
return j;
len |= j;
}
return len;
}
},{"../../asn1":95,"inherits":287}],104:[function(require,module,exports){
var decoders = exports;
decoders.der = require('./der');
decoders.pem = require('./pem');
},{"./der":103,"./pem":105}],105:[function(require,module,exports){
var inherits = require('inherits');
var Buffer = require('buffer').Buffer;
var DERDecoder = require('./der');
function PEMDecoder(entity) {
DERDecoder.call(this, entity);
this.enc = 'pem';
};
inherits(PEMDecoder, DERDecoder);
module.exports = PEMDecoder;
PEMDecoder.prototype.decode = function decode(data, options) {
var lines = data.toString().split(/[\r\n]+/g);
var label = options.label.toUpperCase();
var re = /^-----(BEGIN|END) ([^-]+)-----$/;
var start = -1;
var end = -1;
for (var i = 0; i < lines.length; i++) {
var match = lines[i].match(re);
if (match === null)
continue;
if (match[2] !== label)
continue;
if (start === -1) {
if (match[1] !== 'BEGIN')
break;
start = i;
} else {
if (match[1] !== 'END')
break;
end = i;
break;
}
}
if (start === -1 || end === -1)
throw new Error('PEM section not found for: ' + label);
var base64 = lines.slice(start + 1, end).join('');
// Remove excessive symbols
base64.replace(/[^a-z0-9\+\/=]+/gi, '');
var input = new Buffer(base64, 'base64');
return DERDecoder.prototype.decode.call(this, input, options);
};
},{"./der":103,"buffer":157,"inherits":287}],106:[function(require,module,exports){
var inherits = require('inherits');
var Buffer = require('buffer').Buffer;
var asn1 = require('../../asn1');
var base = asn1.base;
// Import DER constants
var der = asn1.constants.der;
function DEREncoder(entity) {
this.enc = 'der';
this.name = entity.name;
this.entity = entity;
// Construct base tree
this.tree = new DERNode();
this.tree._init(entity.body);
};
module.exports = DEREncoder;
DEREncoder.prototype.encode = function encode(data, reporter) {
return this.tree._encode(data, reporter).join();
};
// Tree methods
function DERNode(parent) {
base.Node.call(this, 'der', parent);
}
inherits(DERNode, base.Node);
DERNode.prototype._encodeComposite = function encodeComposite(tag,
primitive,
cls,
content) {
var encodedTag = encodeTag(tag, primitive, cls, this.reporter);
// Short form
if (content.length < 0x80) {
var header = new Buffer(2);
header[0] = encodedTag;
header[1] = content.length;
return this._createEncoderBuffer([ header, content ]);
}
// Long form
// Count octets required to store length
var lenOctets = 1;
for (var i = content.length; i >= 0x100; i >>= 8)
lenOctets++;
var header = new Buffer(1 + 1 + lenOctets);
header[0] = encodedTag;
header[1] = 0x80 | lenOctets;
for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)
header[i] = j & 0xff;
return this._createEncoderBuffer([ header, content ]);
};
DERNode.prototype._encodeStr = function encodeStr(str, tag) {
if (tag === 'bitstr') {
return this._createEncoderBuffer([ str.unused | 0, str.data ]);
} else if (tag === 'bmpstr') {
var buf = new Buffer(str.length * 2);
for (var i = 0; i < str.length; i++) {
buf.writeUInt16BE(str.charCodeAt(i), i * 2);
}
return this._createEncoderBuffer(buf);
} else if (tag === 'numstr') {
if (!this._isNumstr(str)) {
return this.reporter.error('Encoding of string type: numstr supports ' +
'only digits and space');
}
return this._createEncoderBuffer(str);
} else if (tag === 'printstr') {
if (!this._isPrintstr(str)) {
return this.reporter.error('Encoding of string type: printstr supports ' +
'only latin upper and lower case letters, ' +
'digits, space, apostrophe, left and rigth ' +
'parenthesis, plus sign, comma, hyphen, ' +
'dot, slash, colon, equal sign, ' +
'question mark');
}
return this._createEncoderBuffer(str);
} else if (/str$/.test(tag)) {
return this._createEncoderBuffer(str);
} else if (tag === 'objDesc') {
return this._createEncoderBuffer(str);
} else {
return this.reporter.error('Encoding of string type: ' + tag +
' unsupported');
}
};
DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
if (typeof id === 'string') {
if (!values)
return this.reporter.error('string objid given, but no values map found');
if (!values.hasOwnProperty(id))
return this.reporter.error('objid not found in values map');
id = values[id].split(/[\s\.]+/g);
for (var i = 0; i < id.length; i++)
id[i] |= 0;
} else if (Array.isArray(id)) {
id = id.slice();
for (var i = 0; i < id.length; i++)
id[i] |= 0;
}
if (!Array.isArray(id)) {
return this.reporter.error('objid() should be either array or string, ' +
'got: ' + JSON.stringify(id));
}
if (!relative) {
if (id[1] >= 40)
return this.reporter.error('Second objid identifier OOB');
id.splice(0, 2, id[0] * 40 + id[1]);
}
// Count number of octets
var size = 0;
for (var i = 0; i < id.length; i++) {
var ident = id[i];
for (size++; ident >= 0x80; ident >>= 7)
size++;
}
var objid = new Buffer(size);
var offset = objid.length - 1;
for (var i = id.length - 1; i >= 0; i--) {
var ident = id[i];
objid[offset--] = ident & 0x7f;
while ((ident >>= 7) > 0)
objid[offset--] = 0x80 | (ident & 0x7f);
}
return this._createEncoderBuffer(objid);
};
function two(num) {
if (num < 10)
return '0' + num;
else
return num;
}
DERNode.prototype._encodeTime = function encodeTime(time, tag) {
var str;
var date = new Date(time);
if (tag === 'gentime') {
str = [
two(date.getFullYear()),
two(date.getUTCMonth() + 1),
two(date.getUTCDate()),
two(date.getUTCHours()),
two(date.getUTCMinutes()),
two(date.getUTCSeconds()),
'Z'
].join('');
} else if (tag === 'utctime') {
str = [
two(date.getFullYear() % 100),
two(date.getUTCMonth() + 1),
two(date.getUTCDate()),
two(date.getUTCHours()),
two(date.getUTCMinutes()),
two(date.getUTCSeconds()),
'Z'
].join('');
} else {
this.reporter.error('Encoding ' + tag + ' time is not supported yet');
}
return this._encodeStr(str, 'octstr');
};
DERNode.prototype._encodeNull = function encodeNull() {
return this._createEncoderBuffer('');
};
DERNode.prototype._encodeInt = function encodeInt(num, values) {
if (typeof num === 'string') {
if (!values)
return this.reporter.error('String int or enum given, but no values map');
if (!values.hasOwnProperty(num)) {
return this.reporter.error('Values map doesn\'t contain: ' +
JSON.stringify(num));
}
num = values[num];
}
// Bignum, assume big endian
if (typeof num !== 'number' && !Buffer.isBuffer(num)) {
var numArray = num.toArray();
if (!num.sign && numArray[0] & 0x80) {
numArray.unshift(0);
}
num = new Buffer(numArray);
}
if (Buffer.isBuffer(num)) {
var size = num.length;
if (num.length === 0)
size++;
var out = new Buffer(size);
num.copy(out);
if (num.length === 0)
out[0] = 0
return this._createEncoderBuffer(out);
}
if (num < 0x80)
return this._createEncoderBuffer(num);
if (num < 0x100)
return this._createEncoderBuffer([0, num]);
var size = 1;
for (var i = num; i >= 0x100; i >>= 8)
size++;
var out = new Array(size);
for (var i = out.length - 1; i >= 0; i--) {
out[i] = num & 0xff;
num >>= 8;
}
if(out[0] & 0x80) {
out.unshift(0);
}
return this._createEncoderBuffer(new Buffer(out));
};
DERNode.prototype._encodeBool = function encodeBool(value) {
return this._createEncoderBuffer(value ? 0xff : 0);
};
DERNode.prototype._use = function use(entity, obj) {
if (typeof entity === 'function')
entity = entity(obj);
return entity._getEncoder('der').tree;
};
DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {
var state = this._baseState;
var i;
if (state['default'] === null)
return false;
var data = dataBuffer.join();
if (state.defaultBuffer === undefined)
state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();
if (data.length !== state.defaultBuffer.length)
return false;
for (i=0; i < data.length; i++)
if (data[i] !== state.defaultBuffer[i])
return false;
return true;
};
// Utility methods
function encodeTag(tag, primitive, cls, reporter) {
var res;
if (tag === 'seqof')
tag = 'seq';
else if (tag === 'setof')
tag = 'set';
if (der.tagByName.hasOwnProperty(tag))
res = der.tagByName[tag];
else if (typeof tag === 'number' && (tag | 0) === tag)
res = tag;
else
return reporter.error('Unknown tag: ' + tag);
if (res >= 0x1f)
return reporter.error('Multi-octet tag encoding unsupported');
if (!primitive)
res |= 0x20;
res |= (der.tagClassByName[cls || 'universal'] << 6);
return res;
}
},{"../../asn1":95,"buffer":157,"inherits":287}],107:[function(require,module,exports){
var encoders = exports;
encoders.der = require('./der');
encoders.pem = require('./pem');
},{"./der":106,"./pem":108}],108:[function(require,module,exports){
var inherits = require('inherits');
var DEREncoder = require('./der');
function PEMEncoder(entity) {
DEREncoder.call(this, entity);
this.enc = 'pem';
};
inherits(PEMEncoder, DEREncoder);
module.exports = PEMEncoder;
PEMEncoder.prototype.encode = function encode(data, options) {
var buf = DEREncoder.prototype.encode.call(this, data);
var p = buf.toString('base64');
var out = [ '-----BEGIN ' + options.label + '-----' ];
for (var i = 0; i < p.length; i += 64)
out.push(p.slice(i, i + 64));
out.push('-----END ' + options.label + '-----');
return out.join('\n');
};
},{"./der":106,"inherits":287}],109:[function(require,module,exports){
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
module.exports = {
newInvalidAsn1Error: function(msg) {
var e = new Error();
e.name = 'InvalidAsn1Error';
e.message = msg || '';
return e;
}
};
},{}],110:[function(require,module,exports){
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
var errors = require('./errors');
var types = require('./types');
var Reader = require('./reader');
var Writer = require('./writer');
///--- Exports
module.exports = {
Reader: Reader,
Writer: Writer
};
for (var t in types) {
if (types.hasOwnProperty(t))
module.exports[t] = types[t];
}
for (var e in errors) {
if (errors.hasOwnProperty(e))
module.exports[e] = errors[e];
}
},{"./errors":109,"./reader":111,"./types":112,"./writer":113}],111:[function(require,module,exports){
(function (Buffer){
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
var assert = require('assert');
var ASN1 = require('./types');
var errors = require('./errors');
///--- Globals
var newInvalidAsn1Error = errors.newInvalidAsn1Error;
///--- API
function Reader(data) {
if (!data || !Buffer.isBuffer(data))
throw new TypeError('data must be a node Buffer');
this._buf = data;
this._size = data.length;
// These hold the "current" state
this._len = 0;
this._offset = 0;
}
Object.defineProperty(Reader.prototype, 'length', {
enumerable: true,
get: function () { return (this._len); }
});
Object.defineProperty(Reader.prototype, 'offset', {
enumerable: true,
get: function () { return (this._offset); }
});
Object.defineProperty(Reader.prototype, 'remain', {
get: function () { return (this._size - this._offset); }
});
Object.defineProperty(Reader.prototype, 'buffer', {
get: function () { return (this._buf.slice(this._offset)); }
});
/**
* Reads a single byte and advances offset; you can pass in `true` to make this
* a "peek" operation (i.e., get the byte, but don't advance the offset).
*
* @param {Boolean} peek true means don't move offset.
* @return {Number} the next byte, null if not enough data.
*/
Reader.prototype.readByte = function(peek) {
if (this._size - this._offset < 1)
return null;
var b = this._buf[this._offset] & 0xff;
if (!peek)
this._offset += 1;
return b;
};
Reader.prototype.peek = function() {
return this.readByte(true);
};
/**
* Reads a (potentially) variable length off the BER buffer. This call is
* not really meant to be called directly, as callers have to manipulate
* the internal buffer afterwards.
*
* As a result of this call, you can call `Reader.length`, until the
* next thing called that does a readLength.
*
* @return {Number} the amount of offset to advance the buffer.
* @throws {InvalidAsn1Error} on bad ASN.1
*/
Reader.prototype.readLength = function(offset) {
if (offset === undefined)
offset = this._offset;
if (offset >= this._size)
return null;
var lenB = this._buf[offset++] & 0xff;
if (lenB === null)
return null;
if ((lenB & 0x80) == 0x80) {
lenB &= 0x7f;
if (lenB == 0)
throw newInvalidAsn1Error('Indefinite length not supported');
if (lenB > 4)
throw newInvalidAsn1Error('encoding too long');
if (this._size - offset < lenB)
return null;
this._len = 0;
for (var i = 0; i < lenB; i++)
this._len = (this._len << 8) + (this._buf[offset++] & 0xff);
} else {
// Wasn't a variable length
this._len = lenB;
}
return offset;
};
/**
* Parses the next sequence in this BER buffer.
*
* To get the length of the sequence, call `Reader.length`.
*
* @return {Number} the sequence's tag.
*/
Reader.prototype.readSequence = function(tag) {
var seq = this.peek();
if (seq === null)
return null;
if (tag !== undefined && tag !== seq)
throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
': got 0x' + seq.toString(16));
var o = this.readLength(this._offset + 1); // stored in `length`
if (o === null)
return null;
this._offset = o;
return seq;
};
Reader.prototype.readInt = function() {
return this._readTag(ASN1.Integer);
};
Reader.prototype.readBoolean = function() {
return (this._readTag(ASN1.Boolean) === 0 ? false : true);
};
Reader.prototype.readEnumeration = function() {
return this._readTag(ASN1.Enumeration);
};
Reader.prototype.readString = function(tag, retbuf) {
if (!tag)
tag = ASN1.OctetString;
var b = this.peek();
if (b === null)
return null;
if (b !== tag)
throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
': got 0x' + b.toString(16));
var o = this.readLength(this._offset + 1); // stored in `length`
if (o === null)
return null;
if (this.length > this._size - o)
return null;
this._offset = o;
if (this.length === 0)
return retbuf ? new Buffer(0) : '';
var str = this._buf.slice(this._offset, this._offset + this.length);
this._offset += this.length;
return retbuf ? str : str.toString('utf8');
};
Reader.prototype.readOID = function(tag) {
if (!tag)
tag = ASN1.OID;
var b = this.readString(tag, true);
if (b === null)
return null;
var values = [];
var value = 0;
for (var i = 0; i < b.length; i++) {
var byte = b[i] & 0xff;
value <<= 7;
value += byte & 0x7f;
if ((byte & 0x80) == 0) {
values.push(value);
value = 0;
}
}
value = values.shift();
values.unshift(value % 40);
values.unshift((value / 40) >> 0);
return values.join('.');
};
Reader.prototype._readTag = function(tag) {
assert.ok(tag !== undefined);
var b = this.peek();
if (b === null)
return null;
if (b !== tag)
throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
': got 0x' + b.toString(16));
var o = this.readLength(this._offset + 1); // stored in `length`
if (o === null)
return null;
if (this.length > 4)
throw newInvalidAsn1Error('Integer too long: ' + this.length);
if (this.length > this._size - o)
return null;
this._offset = o;
var fb = this._buf[this._offset];
var value = 0;
for (var i = 0; i < this.length; i++) {
value <<= 8;
value |= (this._buf[this._offset++] & 0xff);
}
if ((fb & 0x80) == 0x80 && i !== 4)
value -= (1 << (i * 8));
return value >> 0;
};
///--- Exported API
module.exports = Reader;
}).call(this,require("buffer").Buffer)
},{"./errors":109,"./types":112,"assert":116,"buffer":157}],112:[function(require,module,exports){
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
module.exports = {
EOC: 0,
Boolean: 1,
Integer: 2,
BitString: 3,
OctetString: 4,
Null: 5,
OID: 6,
ObjectDescriptor: 7,
External: 8,
Real: 9, // float
Enumeration: 10,
PDV: 11,
Utf8String: 12,
RelativeOID: 13,
Sequence: 16,
Set: 17,
NumericString: 18,
PrintableString: 19,
T61String: 20,
VideotexString: 21,
IA5String: 22,
UTCTime: 23,
GeneralizedTime: 24,
GraphicString: 25,
VisibleString: 26,
GeneralString: 28,
UniversalString: 29,
CharacterString: 30,
BMPString: 31,
Constructor: 32,
Context: 128
};
},{}],113:[function(require,module,exports){
(function (Buffer){
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
var assert = require('assert');
var ASN1 = require('./types');
var errors = require('./errors');
///--- Globals
var newInvalidAsn1Error = errors.newInvalidAsn1Error;
var DEFAULT_OPTS = {
size: 1024,
growthFactor: 8
};
///--- Helpers
function merge(from, to) {
assert.ok(from);
assert.equal(typeof(from), 'object');
assert.ok(to);
assert.equal(typeof(to), 'object');
var keys = Object.getOwnPropertyNames(from);
keys.forEach(function(key) {
if (to[key])
return;
var value = Object.getOwnPropertyDescriptor(from, key);
Object.defineProperty(to, key, value);
});
return to;
}
///--- API
function Writer(options) {
options = merge(DEFAULT_OPTS, options || {});
this._buf = new Buffer(options.size || 1024);
this._size = this._buf.length;
this._offset = 0;
this._options = options;
// A list of offsets in the buffer where we need to insert
// sequence tag/len pairs.
this._seq = [];
}
Object.defineProperty(Writer.prototype, 'buffer', {
get: function () {
if (this._seq.length)
throw new InvalidAsn1Error(this._seq.length + ' unended sequence(s)');
return (this._buf.slice(0, this._offset));
}
});
Writer.prototype.writeByte = function(b) {
if (typeof(b) !== 'number')
throw new TypeError('argument must be a Number');
this._ensure(1);
this._buf[this._offset++] = b;
};
Writer.prototype.writeInt = function(i, tag) {
if (typeof(i) !== 'number')
throw new TypeError('argument must be a Number');
if (typeof(tag) !== 'number')
tag = ASN1.Integer;
var sz = 4;
while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) &&
(sz > 1)) {
sz--;
i <<= 8;
}
if (sz > 4)
throw new InvalidAsn1Error('BER ints cannot be > 0xffffffff');
this._ensure(2 + sz);
this._buf[this._offset++] = tag;
this._buf[this._offset++] = sz;
while (sz-- > 0) {
this._buf[this._offset++] = ((i & 0xff000000) >>> 24);
i <<= 8;
}
};
Writer.prototype.writeNull = function() {
this.writeByte(ASN1.Null);
this.writeByte(0x00);
};
Writer.prototype.writeEnumeration = function(i, tag) {
if (typeof(i) !== 'number')
throw new TypeError('argument must be a Number');
if (typeof(tag) !== 'number')
tag = ASN1.Enumeration;
return this.writeInt(i, tag);
};
Writer.prototype.writeBoolean = function(b, tag) {
if (typeof(b) !== 'boolean')
throw new TypeError('argument must be a Boolean');
if (typeof(tag) !== 'number')
tag = ASN1.Boolean;
this._ensure(3);
this._buf[this._offset++] = tag;
this._buf[this._offset++] = 0x01;
this._buf[this._offset++] = b ? 0xff : 0x00;
};
Writer.prototype.writeString = function(s, tag) {
if (typeof(s) !== 'string')
throw new TypeError('argument must be a string (was: ' + typeof(s) + ')');
if (typeof(tag) !== 'number')
tag = ASN1.OctetString;
var len = Buffer.byteLength(s);
this.writeByte(tag);
this.writeLength(len);
if (len) {
this._ensure(len);
this._buf.write(s, this._offset);
this._offset += len;
}
};
Writer.prototype.writeBuffer = function(buf, tag) {
if (typeof(tag) !== 'number')
throw new TypeError('tag must be a number');
if (!Buffer.isBuffer(buf))
throw new TypeError('argument must be a buffer');
this.writeByte(tag);
this.writeLength(buf.length);
this._ensure(buf.length);
buf.copy(this._buf, this._offset, 0, buf.length);
this._offset += buf.length;
};
Writer.prototype.writeStringArray = function(strings) {
if ((!strings instanceof Array))
throw new TypeError('argument must be an Array[String]');
var self = this;
strings.forEach(function(s) {
self.writeString(s);
});
};
// This is really to solve DER cases, but whatever for now
Writer.prototype.writeOID = function(s, tag) {
if (typeof(s) !== 'string')
throw new TypeError('argument must be a string');
if (typeof(tag) !== 'number')
tag = ASN1.OID;
if (!/^([0-9]+\.){3,}[0-9]+$/.test(s))
throw new Error('argument is not a valid OID string');
function encodeOctet(bytes, octet) {
if (octet < 128) {
bytes.push(octet);
} else if (octet < 16384) {
bytes.push((octet >>> 7) | 0x80);
bytes.push(octet & 0x7F);
} else if (octet < 2097152) {
bytes.push((octet >>> 14) | 0x80);
bytes.push(((octet >>> 7) | 0x80) & 0xFF);
bytes.push(octet & 0x7F);
} else if (octet < 268435456) {
bytes.push((octet >>> 21) | 0x80);
bytes.push(((octet >>> 14) | 0x80) & 0xFF);
bytes.push(((octet >>> 7) | 0x80) & 0xFF);
bytes.push(octet & 0x7F);
} else {
bytes.push(((octet >>> 28) | 0x80) & 0xFF);
bytes.push(((octet >>> 21) | 0x80) & 0xFF);
bytes.push(((octet >>> 14) | 0x80) & 0xFF);
bytes.push(((octet >>> 7) | 0x80) & 0xFF);
bytes.push(octet & 0x7F);
}
}
var tmp = s.split('.');
var bytes = [];
bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));
tmp.slice(2).forEach(function(b) {
encodeOctet(bytes, parseInt(b, 10));
});
var self = this;
this._ensure(2 + bytes.length);
this.writeByte(tag);
this.writeLength(bytes.length);
bytes.forEach(function(b) {
self.writeByte(b);
});
};
Writer.prototype.writeLength = function(len) {
if (typeof(len) !== 'number')
throw new TypeError('argument must be a Number');
this._ensure(4);
if (len <= 0x7f) {
this._buf[this._offset++] = len;
} else if (len <= 0xff) {
this._buf[this._offset++] = 0x81;
this._buf[this._offset++] = len;
} else if (len <= 0xffff) {
this._buf[this._offset++] = 0x82;
this._buf[this._offset++] = len >> 8;
this._buf[this._offset++] = len;
} else if (len <= 0xffffff) {
this._buf[this._offset++] = 0x83;
this._buf[this._offset++] = len >> 16;
this._buf[this._offset++] = len >> 8;
this._buf[this._offset++] = len;
} else {
throw new InvalidAsn1ERror('Length too long (> 4 bytes)');
}
};
Writer.prototype.startSequence = function(tag) {
if (typeof(tag) !== 'number')
tag = ASN1.Sequence | ASN1.Constructor;
this.writeByte(tag);
this._seq.push(this._offset);
this._ensure(3);
this._offset += 3;
};
Writer.prototype.endSequence = function() {
var seq = this._seq.pop();
var start = seq + 3;
var len = this._offset - start;
if (len <= 0x7f) {
this._shift(start, len, -2);
this._buf[seq] = len;
} else if (len <= 0xff) {
this._shift(start, len, -1);
this._buf[seq] = 0x81;
this._buf[seq + 1] = len;
} else if (len <= 0xffff) {
this._buf[seq] = 0x82;
this._buf[seq + 1] = len >> 8;
this._buf[seq + 2] = len;
} else if (len <= 0xffffff) {
this._shift(start, len, 1);
this._buf[seq] = 0x83;
this._buf[seq + 1] = len >> 16;
this._buf[seq + 2] = len >> 8;
this._buf[seq + 3] = len;
} else {
throw new InvalidAsn1Error('Sequence too long');
}
};
Writer.prototype._shift = function(start, len, shift) {
assert.ok(start !== undefined);
assert.ok(len !== undefined);
assert.ok(shift);
this._buf.copy(this._buf, start + shift, start, start + len);
this._offset += shift;
};
Writer.prototype._ensure = function(len) {
assert.ok(len);
if (this._size - this._offset < len) {
var sz = this._size * this._options.growthFactor;
if (sz - this._offset < len)
sz += len;
var buf = new Buffer(sz);
this._buf.copy(buf, 0, 0, this._offset);
this._buf = buf;
this._size = sz;
}
};
///--- Exported API
module.exports = Writer;
}).call(this,require("buffer").Buffer)
},{"./errors":109,"./types":112,"assert":116,"buffer":157}],114:[function(require,module,exports){
// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
// If you have no idea what ASN.1 or BER is, see this:
// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc
var Ber = require('./ber/index');
///--- Exported API
module.exports = {
Ber: Ber,
BerReader: Ber.Reader,
BerWriter: Ber.Writer
};
},{"./ber/index":110}],115:[function(require,module,exports){
(function (Buffer,process){
// Copyright (c) 2012, Mark Cavage. All rights reserved.
// Copyright 2015 Joyent, Inc.
var assert = require('assert');
var Stream = require('stream').Stream;
var util = require('util');
///--- Globals
/* JSSTYLED */
var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;
///--- Internal
function _capitalize(str) {
return (str.charAt(0).toUpperCase() + str.slice(1));
}
function _toss(name, expected, oper, arg, actual) {
throw new assert.AssertionError({
message: util.format('%s (%s) is required', name, expected),
actual: (actual === undefined) ? typeof (arg) : actual(arg),
expected: expected,
operator: oper || '===',
stackStartFunction: _toss.caller
});
}
function _getClass(arg) {
return (Object.prototype.toString.call(arg).slice(8, -1));
}
function noop() {
// Why even bother with asserts?
}
///--- Exports
var types = {
bool: {
check: function (arg) { return typeof (arg) === 'boolean'; }
},
func: {
check: function (arg) { return typeof (arg) === 'function'; }
},
string: {
check: function (arg) { return typeof (arg) === 'string'; }
},
object: {
check: function (arg) {
return typeof (arg) === 'object' && arg !== null;
}
},
number: {
check: function (arg) {
return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg);
}
},
buffer: {
check: function (arg) { return Buffer.isBuffer(arg); },
operator: 'Buffer.isBuffer'
},
array: {
check: function (arg) { return Array.isArray(arg); },
operator: 'Array.isArray'
},
stream: {
check: function (arg) { return arg instanceof Stream; },
operator: 'instanceof',
actual: _getClass
},
date: {
check: function (arg) { return arg instanceof Date; },
operator: 'instanceof',
actual: _getClass
},
regexp: {
check: function (arg) { return arg instanceof RegExp; },
operator: 'instanceof',
actual: _getClass
},
uuid: {
check: function (arg) {
return typeof (arg) === 'string' && UUID_REGEXP.test(arg);
},
operator: 'isUUID'
}
};
function _setExports(ndebug) {
var keys = Object.keys(types);
var out;
/* re-export standard assert */
if (process.env.NODE_NDEBUG) {
out = noop;
} else {
out = function (arg, msg) {
if (!arg) {
_toss(msg, 'true', arg);
}
};
}
/* standard checks */
keys.forEach(function (k) {
if (ndebug) {
out[k] = noop;
return;
}
var type = types[k];
out[k] = function (arg, msg) {
if (!type.check(arg)) {
_toss(msg, k, type.operator, arg, type.actual);
}
};
});
/* optional checks */
keys.forEach(function (k) {
var name = 'optional' + _capitalize(k);
if (ndebug) {
out[name] = noop;
return;
}
var type = types[k];
out[name] = function (arg, msg) {
if (arg === undefined || arg === null) {
return;
}
if (!type.check(arg)) {
_toss(msg, k, type.operator, arg, type.actual);
}
};
});
/* arrayOf checks */
keys.forEach(function (k) {
var name = 'arrayOf' + _capitalize(k);
if (ndebug) {
out[name] = noop;
return;
}
var type = types[k];
var expected = '[' + k + ']';
out[name] = function (arg, msg) {
if (!Array.isArray(arg)) {
_toss(msg, expected, type.operator, arg, type.actual);
}
var i;
for (i = 0; i < arg.length; i++) {
if (!type.check(arg[i])) {
_toss(msg, expected, type.operator, arg, type.actual);
}
}
};
});
/* optionalArrayOf checks */
keys.forEach(function (k) {
var name = 'optionalArrayOf' + _capitalize(k);
if (ndebug) {
out[name] = noop;
return;
}
var type = types[k];
var expected = '[' + k + ']';
out[name] = function (arg, msg) {
if (arg === undefined || arg === null) {
return;
}
if (!Array.isArray(arg)) {
_toss(msg, expected, type.operator, arg, type.actual);
}
var i;
for (i = 0; i < arg.length; i++) {
if (!type.check(arg[i])) {
_toss(msg, expected, type.operator, arg, type.actual);
}
}
};
});
/* re-export built-in assertions */
Object.keys(assert).forEach(function (k) {
if (k === 'AssertionError') {
out[k] = assert[k];
return;
}
if (ndebug) {
out[k] = noop;
return;
}
out[k] = assert[k];
});
/* export ourselves (for unit tests _only_) */
out._setExports = _setExports;
return out;
}
module.exports = _setExports(process.env.NODE_NDEBUG);
}).call(this,{"isBuffer":require("../is-buffer/index.js")},require('_process'))
},{"../is-buffer/index.js":288,"_process":336,"assert":116,"stream":467,"util":491}],116:[function(require,module,exports){
(function (global){
'use strict';
// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
// original notice:
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
function compare(a, b) {
if (a === b) {
return 0;
}
var x = a.length;
var y = b.length;
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break;
}
}
if (x < y) {
return -1;
}
if (y < x) {
return 1;
}
return 0;
}
function isBuffer(b) {
if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
return global.Buffer.isBuffer(b);
}
return !!(b != null && b._isBuffer);
}
// based on node assert, original notice:
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
var util = require('util/');
var hasOwn = Object.prototype.hasOwnProperty;
var pSlice = Array.prototype.slice;
var functionsHaveNames = (function () {
return function foo() {}.name === 'foo';
}());
function pToString (obj) {
return Object.prototype.toString.call(obj);
}
function isView(arrbuf) {
if (isBuffer(arrbuf)) {
return false;
}
if (typeof global.ArrayBuffer !== 'function') {
return false;
}
if (typeof ArrayBuffer.isView === 'function') {
return ArrayBuffer.isView(arrbuf);
}
if (!arrbuf) {
return false;
}
if (arrbuf instanceof DataView) {
return true;
}
if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
return true;
}
return false;
}
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
// actual: actual,
// expected: expected })
var regex = /\s*function\s+([^\(\s]*)\s*/;
// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
function getName(func) {
if (!util.isFunction(func)) {
return;
}
if (functionsHaveNames) {
return func.name;
}
var str = func.toString();
var match = str.match(regex);
return match && match[1];
}
assert.AssertionError = function AssertionError(options) {
this.name = 'AssertionError';
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
if (options.message) {
this.message = options.message;
this.generatedMessage = false;
} else {
this.message = getMessage(this);
this.generatedMessage = true;
}
var stackStartFunction = options.stackStartFunction || fail;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, stackStartFunction);
} else {
// non v8 browsers so we can have a stacktrace
var err = new Error();
if (err.stack) {
var out = err.stack;
// try to strip useless frames
var fn_name = getName(stackStartFunction);
var idx = out.indexOf('\n' + fn_name);
if (idx >= 0) {
// once we have located the function frame
// we need to strip out everything before it (and its line)
var next_line = out.indexOf('\n', idx + 1);
out = out.substring(next_line + 1);
}
this.stack = out;
}
}
};
// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);
function truncate(s, n) {
if (typeof s === 'string') {
return s.length < n ? s : s.slice(0, n);
} else {
return s;
}
}
function inspect(something) {
if (functionsHaveNames || !util.isFunction(something)) {
return util.inspect(something);
}
var rawname = getName(something);
var name = rawname ? ': ' + rawname : '';
return '[Function' + name + ']';
}
function getMessage(self) {
return truncate(inspect(self.actual), 128) + ' ' +
self.operator + ' ' +
truncate(inspect(self.expected), 128);
}
// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.
// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;
// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.
function ok(value, message) {
if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);
assert.equal = function equal(actual, expected, message) {
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};
// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);
assert.notEqual = function notEqual(actual, expected, message) {
if (actual == expected) {
fail(actual, expected, message, '!=', assert.notEqual);
}
};
// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);
assert.deepEqual = function deepEqual(actual, expected, message) {
if (!_deepEqual(actual, expected, false)) {
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
};
assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
if (!_deepEqual(actual, expected, true)) {
fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
}
};
function _deepEqual(actual, expected, strict, memos) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (isBuffer(actual) && isBuffer(expected)) {
return compare(actual, expected) === 0;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (util.isDate(actual) && util.isDate(expected)) {
return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (util.isRegExp(actual) && util.isRegExp(expected)) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
// 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if ((actual === null || typeof actual !== 'object') &&
(expected === null || typeof expected !== 'object')) {
return strict ? actual === expected : actual == expected;
// If both values are instances of typed arrays, wrap their underlying
// ArrayBuffers in a Buffer each to increase performance
// This optimization requires the arrays to have the same type as checked by
// Object.prototype.toString (aka pToString). Never perform binary
// comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
// bit patterns are not identical.
} else if (isView(actual) && isView(expected) &&
pToString(actual) === pToString(expected) &&
!(actual instanceof Float32Array ||
actual instanceof Float64Array)) {
return compare(new Uint8Array(actual.buffer),
new Uint8Array(expected.buffer)) === 0;
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else if (isBuffer(actual) !== isBuffer(expected)) {
return false;
} else {
memos = memos || {actual: [], expected: []};
var actualIndex = memos.actual.indexOf(actual);
if (actualIndex !== -1) {
if (actualIndex === memos.expected.indexOf(expected)) {
return true;
}
}
memos.actual.push(actual);
memos.expected.push(expected);
return objEquiv(actual, expected, strict, memos);
}
}
function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function objEquiv(a, b, strict, actualVisitedObjects) {
if (a === null || a === undefined || b === null || b === undefined)
return false;
// if one is a primitive, the other must be same
if (util.isPrimitive(a) || util.isPrimitive(b))
return a === b;
if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
return false;
var aIsArgs = isArguments(a);
var bIsArgs = isArguments(b);
if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
return false;
if (aIsArgs) {
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b, strict);
}
var ka = objectKeys(a);
var kb = objectKeys(b);
var key, i;
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length !== kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] !== kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
return false;
}
return true;
}
// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (_deepEqual(actual, expected, false)) {
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
}
};
assert.notDeepStrictEqual = notDeepStrictEqual;
function notDeepStrictEqual(actual, expected, message) {
if (_deepEqual(actual, expected, true)) {
fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
}
}
// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);
assert.strictEqual = function strictEqual(actual, expected, message) {
if (actual !== expected) {
fail(actual, expected, message, '===', assert.strictEqual);
}
};
// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (actual === expected) {
fail(actual, expected, message, '!==', assert.notStrictEqual);
}
};
function expectedException(actual, expected) {
if (!actual || !expected) {
return false;
}
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
return expected.test(actual);
}
try {
if (actual instanceof expected) {
return true;
}
} catch (e) {
// Ignore. The instanceof check doesn't work for arrow functions.
}
if (Error.isPrototypeOf(expected)) {
return false;
}
return expected.call({}, actual) === true;
}
function _tryBlock(block) {
var error;
try {
block();
} catch (e) {
error = e;
}
return error;
}
function _throws(shouldThrow, block, expected, message) {
var actual;
if (typeof block !== 'function') {
throw new TypeError('"block" argument must be a function');
}
if (typeof expected === 'string') {
message = expected;
expected = null;
}
actual = _tryBlock(block);
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
(message ? ' ' + message : '.');
if (shouldThrow && !actual) {
fail(actual, expected, 'Missing expected exception' + message);
}
var userProvidedMessage = typeof message === 'string';
var isUnwantedException = !shouldThrow && util.isError(actual);
var isUnexpectedException = !shouldThrow && actual && !expected;
if ((isUnwantedException &&
userProvidedMessage &&
expectedException(actual, expected)) ||
isUnexpectedException) {
fail(actual, expected, 'Got unwanted exception' + message);
}
if ((shouldThrow && actual && expected &&
!expectedException(actual, expected)) || (!shouldThrow && actual)) {
throw actual;
}
}
// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);
assert.throws = function(block, /*optional*/error, /*optional*/message) {
_throws(true, block, error, message);
};
// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
_throws(false, block, error, message);
};
assert.ifError = function(err) { if (err) throw err; };
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
if (hasOwn.call(obj, key)) keys.push(key);
}
return keys;
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"util/":491}],117:[function(require,module,exports){
/*!
* Copyright 2010 LearnBoost <dev@learnboost.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Module dependencies.
*/
var crypto = require('crypto')
, parse = require('url').parse
;
/**
* Valid keys.
*/
var keys =
[ 'acl'
, 'location'
, 'logging'
, 'notification'
, 'partNumber'
, 'policy'
, 'requestPayment'
, 'torrent'
, 'uploadId'
, 'uploads'
, 'versionId'
, 'versioning'
, 'versions'
, 'website'
]
/**
* Return an "Authorization" header value with the given `options`
* in the form of "AWS <key>:<signature>"
*
* @param {Object} options
* @return {String}
* @api private
*/
function authorization (options) {
return 'AWS ' + options.key + ':' + sign(options)
}
module.exports = authorization
module.exports.authorization = authorization
/**
* Simple HMAC-SHA1 Wrapper
*
* @param {Object} options
* @return {String}
* @api private
*/
function hmacSha1 (options) {
return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64')
}
module.exports.hmacSha1 = hmacSha1
/**
* Create a base64 sha1 HMAC for `options`.
*
* @param {Object} options
* @return {String}
* @api private
*/
function sign (options) {
options.message = stringToSign(options)
return hmacSha1(options)
}
module.exports.sign = sign
/**
* Create a base64 sha1 HMAC for `options`.
*
* Specifically to be used with S3 presigned URLs
*
* @param {Object} options
* @return {String}
* @api private
*/
function signQuery (options) {
options.message = queryStringToSign(options)
return hmacSha1(options)
}
module.exports.signQuery= signQuery
/**
* Return a string for sign() with the given `options`.
*
* Spec:
*
* <verb>\n
* <md5>\n
* <content-type>\n
* <date>\n
* [headers\n]
* <resource>
*
* @param {Object} options
* @return {String}
* @api private
*/
function stringToSign (options) {
var headers = options.amazonHeaders || ''
if (headers) headers += '\n'
var r =
[ options.verb
, options.md5
, options.contentType
, options.date ? options.date.toUTCString() : ''
, headers + options.resource
]
return r.join('\n')
}
module.exports.queryStringToSign = stringToSign
/**
* Return a string for sign() with the given `options`, but is meant exclusively
* for S3 presigned URLs
*
* Spec:
*
* <date>\n
* <resource>
*
* @param {Object} options
* @return {String}
* @api private
*/
function queryStringToSign (options){
return 'GET\n\n\n' + options.date + '\n' + options.resource
}
module.exports.queryStringToSign = queryStringToSign
/**
* Perform the following:
*
* - ignore non-amazon headers
* - lowercase fields
* - sort lexicographically
* - trim whitespace between ":"
* - join with newline
*
* @param {Object} headers
* @return {String}
* @api private
*/
function canonicalizeHeaders (headers) {
var buf = []
, fields = Object.keys(headers)
;
for (var i = 0, len = fields.length; i < len; ++i) {
var field = fields[i]
, val = headers[field]
, field = field.toLowerCase()
;
if (0 !== field.indexOf('x-amz')) continue
buf.push(field + ':' + val)
}
return buf.sort().join('\n')
}
module.exports.canonicalizeHeaders = canonicalizeHeaders
/**
* Perform the following:
*
* - ignore non sub-resources
* - sort lexicographically
*
* @param {String} resource
* @return {String}
* @api private
*/
function canonicalizeResource (resource) {
var url = parse(resource, true)
, path = url.pathname
, buf = []
;
Object.keys(url.query).forEach(function(key){
if (!~keys.indexOf(key)) return
var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key])
buf.push(key + val)
})
return path + (buf.length ? '?' + buf.sort().join('&') : '')
}
module.exports.canonicalizeResource = canonicalizeResource
},{"crypto":170,"url":486}],118:[function(require,module,exports){
(function (process,Buffer){
var aws4 = exports,
url = require('url'),
querystring = require('querystring'),
crypto = require('crypto'),
lru = require('./lru'),
credentialsCache = lru(1000)
// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html
function hmac(key, string, encoding) {
return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding)
}
function hash(string, encoding) {
return crypto.createHash('sha256').update(string, 'utf8').digest(encoding)
}
// This function assumes the string has already been percent encoded
function encodeRfc3986(urlEncodedString) {
return urlEncodedString.replace(/[!'()*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
// request: { path | body, [host], [method], [headers], [service], [region] }
// credentials: { accessKeyId, secretAccessKey, [sessionToken] }
function RequestSigner(request, credentials) {
if (typeof request === 'string') request = url.parse(request)
var headers = request.headers = (request.headers || {}),
hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host)
this.request = request
this.credentials = credentials || this.defaultCredentials()
this.service = request.service || hostParts[0] || ''
this.region = request.region || hostParts[1] || 'us-east-1'
// SES uses a different domain from the service name
if (this.service === 'email') this.service = 'ses'
if (!request.method && request.body)
request.method = 'POST'
if (!headers.Host && !headers.host) {
headers.Host = request.hostname || request.host || this.createHost()
// If a port is specified explicitly, use it as is
if (request.port)
headers.Host += ':' + request.port
}
if (!request.hostname && !request.host)
request.hostname = headers.Host || headers.host
this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT'
}
RequestSigner.prototype.matchHost = function(host) {
var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com$/)
var hostParts = (match || []).slice(1, 3)
// ES's hostParts are sometimes the other way round, if the value that is expected
// to be region equals ‘es’ switch them back
// e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com
if (hostParts[1] === 'es')
hostParts = hostParts.reverse()
return hostParts
}
// http://docs.aws.amazon.com/general/latest/gr/rande.html
RequestSigner.prototype.isSingleRegion = function() {
// Special case for S3 and SimpleDB in us-east-1
if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true
return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']
.indexOf(this.service) >= 0
}
RequestSigner.prototype.createHost = function() {
var region = this.isSingleRegion() ? '' :
(this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region,
service = this.service === 'ses' ? 'email' : this.service
return service + region + '.amazonaws.com'
}
RequestSigner.prototype.prepareRequest = function() {
this.parsePath()
var request = this.request, headers = request.headers, query
if (request.signQuery) {
this.parsedPath.query = query = this.parsedPath.query || {}
if (this.credentials.sessionToken)
query['X-Amz-Security-Token'] = this.credentials.sessionToken
if (this.service === 's3' && !query['X-Amz-Expires'])
query['X-Amz-Expires'] = 86400
if (query['X-Amz-Date'])
this.datetime = query['X-Amz-Date']
else
query['X-Amz-Date'] = this.getDateTime()
query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'
query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()
query['X-Amz-SignedHeaders'] = this.signedHeaders()
} else {
if (!request.doNotModifyHeaders && !this.isCodeCommitGit) {
if (request.body && !headers['Content-Type'] && !headers['content-type'])
headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
if (request.body && !headers['Content-Length'] && !headers['content-length'])
headers['Content-Length'] = Buffer.byteLength(request.body)
if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token'])
headers['X-Amz-Security-Token'] = this.credentials.sessionToken
if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256'])
headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')
if (headers['X-Amz-Date'] || headers['x-amz-date'])
this.datetime = headers['X-Amz-Date'] || headers['x-amz-date']
else
headers['X-Amz-Date'] = this.getDateTime()
}
delete headers.Authorization
delete headers.authorization
}
}
RequestSigner.prototype.sign = function() {
if (!this.parsedPath) this.prepareRequest()
if (this.request.signQuery) {
this.parsedPath.query['X-Amz-Signature'] = this.signature()
} else {
this.request.headers.Authorization = this.authHeader()
}
this.request.path = this.formatPath()
return this.request
}
RequestSigner.prototype.getDateTime = function() {
if (!this.datetime) {
var headers = this.request.headers,
date = new Date(headers.Date || headers.date || new Date)
this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '')
// Remove the trailing 'Z' on the timestamp string for CodeCommit git access
if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1)
}
return this.datetime
}
RequestSigner.prototype.getDate = function() {
return this.getDateTime().substr(0, 8)
}
RequestSigner.prototype.authHeader = function() {
return [
'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),
'SignedHeaders=' + this.signedHeaders(),
'Signature=' + this.signature(),
].join(', ')
}
RequestSigner.prototype.signature = function() {
var date = this.getDate(),
cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),
kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)
if (!kCredentials) {
kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)
kRegion = hmac(kDate, this.region)
kService = hmac(kRegion, this.service)
kCredentials = hmac(kService, 'aws4_request')
credentialsCache.set(cacheKey, kCredentials)
}
return hmac(kCredentials, this.stringToSign(), 'hex')
}
RequestSigner.prototype.stringToSign = function() {
return [
'AWS4-HMAC-SHA256',
this.getDateTime(),
this.credentialString(),
hash(this.canonicalString(), 'hex'),
].join('\n')
}
RequestSigner.prototype.canonicalString = function() {
if (!this.parsedPath) this.prepareRequest()
var pathStr = this.parsedPath.path,
query = this.parsedPath.query,
headers = this.request.headers,
queryStr = '',
normalizePath = this.service !== 's3',
decodePath = this.service === 's3' || this.request.doNotEncodePath,
decodeSlashesInPath = this.service === 's3',
firstValOnly = this.service === 's3',
bodyHash
if (this.service === 's3' && this.request.signQuery) {
bodyHash = 'UNSIGNED-PAYLOAD'
} else if (this.isCodeCommitGit) {
bodyHash = ''
} else {
bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] ||
hash(this.request.body || '', 'hex')
}
if (query) {
queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) {
if (!key) return obj
obj[key] = !Array.isArray(query[key]) ? query[key] :
(firstValOnly ? query[key][0] : query[key].slice().sort())
return obj
}, {})))
}
if (pathStr !== '/') {
if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/')
pathStr = pathStr.split('/').reduce(function(path, piece) {
if (normalizePath && piece === '..') {
path.pop()
} else if (!normalizePath || piece !== '.') {
if (decodePath) piece = querystring.unescape(piece)
path.push(encodeRfc3986(querystring.escape(piece)))
}
return path
}, []).join('/')
if (pathStr[0] !== '/') pathStr = '/' + pathStr
if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/')
}
return [
this.request.method || 'GET',
pathStr,
queryStr,
this.canonicalHeaders() + '\n',
this.signedHeaders(),
bodyHash,
].join('\n')
}
RequestSigner.prototype.canonicalHeaders = function() {
var headers = this.request.headers
function trimAll(header) {
return header.toString().trim().replace(/\s+/g, ' ')
}
return Object.keys(headers)
.sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })
.map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })
.join('\n')
}
RequestSigner.prototype.signedHeaders = function() {
return Object.keys(this.request.headers)
.map(function(key) { return key.toLowerCase() })
.sort()
.join(';')
}
RequestSigner.prototype.credentialString = function() {
return [
this.getDate(),
this.region,
this.service,
'aws4_request',
].join('/')
}
RequestSigner.prototype.defaultCredentials = function() {
var env = process.env
return {
accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
sessionToken: env.AWS_SESSION_TOKEN,
}
}
RequestSigner.prototype.parsePath = function() {
var path = this.request.path || '/',
queryIx = path.indexOf('?'),
query = null
if (queryIx >= 0) {
query = querystring.parse(path.slice(queryIx + 1))
path = path.slice(0, queryIx)
}
// S3 doesn't always encode characters > 127 correctly and
// all services don't encode characters > 255 correctly
// So if there are non-reserved chars (and it's not already all % encoded), just encode them all
if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) {
path = path.split('/').map(function(piece) {
return querystring.escape(querystring.unescape(piece))
}).join('/')
}
this.parsedPath = {
path: path,
query: query,
}
}
RequestSigner.prototype.formatPath = function() {
var path = this.parsedPath.path,
query = this.parsedPath.query
if (!query) return path
// Services don't support empty query string keys
if (query[''] != null) delete query['']
return path + '?' + encodeRfc3986(querystring.stringify(query))
}
aws4.RequestSigner = RequestSigner
aws4.sign = function(request, credentials) {
return new RequestSigner(request, credentials).sign()
}
}).call(this,require('_process'),require("buffer").Buffer)
},{"./lru":119,"_process":336,"buffer":157,"crypto":170,"querystring":351,"url":486}],119:[function(require,module,exports){
module.exports = function(size) {
return new LruCache(size)
}
function LruCache(size) {
this.capacity = size | 0
this.map = Object.create(null)
this.list = new DoublyLinkedList()
}
LruCache.prototype.get = function(key) {
var node = this.map[key]
if (node == null) return undefined
this.used(node)
return node.val
}
LruCache.prototype.set = function(key, val) {
var node = this.map[key]
if (node != null) {
node.val = val
} else {
if (!this.capacity) this.prune()
if (!this.capacity) return false
node = new DoublyLinkedNode(key, val)
this.map[key] = node
this.capacity--
}
this.used(node)
return true
}
LruCache.prototype.used = function(node) {
this.list.moveToFront(node)
}
LruCache.prototype.prune = function() {
var node = this.list.pop()
if (node != null) {
delete this.map[node.key]
this.capacity++
}
}
function DoublyLinkedList() {
this.firstNode = null
this.lastNode = null
}
DoublyLinkedList.prototype.moveToFront = function(node) {
if (this.firstNode == node) return
this.remove(node)
if (this.firstNode == null) {
this.firstNode = node
this.lastNode = node
node.prev = null
node.next = null
} else {
node.prev = null
node.next = this.firstNode
node.next.prev = node
this.firstNode = node
}
}
DoublyLinkedList.prototype.pop = function() {
var lastNode = this.lastNode
if (lastNode != null) {
this.remove(lastNode)
}
return lastNode
}
DoublyLinkedList.prototype.remove = function(node) {
if (this.firstNode == node) {
this.firstNode = node.next
} else if (node.prev != null) {
node.prev.next = node.next
}
if (this.lastNode == node) {
this.lastNode = node.prev
} else if (node.next != null) {
node.next.prev = node.prev
}
}
function DoublyLinkedNode(key, val) {
this.key = key
this.val = val
this.prev = null
this.next = null
}
},{}],120:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function placeHoldersCount (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
}
function byteLength (b64) {
// base64 is 4/3 + up to two characters of the original data
return (b64.length * 3 / 4) - placeHoldersCount(b64)
}
function toByteArray (b64) {
var i, l, tmp, placeHolders, arr
var len = b64.length
placeHolders = placeHoldersCount(b64)
arr = new Arr((len * 3 / 4) - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len
var L = 0
for (i = 0; i < l; i += 4) {
tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
arr[L++] = (tmp >> 16) & 0xFF
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
if (placeHolders === 2) {
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[L++] = tmp & 0xFF
} else if (placeHolders === 1) {
tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var output = ''
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
output += lookup[tmp >> 2]
output += lookup[(tmp << 4) & 0x3F]
output += '=='
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
output += lookup[tmp >> 10]
output += lookup[(tmp >> 4) & 0x3F]
output += lookup[(tmp << 2) & 0x3F]
output += '='
}
parts.push(output)
return parts.join('')
}
},{}],121:[function(require,module,exports){
'use strict';
var crypto_hash_sha512 = require('tweetnacl').lowlevel.crypto_hash;
/*
* This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a
* result, it retains the original copyright and license. The two files are
* under slightly different (but compatible) licenses, and are here combined in
* one file.
*
* Credit for the actual porting work goes to:
* Devi Mandiri <me@devi.web.id>
*/
/*
* The Blowfish portions are under the following license:
*
* Blowfish block cipher for OpenBSD
* Copyright 1997 Niels Provos <provos@physnet.uni-hamburg.de>
* All rights reserved.
*
* Implementation advice by David Mazieres <dm@lcs.mit.edu>.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* The bcrypt_pbkdf portions are under the following license:
*
* Copyright (c) 2013 Ted Unangst <tedu@openbsd.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Performance improvements (Javascript-specific):
*
* Copyright 2016, Joyent Inc
* Author: Alex Wilson <alex.wilson@joyent.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// Ported from OpenBSD bcrypt_pbkdf.c v1.9
var BLF_J = 0;
var Blowfish = function() {
this.S = [
new Uint32Array([
0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]),
new Uint32Array([
0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]),
new Uint32Array([
0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]),
new Uint32Array([
0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6])
];
this.P = new Uint32Array([
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
0x9216d5d9, 0x8979fb1b]);
};
function F(S, x8, i) {
return (((S[0][x8[i+3]] +
S[1][x8[i+2]]) ^
S[2][x8[i+1]]) +
S[3][x8[i]]);
};
Blowfish.prototype.encipher = function(x, x8) {
if (x8 === undefined) {
x8 = new Uint8Array(x.buffer);
if (x.byteOffset !== 0)
x8 = x8.subarray(x.byteOffset);
}
x[0] ^= this.P[0];
for (var i = 1; i < 16; i += 2) {
x[1] ^= F(this.S, x8, 0) ^ this.P[i];
x[0] ^= F(this.S, x8, 4) ^ this.P[i+1];
}
var t = x[0];
x[0] = x[1] ^ this.P[17];
x[1] = t;
};
Blowfish.prototype.decipher = function(x) {
var x8 = new Uint8Array(x.buffer);
if (x.byteOffset !== 0)
x8 = x8.subarray(x.byteOffset);
x[0] ^= this.P[17];
for (var i = 16; i > 0; i -= 2) {
x[1] ^= F(this.S, x8, 0) ^ this.P[i];
x[0] ^= F(this.S, x8, 4) ^ this.P[i-1];
}
var t = x[0];
x[0] = x[1] ^ this.P[0];
x[1] = t;
};
function stream2word(data, databytes){
var i, temp = 0;
for (i = 0; i < 4; i++, BLF_J++) {
if (BLF_J >= databytes) BLF_J = 0;
temp = (temp << 8) | data[BLF_J];
}
return temp;
};
Blowfish.prototype.expand0state = function(key, keybytes) {
var d = new Uint32Array(2), i, k;
var d8 = new Uint8Array(d.buffer);
for (i = 0, BLF_J = 0; i < 18; i++) {
this.P[i] ^= stream2word(key, keybytes);
}
BLF_J = 0;
for (i = 0; i < 18; i += 2) {
this.encipher(d, d8);
this.P[i] = d[0];
this.P[i+1] = d[1];
}
for (i = 0; i < 4; i++) {
for (k = 0; k < 256; k += 2) {
this.encipher(d, d8);
this.S[i][k] = d[0];
this.S[i][k+1] = d[1];
}
}
};
Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) {
var d = new Uint32Array(2), i, k;
for (i = 0, BLF_J = 0; i < 18; i++) {
this.P[i] ^= stream2word(key, keybytes);
}
for (i = 0, BLF_J = 0; i < 18; i += 2) {
d[0] ^= stream2word(data, databytes);
d[1] ^= stream2word(data, databytes);
this.encipher(d);
this.P[i] = d[0];
this.P[i+1] = d[1];
}
for (i = 0; i < 4; i++) {
for (k = 0; k < 256; k += 2) {
d[0] ^= stream2word(data, databytes);
d[1] ^= stream2word(data, databytes);
this.encipher(d);
this.S[i][k] = d[0];
this.S[i][k+1] = d[1];
}
}
BLF_J = 0;
};
Blowfish.prototype.enc = function(data, blocks) {
for (var i = 0; i < blocks; i++) {
this.encipher(data.subarray(i*2));
}
};
Blowfish.prototype.dec = function(data, blocks) {
for (var i = 0; i < blocks; i++) {
this.decipher(data.subarray(i*2));
}
};
var BCRYPT_BLOCKS = 8,
BCRYPT_HASHSIZE = 32;
function bcrypt_hash(sha2pass, sha2salt, out) {
var state = new Blowfish(),
cdata = new Uint32Array(BCRYPT_BLOCKS), i,
ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105,
99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109,
105,116,101]); //"OxychromaticBlowfishSwatDynamite"
state.expandstate(sha2salt, 64, sha2pass, 64);
for (i = 0; i < 64; i++) {
state.expand0state(sha2salt, 64);
state.expand0state(sha2pass, 64);
}
for (i = 0; i < BCRYPT_BLOCKS; i++)
cdata[i] = stream2word(ciphertext, ciphertext.byteLength);
for (i = 0; i < 64; i++)
state.enc(cdata, cdata.byteLength / 8);
for (i = 0; i < BCRYPT_BLOCKS; i++) {
out[4*i+3] = cdata[i] >>> 24;
out[4*i+2] = cdata[i] >>> 16;
out[4*i+1] = cdata[i] >>> 8;
out[4*i+0] = cdata[i];
}
};
function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) {
var sha2pass = new Uint8Array(64),
sha2salt = new Uint8Array(64),
out = new Uint8Array(BCRYPT_HASHSIZE),
tmpout = new Uint8Array(BCRYPT_HASHSIZE),
countsalt = new Uint8Array(saltlen+4),
i, j, amt, stride, dest, count,
origkeylen = keylen;
if (rounds < 1)
return -1;
if (passlen === 0 || saltlen === 0 || keylen === 0 ||
keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20))
return -1;
stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength);
amt = Math.floor((keylen + stride - 1) / stride);
for (i = 0; i < saltlen; i++)
countsalt[i] = salt[i];
crypto_hash_sha512(sha2pass, pass, passlen);
for (count = 1; keylen > 0; count++) {
countsalt[saltlen+0] = count >>> 24;
countsalt[saltlen+1] = count >>> 16;
countsalt[saltlen+2] = count >>> 8;
countsalt[saltlen+3] = count;
crypto_hash_sha512(sha2salt, countsalt, saltlen + 4);
bcrypt_hash(sha2pass, sha2salt, tmpout);
for (i = out.byteLength; i--;)
out[i] = tmpout[i];
for (i = 1; i < rounds; i++) {
crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength);
bcrypt_hash(sha2pass, sha2salt, tmpout);
for (j = 0; j < out.byteLength; j++)
out[j] ^= tmpout[j];
}
amt = Math.min(amt, keylen);
for (i = 0; i < amt; i++) {
dest = i * stride + (count - 1);
if (dest >= origkeylen)
break;
key[dest] = out[i];
}
keylen -= i;
}
return 0;
};
module.exports = {
BLOCKS: BCRYPT_BLOCKS,
HASHSIZE: BCRYPT_HASHSIZE,
hash: bcrypt_hash,
pbkdf: bcrypt_pbkdf
};
},{"tweetnacl":483}],122:[function(require,module,exports){
(function (module, exports) {
'use strict';
// Utils
function assert (val, msg) {
if (!val) throw new Error(msg || 'Assertion failed');
}
// Could use `inherits` module, but don't want to move from single file
// architecture yet.
function inherits (ctor, superCtor) {
ctor.super_ = superCtor;
var TempCtor = function () {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
}
// BN
function BN (number, base, endian) {
if (BN.isBN(number)) {
return number;
}
this.negative = 0;
this.words = null;
this.length = 0;
// Reduction context
this.red = null;
if (number !== null) {
if (base === 'le' || base === 'be') {
endian = base;
base = 10;
}
this._init(number || 0, base || 10, endian || 'be');
}
}
if (typeof module === 'object') {
module.exports = BN;
} else {
exports.BN = BN;
}
BN.BN = BN;
BN.wordSize = 26;
var Buffer;
try {
Buffer = require('buffer').Buffer;
} catch (e) {
}
BN.isBN = function isBN (num) {
if (num instanceof BN) {
return true;
}
return num !== null && typeof num === 'object' &&
num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
};
BN.max = function max (left, right) {
if (left.cmp(right) > 0) return left;
return right;
};
BN.min = function min (left, right) {
if (left.cmp(right) < 0) return left;
return right;
};
BN.prototype._init = function init (number, base, endian) {
if (typeof number === 'number') {
return this._initNumber(number, base, endian);
}
if (typeof number === 'object') {
return this._initArray(number, base, endian);
}
if (base === 'hex') {
base = 16;
}
assert(base === (base | 0) && base >= 2 && base <= 36);
number = number.toString().replace(/\s+/g, '');
var start = 0;
if (number[0] === '-') {
start++;
}
if (base === 16) {
this._parseHex(number, start);
} else {
this._parseBase(number, base, start);
}
if (number[0] === '-') {
this.negative = 1;
}
this.strip();
if (endian !== 'le') return;
this._initArray(this.toArray(), base, endian);
};
BN.prototype._initNumber = function _initNumber (number, base, endian) {
if (number < 0) {
this.negative = 1;
number = -number;
}
if (number < 0x4000000) {
this.words = [ number & 0x3ffffff ];
this.length = 1;
} else if (number < 0x10000000000000) {
this.words = [
number & 0x3ffffff,
(number / 0x4000000) & 0x3ffffff
];
this.length = 2;
} else {
assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
this.words = [
number & 0x3ffffff,
(number / 0x4000000) & 0x3ffffff,
1
];
this.length = 3;
}
if (endian !== 'le') return;
// Reverse the bytes
this._initArray(this.toArray(), base, endian);
};
BN.prototype._initArray = function _initArray (number, base, endian) {
// Perhaps a Uint8Array
assert(typeof number.length === 'number');
if (number.length <= 0) {
this.words = [ 0 ];
this.length = 1;
return this;
}
this.length = Math.ceil(number.length / 3);
this.words = new Array(this.length);
for (var i = 0; i < this.length; i++) {
this.words[i] = 0;
}
var j, w;
var off = 0;
if (endian === 'be') {
for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
} else if (endian === 'le') {
for (i = 0, j = 0; i < number.length; i += 3) {
w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
}
return this.strip();
};
function parseHex (str, start, end) {
var r = 0;
var len = Math.min(str.length, end);
for (var i = start; i < len; i++) {
var c = str.charCodeAt(i) - 48;
r <<= 4;
// 'a' - 'f'
if (c >= 49 && c <= 54) {
r |= c - 49 + 0xa;
// 'A' - 'F'
} else if (c >= 17 && c <= 22) {
r |= c - 17 + 0xa;
// '0' - '9'
} else {
r |= c & 0xf;
}
}
return r;
}
BN.prototype._parseHex = function _parseHex (number, start) {
// Create possibly bigger array to ensure that it fits the number
this.length = Math.ceil((number.length - start) / 6);
this.words = new Array(this.length);
for (var i = 0; i < this.length; i++) {
this.words[i] = 0;
}
var j, w;
// Scan 24-bit chunks and add them to the number
var off = 0;
for (i = number.length - 6, j = 0; i >= start; i -= 6) {
w = parseHex(number, i, i + 6);
this.words[j] |= (w << off) & 0x3ffffff;
// NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
if (i + 6 !== start) {
w = parseHex(number, start, i + 6);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
}
this.strip();
};
function parseBase (str, start, end, mul) {
var r = 0;
var len = Math.min(str.length, end);
for (var i = start; i < len; i++) {
var c = str.charCodeAt(i) - 48;
r *= mul;
// 'a'
if (c >= 49) {
r += c - 49 + 0xa;
// 'A'
} else if (c >= 17) {
r += c - 17 + 0xa;
// '0' - '9'
} else {
r += c;
}
}
return r;
}
BN.prototype._parseBase = function _parseBase (number, base, start) {
// Initialize as zero
this.words = [ 0 ];
this.length = 1;
// Find length of limb in base
for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
limbLen++;
}
limbLen--;
limbPow = (limbPow / base) | 0;
var total = number.length - start;
var mod = total % limbLen;
var end = Math.min(total, total - mod) + start;
var word = 0;
for (var i = start; i < end; i += limbLen) {
word = parseBase(number, i, i + limbLen, base);
this.imuln(limbPow);
if (this.words[0] + word < 0x4000000) {
this.words[0] += word;
} else {
this._iaddn(word);
}
}
if (mod !== 0) {
var pow = 1;
word = parseBase(number, i, number.length, base);
for (i = 0; i < mod; i++) {
pow *= base;
}
this.imuln(pow);
if (this.words[0] + word < 0x4000000) {
this.words[0] += word;
} else {
this._iaddn(word);
}
}
};
BN.prototype.copy = function copy (dest) {
dest.words = new Array(this.length);
for (var i = 0; i < this.length; i++) {
dest.words[i] = this.words[i];
}
dest.length = this.length;
dest.negative = this.negative;
dest.red = this.red;
};
BN.prototype.clone = function clone () {
var r = new BN(null);
this.copy(r);
return r;
};
BN.prototype._expand = function _expand (size) {
while (this.length < size) {
this.words[this.length++] = 0;
}
return this;
};
// Remove leading `0` from `this`
BN.prototype.strip = function strip () {
while (this.length > 1 && this.words[this.length - 1] === 0) {
this.length--;
}
return this._normSign();
};
BN.prototype._normSign = function _normSign () {
// -0 = 0
if (this.length === 1 && this.words[0] === 0) {
this.negative = 0;
}
return this;
};
BN.prototype.inspect = function inspect () {
return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
};
/*
var zeros = [];
var groupSizes = [];
var groupBases = [];
var s = '';
var i = -1;
while (++i < BN.wordSize) {
zeros[i] = s;
s += '0';
}
groupSizes[0] = 0;
groupSizes[1] = 0;
groupBases[0] = 0;
groupBases[1] = 0;
var base = 2 - 1;
while (++base < 36 + 1) {
var groupSize = 0;
var groupBase = 1;
while (groupBase < (1 << BN.wordSize) / base) {
groupBase *= base;
groupSize += 1;
}
groupSizes[base] = groupSize;
groupBases[base] = groupBase;
}
*/
var zeros = [
'',
'0',
'00',
'000',
'0000',
'00000',
'000000',
'0000000',
'00000000',
'000000000',
'0000000000',
'00000000000',
'000000000000',
'0000000000000',
'00000000000000',
'000000000000000',
'0000000000000000',
'00000000000000000',
'000000000000000000',
'0000000000000000000',
'00000000000000000000',
'000000000000000000000',
'0000000000000000000000',
'00000000000000000000000',
'000000000000000000000000',
'0000000000000000000000000'
];
var groupSizes = [
0, 0,
25, 16, 12, 11, 10, 9, 8,
8, 7, 7, 7, 7, 6, 6,
6, 6, 6, 6, 6, 5, 5,
5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5
];
var groupBases = [
0, 0,
33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
];
BN.prototype.toString = function toString (base, padding) {
base = base || 10;
padding = padding | 0 || 1;
var out;
if (base === 16 || base === 'hex') {
out = '';
var off = 0;
var carry = 0;
for (var i = 0; i < this.length; i++) {
var w = this.words[i];
var word = (((w << off) | carry) & 0xffffff).toString(16);
carry = (w >>> (24 - off)) & 0xffffff;
if (carry !== 0 || i !== this.length - 1) {
out = zeros[6 - word.length] + word + out;
} else {
out = word + out;
}
off += 2;
if (off >= 26) {
off -= 26;
i--;
}
}
if (carry !== 0) {
out = carry.toString(16) + out;
}
while (out.length % padding !== 0) {
out = '0' + out;
}
if (this.negative !== 0) {
out = '-' + out;
}
return out;
}
if (base === (base | 0) && base >= 2 && base <= 36) {
// var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
var groupSize = groupSizes[base];
// var groupBase = Math.pow(base, groupSize);
var groupBase = groupBases[base];
out = '';
var c = this.clone();
c.negative = 0;
while (!c.isZero()) {
var r = c.modn(groupBase).toString(base);
c = c.idivn(groupBase);
if (!c.isZero()) {
out = zeros[groupSize - r.length] + r + out;
} else {
out = r + out;
}
}
if (this.isZero()) {
out = '0' + out;
}
while (out.length % padding !== 0) {
out = '0' + out;
}
if (this.negative !== 0) {
out = '-' + out;
}
return out;
}
assert(false, 'Base should be between 2 and 36');
};
BN.prototype.toNumber = function toNumber () {
var ret = this.words[0];
if (this.length === 2) {
ret += this.words[1] * 0x4000000;
} else if (this.length === 3 && this.words[2] === 0x01) {
// NOTE: at this stage it is known that the top bit is set
ret += 0x10000000000000 + (this.words[1] * 0x4000000);
} else if (this.length > 2) {
assert(false, 'Number can only safely store up to 53 bits');
}
return (this.negative !== 0) ? -ret : ret;
};
BN.prototype.toJSON = function toJSON () {
return this.toString(16);
};
BN.prototype.toBuffer = function toBuffer (endian, length) {
assert(typeof Buffer !== 'undefined');
return this.toArrayLike(Buffer, endian, length);
};
BN.prototype.toArray = function toArray (endian, length) {
return this.toArrayLike(Array, endian, length);
};
BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
var byteLength = this.byteLength();
var reqLength = length || Math.max(1, byteLength);
assert(byteLength <= reqLength, 'byte array longer than desired length');
assert(reqLength > 0, 'Requested array length <= 0');
this.strip();
var littleEndian = endian === 'le';
var res = new ArrayType(reqLength);
var b, i;
var q = this.clone();
if (!littleEndian) {
// Assume big-endian
for (i = 0; i < reqLength - byteLength; i++) {
res[i] = 0;
}
for (i = 0; !q.isZero(); i++) {
b = q.andln(0xff);
q.iushrn(8);
res[reqLength - i - 1] = b;
}
} else {
for (i = 0; !q.isZero(); i++) {
b = q.andln(0xff);
q.iushrn(8);
res[i] = b;
}
for (; i < reqLength; i++) {
res[i] = 0;
}
}
return res;
};
if (Math.clz32) {
BN.prototype._countBits = function _countBits (w) {
return 32 - Math.clz32(w);
};
} else {
BN.prototype._countBits = function _countBits (w) {
var t = w;
var r = 0;
if (t >= 0x1000) {
r += 13;
t >>>= 13;
}
if (t >= 0x40) {
r += 7;
t >>>= 7;
}
if (t >= 0x8) {
r += 4;
t >>>= 4;
}
if (t >= 0x02) {
r += 2;
t >>>= 2;
}
return r + t;
};
}
BN.prototype._zeroBits = function _zeroBits (w) {
// Short-cut
if (w === 0) return 26;
var t = w;
var r = 0;
if ((t & 0x1fff) === 0) {
r += 13;
t >>>= 13;
}
if ((t & 0x7f) === 0) {
r += 7;
t >>>= 7;
}
if ((t & 0xf) === 0) {
r += 4;
t >>>= 4;
}
if ((t & 0x3) === 0) {
r += 2;
t >>>= 2;
}
if ((t & 0x1) === 0) {
r++;
}
return r;
};
// Return number of used bits in a BN
BN.prototype.bitLength = function bitLength () {
var w = this.words[this.length - 1];
var hi = this._countBits(w);
return (this.length - 1) * 26 + hi;
};
function toBitArray (num) {
var w = new Array(num.bitLength());
for (var bit = 0; bit < w.length; bit++) {
var off = (bit / 26) | 0;
var wbit = bit % 26;
w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
}
return w;
}
// Number of trailing zero bits
BN.prototype.zeroBits = function zeroBits () {
if (this.isZero()) return 0;
var r = 0;
for (var i = 0; i < this.length; i++) {
var b = this._zeroBits(this.words[i]);
r += b;
if (b !== 26) break;
}
return r;
};
BN.prototype.byteLength = function byteLength () {
return Math.ceil(this.bitLength() / 8);
};
BN.prototype.toTwos = function toTwos (width) {
if (this.negative !== 0) {
return this.abs().inotn(width).iaddn(1);
}
return this.clone();
};
BN.prototype.fromTwos = function fromTwos (width) {
if (this.testn(width - 1)) {
return this.notn(width).iaddn(1).ineg();
}
return this.clone();
};
BN.prototype.isNeg = function isNeg () {
return this.negative !== 0;
};
// Return negative clone of `this`
BN.prototype.neg = function neg () {
return this.clone().ineg();
};
BN.prototype.ineg = function ineg () {
if (!this.isZero()) {
this.negative ^= 1;
}
return this;
};
// Or `num` with `this` in-place
BN.prototype.iuor = function iuor (num) {
while (this.length < num.length) {
this.words[this.length++] = 0;
}
for (var i = 0; i < num.length; i++) {
this.words[i] = this.words[i] | num.words[i];
}
return this.strip();
};
BN.prototype.ior = function ior (num) {
assert((this.negative | num.negative) === 0);
return this.iuor(num);
};
// Or `num` with `this`
BN.prototype.or = function or (num) {
if (this.length > num.length) return this.clone().ior(num);
return num.clone().ior(this);
};
BN.prototype.uor = function uor (num) {
if (this.length > num.length) return this.clone().iuor(num);
return num.clone().iuor(this);
};
// And `num` with `this` in-place
BN.prototype.iuand = function iuand (num) {
// b = min-length(num, this)
var b;
if (this.length > num.length) {
b = num;
} else {
b = this;
}
for (var i = 0; i < b.length; i++) {
this.words[i] = this.words[i] & num.words[i];
}
this.length = b.length;
return this.strip();
};
BN.prototype.iand = function iand (num) {
assert((this.negative | num.negative) === 0);
return this.iuand(num);
};
// And `num` with `this`
BN.prototype.and = function and (num) {
if (this.length > num.length) return this.clone().iand(num);
return num.clone().iand(this);
};
BN.prototype.uand = function uand (num) {
if (this.length > num.length) return this.clone().iuand(num);
return num.clone().iuand(this);
};
// Xor `num` with `this` in-place
BN.prototype.iuxor = function iuxor (num) {
// a.length > b.length
var a;
var b;
if (this.length > num.length) {
a = this;
b = num;
} else {
a = num;
b = this;
}
for (var i = 0; i < b.length; i++) {
this.words[i] = a.words[i] ^ b.words[i];
}
if (this !== a) {
for (; i < a.length; i++) {
this.words[i] = a.words[i];
}
}
this.length = a.length;
return this.strip();
};
BN.prototype.ixor = function ixor (num) {
assert((this.negative | num.negative) === 0);
return this.iuxor(num);
};
// Xor `num` with `this`
BN.prototype.xor = function xor (num) {
if (this.length > num.length) return this.clone().ixor(num);
return num.clone().ixor(this);
};
BN.prototype.uxor = function uxor (num) {
if (this.length > num.length) return this.clone().iuxor(num);
return num.clone().iuxor(this);
};
// Not ``this`` with ``width`` bitwidth
BN.prototype.inotn = function inotn (width) {
assert(typeof width === 'number' && width >= 0);
var bytesNeeded = Math.ceil(width / 26) | 0;
var bitsLeft = width % 26;
// Extend the buffer with leading zeroes
this._expand(bytesNeeded);
if (bitsLeft > 0) {
bytesNeeded--;
}
// Handle complete words
for (var i = 0; i < bytesNeeded; i++) {
this.words[i] = ~this.words[i] & 0x3ffffff;
}
// Handle the residue
if (bitsLeft > 0) {
this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
}
// And remove leading zeroes
return this.strip();
};
BN.prototype.notn = function notn (width) {
return this.clone().inotn(width);
};
// Set `bit` of `this`
BN.prototype.setn = function setn (bit, val) {
assert(typeof bit === 'number' && bit >= 0);
var off = (bit / 26) | 0;
var wbit = bit % 26;
this._expand(off + 1);
if (val) {
this.words[off] = this.words[off] | (1 << wbit);
} else {
this.words[off] = this.words[off] & ~(1 << wbit);
}
return this.strip();
};
// Add `num` to `this` in-place
BN.prototype.iadd = function iadd (num) {
var r;
// negative + positive
if (this.negative !== 0 && num.negative === 0) {
this.negative = 0;
r = this.isub(num);
this.negative ^= 1;
return this._normSign();
// positive + negative
} else if (this.negative === 0 && num.negative !== 0) {
num.negative = 0;
r = this.isub(num);
num.negative = 1;
return r._normSign();
}
// a.length > b.length
var a, b;
if (this.length > num.length) {
a = this;
b = num;
} else {
a = num;
b = this;
}
var carry = 0;
for (var i = 0; i < b.length; i++) {
r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
this.words[i] = r & 0x3ffffff;
carry = r >>> 26;
}
for (; carry !== 0 && i < a.length; i++) {
r = (a.words[i] | 0) + carry;
this.words[i] = r & 0x3ffffff;
carry = r >>> 26;
}
this.length = a.length;
if (carry !== 0) {
this.words[this.length] = carry;
this.length++;
// Copy the rest of the words
} else if (a !== this) {
for (; i < a.length; i++) {
this.words[i] = a.words[i];
}
}
return this;
};
// Add `num` to `this`
BN.prototype.add = function add (num) {
var res;
if (num.negative !== 0 && this.negative === 0) {
num.negative = 0;
res = this.sub(num);
num.negative ^= 1;
return res;
} else if (num.negative === 0 && this.negative !== 0) {
this.negative = 0;
res = num.sub(this);
this.negative = 1;
return res;
}
if (this.length > num.length) return this.clone().iadd(num);
return num.clone().iadd(this);
};
// Subtract `num` from `this` in-place
BN.prototype.isub = function isub (num) {
// this - (-num) = this + num
if (num.negative !== 0) {
num.negative = 0;
var r = this.iadd(num);
num.negative = 1;
return r._normSign();
// -this - num = -(this + num)
} else if (this.negative !== 0) {
this.negative = 0;
this.iadd(num);
this.negative = 1;
return this._normSign();
}
// At this point both numbers are positive
var cmp = this.cmp(num);
// Optimization - zeroify
if (cmp === 0) {
this.negative = 0;
this.length = 1;
this.words[0] = 0;
return this;
}
// a > b
var a, b;
if (cmp > 0) {
a = this;
b = num;
} else {
a = num;
b = this;
}
var carry = 0;
for (var i = 0; i < b.length; i++) {
r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
carry = r >> 26;
this.words[i] = r & 0x3ffffff;
}
for (; carry !== 0 && i < a.length; i++) {
r = (a.words[i] | 0) + carry;
carry = r >> 26;
this.words[i] = r & 0x3ffffff;
}
// Copy rest of the words
if (carry === 0 && i < a.length && a !== this) {
for (; i < a.length; i++) {
this.words[i] = a.words[i];
}
}
this.length = Math.max(this.length, i);
if (a !== this) {
this.negative = 1;
}
return this.strip();
};
// Subtract `num` from `this`
BN.prototype.sub = function sub (num) {
return this.clone().isub(num);
};
function smallMulTo (self, num, out) {
out.negative = num.negative ^ self.negative;
var len = (self.length + num.length) | 0;
out.length = len;
len = (len - 1) | 0;
// Peel one iteration (compiler can't do it, because of code complexity)
var a = self.words[0] | 0;
var b = num.words[0] | 0;
var r = a * b;
var lo = r & 0x3ffffff;
var carry = (r / 0x4000000) | 0;
out.words[0] = lo;
for (var k = 1; k < len; k++) {
// Sum all words with the same `i + j = k` and accumulate `ncarry`,
// note that ncarry could be >= 0x3ffffff
var ncarry = carry >>> 26;
var rword = carry & 0x3ffffff;
var maxJ = Math.min(k, num.length - 1);
for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
var i = (k - j) | 0;
a = self.words[i] | 0;
b = num.words[j] | 0;
r = a * b + rword;
ncarry += (r / 0x4000000) | 0;
rword = r & 0x3ffffff;
}
out.words[k] = rword | 0;
carry = ncarry | 0;
}
if (carry !== 0) {
out.words[k] = carry | 0;
} else {
out.length--;
}
return out.strip();
}
// TODO(indutny): it may be reasonable to omit it for users who don't need
// to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
// multiplication (like elliptic secp256k1).
var comb10MulTo = function comb10MulTo (self, num, out) {
var a = self.words;
var b = num.words;
var o = out.words;
var c = 0;
var lo;
var mid;
var hi;
var a0 = a[0] | 0;
var al0 = a0 & 0x1fff;
var ah0 = a0 >>> 13;
var a1 = a[1] | 0;
var al1 = a1 & 0x1fff;
var ah1 = a1 >>> 13;
var a2 = a[2] | 0;
var al2 = a2 & 0x1fff;
var ah2 = a2 >>> 13;
var a3 = a[3] | 0;
var al3 = a3 & 0x1fff;
var ah3 = a3 >>> 13;
var a4 = a[4] | 0;
var al4 = a4 & 0x1fff;
var ah4 = a4 >>> 13;
var a5 = a[5] | 0;
var al5 = a5 & 0x1fff;
var ah5 = a5 >>> 13;
var a6 = a[6] | 0;
var al6 = a6 & 0x1fff;
var ah6 = a6 >>> 13;
var a7 = a[7] | 0;
var al7 = a7 & 0x1fff;
var ah7 = a7 >>> 13;
var a8 = a[8] | 0;
var al8 = a8 & 0x1fff;
var ah8 = a8 >>> 13;
var a9 = a[9] | 0;
var al9 = a9 & 0x1fff;
var ah9 = a9 >>> 13;
var b0 = b[0] | 0;
var bl0 = b0 & 0x1fff;
var bh0 = b0 >>> 13;
var b1 = b[1] | 0;
var bl1 = b1 & 0x1fff;
var bh1 = b1 >>> 13;
var b2 = b[2] | 0;
var bl2 = b2 & 0x1fff;
var bh2 = b2 >>> 13;
var b3 = b[3] | 0;
var bl3 = b3 & 0x1fff;
var bh3 = b3 >>> 13;
var b4 = b[4] | 0;
var bl4 = b4 & 0x1fff;
var bh4 = b4 >>> 13;
var b5 = b[5] | 0;
var bl5 = b5 & 0x1fff;
var bh5 = b5 >>> 13;
var b6 = b[6] | 0;
var bl6 = b6 & 0x1fff;
var bh6 = b6 >>> 13;
var b7 = b[7] | 0;
var bl7 = b7 & 0x1fff;
var bh7 = b7 >>> 13;
var b8 = b[8] | 0;
var bl8 = b8 & 0x1fff;
var bh8 = b8 >>> 13;
var b9 = b[9] | 0;
var bl9 = b9 & 0x1fff;
var bh9 = b9 >>> 13;
out.negative = self.negative ^ num.negative;
out.length = 19;
/* k = 0 */
lo = Math.imul(al0, bl0);
mid = Math.imul(al0, bh0);
mid = (mid + Math.imul(ah0, bl0)) | 0;
hi = Math.imul(ah0, bh0);
var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
w0 &= 0x3ffffff;
/* k = 1 */
lo = Math.imul(al1, bl0);
mid = Math.imul(al1, bh0);
mid = (mid + Math.imul(ah1, bl0)) | 0;
hi = Math.imul(ah1, bh0);
lo = (lo + Math.imul(al0, bl1)) | 0;
mid = (mid + Math.imul(al0, bh1)) | 0;
mid = (mid + Math.imul(ah0, bl1)) | 0;
hi = (hi + Math.imul(ah0, bh1)) | 0;
var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
w1 &= 0x3ffffff;
/* k = 2 */
lo = Math.imul(al2, bl0);
mid = Math.imul(al2, bh0);
mid = (mid + Math.imul(ah2, bl0)) | 0;
hi = Math.imul(ah2, bh0);
lo = (lo + Math.imul(al1, bl1)) | 0;
mid = (mid + Math.imul(al1, bh1)) | 0;
mid = (mid + Math.imul(ah1, bl1)) | 0;
hi = (hi + Math.imul(ah1, bh1)) | 0;
lo = (lo + Math.imul(al0, bl2)) | 0;
mid = (mid + Math.imul(al0, bh2)) | 0;
mid = (mid + Math.imul(ah0, bl2)) | 0;
hi = (hi + Math.imul(ah0, bh2)) | 0;
var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
w2 &= 0x3ffffff;
/* k = 3 */
lo = Math.imul(al3, bl0);
mid = Math.imul(al3, bh0);
mid = (mid + Math.imul(ah3, bl0)) | 0;
hi = Math.imul(ah3, bh0);
lo = (lo + Math.imul(al2, bl1)) | 0;
mid = (mid + Math.imul(al2, bh1)) | 0;
mid = (mid + Math.imul(ah2, bl1)) | 0;
hi = (hi + Math.imul(ah2, bh1)) | 0;
lo = (lo + Math.imul(al1, bl2)) | 0;
mid = (mid + Math.imul(al1, bh2)) | 0;
mid = (mid + Math.imul(ah1, bl2)) | 0;
hi = (hi + Math.imul(ah1, bh2)) | 0;
lo = (lo + Math.imul(al0, bl3)) | 0;
mid = (mid + Math.imul(al0, bh3)) | 0;
mid = (mid + Math.imul(ah0, bl3)) | 0;
hi = (hi + Math.imul(ah0, bh3)) | 0;
var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
w3 &= 0x3ffffff;
/* k = 4 */
lo = Math.imul(al4, bl0);
mid = Math.imul(al4, bh0);
mid = (mid + Math.imul(ah4, bl0)) | 0;
hi = Math.imul(ah4, bh0);
lo = (lo + Math.imul(al3, bl1)) | 0;
mid = (mid + Math.imul(al3, bh1)) | 0;
mid = (mid + Math.imul(ah3, bl1)) | 0;
hi = (hi + Math.imul(ah3, bh1)) | 0;
lo = (lo + Math.imul(al2, bl2)) | 0;
mid = (mid + Math.imul(al2, bh2)) | 0;
mid = (mid + Math.imul(ah2, bl2)) | 0;
hi = (hi + Math.imul(ah2, bh2)) | 0;
lo = (lo + Math.imul(al1, bl3)) | 0;
mid = (mid + Math.imul(al1, bh3)) | 0;
mid = (mid + Math.imul(ah1, bl3)) | 0;
hi = (hi + Math.imul(ah1, bh3)) | 0;
lo = (lo + Math.imul(al0, bl4)) | 0;
mid = (mid + Math.imul(al0, bh4)) | 0;
mid = (mid + Math.imul(ah0, bl4)) | 0;
hi = (hi + Math.imul(ah0, bh4)) | 0;
var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
w4 &= 0x3ffffff;
/* k = 5 */
lo = Math.imul(al5, bl0);
mid = Math.imul(al5, bh0);
mid = (mid + Math.imul(ah5, bl0)) | 0;
hi = Math.imul(ah5, bh0);
lo = (lo + Math.imul(al4, bl1)) | 0;
mid = (mid + Math.imul(al4, bh1)) | 0;
mid = (mid + Math.imul(ah4, bl1)) | 0;
hi = (hi + Math.imul(ah4, bh1)) | 0;
lo = (lo + Math.imul(al3, bl2)) | 0;
mid = (mid + Math.imul(al3, bh2)) | 0;
mid = (mid + Math.imul(ah3, bl2)) | 0;
hi = (hi + Math.imul(ah3, bh2)) | 0;
lo = (lo + Math.imul(al2, bl3)) | 0;
mid = (mid + Math.imul(al2, bh3)) | 0;
mid = (mid + Math.imul(ah2, bl3)) | 0;
hi = (hi + Math.imul(ah2, bh3)) | 0;
lo = (lo + Math.imul(al1, bl4)) | 0;
mid = (mid + Math.imul(al1, bh4)) | 0;
mid = (mid + Math.imul(ah1, bl4)) | 0;
hi = (hi + Math.imul(ah1, bh4)) | 0;
lo = (lo + Math.imul(al0, bl5)) | 0;
mid = (mid + Math.imul(al0, bh5)) | 0;
mid = (mid + Math.imul(ah0, bl5)) | 0;
hi = (hi + Math.imul(ah0, bh5)) | 0;
var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
w5 &= 0x3ffffff;
/* k = 6 */
lo = Math.imul(al6, bl0);
mid = Math.imul(al6, bh0);
mid = (mid + Math.imul(ah6, bl0)) | 0;
hi = Math.imul(ah6, bh0);
lo = (lo + Math.imul(al5, bl1)) | 0;
mid = (mid + Math.imul(al5, bh1)) | 0;
mid = (mid + Math.imul(ah5, bl1)) | 0;
hi = (hi + Math.imul(ah5, bh1)) | 0;
lo = (lo + Math.imul(al4, bl2)) | 0;
mid = (mid + Math.imul(al4, bh2)) | 0;
mid = (mid + Math.imul(ah4, bl2)) | 0;
hi = (hi + Math.imul(ah4, bh2)) | 0;
lo = (lo + Math.imul(al3, bl3)) | 0;
mid = (mid + Math.imul(al3, bh3)) | 0;
mid = (mid + Math.imul(ah3, bl3)) | 0;
hi = (hi + Math.imul(ah3, bh3)) | 0;
lo = (lo + Math.imul(al2, bl4)) | 0;
mid = (mid + Math.imul(al2, bh4)) | 0;
mid = (mid + Math.imul(ah2, bl4)) | 0;
hi = (hi + Math.imul(ah2, bh4)) | 0;
lo = (lo + Math.imul(al1, bl5)) | 0;
mid = (mid + Math.imul(al1, bh5)) | 0;
mid = (mid + Math.imul(ah1, bl5)) | 0;
hi = (hi + Math.imul(ah1, bh5)) | 0;
lo = (lo + Math.imul(al0, bl6)) | 0;
mid = (mid + Math.imul(al0, bh6)) | 0;
mid = (mid + Math.imul(ah0, bl6)) | 0;
hi = (hi + Math.imul(ah0, bh6)) | 0;
var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
w6 &= 0x3ffffff;
/* k = 7 */
lo = Math.imul(al7, bl0);
mid = Math.imul(al7, bh0);
mid = (mid + Math.imul(ah7, bl0)) | 0;
hi = Math.imul(ah7, bh0);
lo = (lo + Math.imul(al6, bl1)) | 0;
mid = (mid + Math.imul(al6, bh1)) | 0;
mid = (mid + Math.imul(ah6, bl1)) | 0;
hi = (hi + Math.imul(ah6, bh1)) | 0;
lo = (lo + Math.imul(al5, bl2)) | 0;
mid = (mid + Math.imul(al5, bh2)) | 0;
mid = (mid + Math.imul(ah5, bl2)) | 0;
hi = (hi + Math.imul(ah5, bh2)) | 0;
lo = (lo + Math.imul(al4, bl3)) | 0;
mid = (mid + Math.imul(al4, bh3)) | 0;
mid = (mid + Math.imul(ah4, bl3)) | 0;
hi = (hi + Math.imul(ah4, bh3)) | 0;
lo = (lo + Math.imul(al3, bl4)) | 0;
mid = (mid + Math.imul(al3, bh4)) | 0;
mid = (mid + Math.imul(ah3, bl4)) | 0;
hi = (hi + Math.imul(ah3, bh4)) | 0;
lo = (lo + Math.imul(al2, bl5)) | 0;
mid = (mid + Math.imul(al2, bh5)) | 0;
mid = (mid + Math.imul(ah2, bl5)) | 0;
hi = (hi + Math.imul(ah2, bh5)) | 0;
lo = (lo + Math.imul(al1, bl6)) | 0;
mid = (mid + Math.imul(al1, bh6)) | 0;
mid = (mid + Math.imul(ah1, bl6)) | 0;
hi = (hi + Math.imul(ah1, bh6)) | 0;
lo = (lo + Math.imul(al0, bl7)) | 0;
mid = (mid + Math.imul(al0, bh7)) | 0;
mid = (mid + Math.imul(ah0, bl7)) | 0;
hi = (hi + Math.imul(ah0, bh7)) | 0;
var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
w7 &= 0x3ffffff;
/* k = 8 */
lo = Math.imul(al8, bl0);
mid = Math.imul(al8, bh0);
mid = (mid + Math.imul(ah8, bl0)) | 0;
hi = Math.imul(ah8, bh0);
lo = (lo + Math.imul(al7, bl1)) | 0;
mid = (mid + Math.imul(al7, bh1)) | 0;
mid = (mid + Math.imul(ah7, bl1)) | 0;
hi = (hi + Math.imul(ah7, bh1)) | 0;
lo = (lo + Math.imul(al6, bl2)) | 0;
mid = (mid + Math.imul(al6, bh2)) | 0;
mid = (mid + Math.imul(ah6, bl2)) | 0;
hi = (hi + Math.imul(ah6, bh2)) | 0;
lo = (lo + Math.imul(al5, bl3)) | 0;
mid = (mid + Math.imul(al5, bh3)) | 0;
mid = (mid + Math.imul(ah5, bl3)) | 0;
hi = (hi + Math.imul(ah5, bh3)) | 0;
lo = (lo + Math.imul(al4, bl4)) | 0;
mid = (mid + Math.imul(al4, bh4)) | 0;
mid = (mid + Math.imul(ah4, bl4)) | 0;
hi = (hi + Math.imul(ah4, bh4)) | 0;
lo = (lo + Math.imul(al3, bl5)) | 0;
mid = (mid + Math.imul(al3, bh5)) | 0;
mid = (mid + Math.imul(ah3, bl5)) | 0;
hi = (hi + Math.imul(ah3, bh5)) | 0;
lo = (lo + Math.imul(al2, bl6)) | 0;
mid = (mid + Math.imul(al2, bh6)) | 0;
mid = (mid + Math.imul(ah2, bl6)) | 0;
hi = (hi + Math.imul(ah2, bh6)) | 0;
lo = (lo + Math.imul(al1, bl7)) | 0;
mid = (mid + Math.imul(al1, bh7)) | 0;
mid = (mid + Math.imul(ah1, bl7)) | 0;
hi = (hi + Math.imul(ah1, bh7)) | 0;
lo = (lo + Math.imul(al0, bl8)) | 0;
mid = (mid + Math.imul(al0, bh8)) | 0;
mid = (mid + Math.imul(ah0, bl8)) | 0;
hi = (hi + Math.imul(ah0, bh8)) | 0;
var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
w8 &= 0x3ffffff;
/* k = 9 */
lo = Math.imul(al9, bl0);
mid = Math.imul(al9, bh0);
mid = (mid + Math.imul(ah9, bl0)) | 0;
hi = Math.imul(ah9, bh0);
lo = (lo + Math.imul(al8, bl1)) | 0;
mid = (mid + Math.imul(al8, bh1)) | 0;
mid = (mid + Math.imul(ah8, bl1)) | 0;
hi = (hi + Math.imul(ah8, bh1)) | 0;
lo = (lo + Math.imul(al7, bl2)) | 0;
mid = (mid + Math.imul(al7, bh2)) | 0;
mid = (mid + Math.imul(ah7, bl2)) | 0;
hi = (hi + Math.imul(ah7, bh2)) | 0;
lo = (lo + Math.imul(al6, bl3)) | 0;
mid = (mid + Math.imul(al6, bh3)) | 0;
mid = (mid + Math.imul(ah6, bl3)) | 0;
hi = (hi + Math.imul(ah6, bh3)) | 0;
lo = (lo + Math.imul(al5, bl4)) | 0;
mid = (mid + Math.imul(al5, bh4)) | 0;
mid = (mid + Math.imul(ah5, bl4)) | 0;
hi = (hi + Math.imul(ah5, bh4)) | 0;
lo = (lo + Math.imul(al4, bl5)) | 0;
mid = (mid + Math.imul(al4, bh5)) | 0;
mid = (mid + Math.imul(ah4, bl5)) | 0;
hi = (hi + Math.imul(ah4, bh5)) | 0;
lo = (lo + Math.imul(al3, bl6)) | 0;
mid = (mid + Math.imul(al3, bh6)) | 0;
mid = (mid + Math.imul(ah3, bl6)) | 0;
hi = (hi + Math.imul(ah3, bh6)) | 0;
lo = (lo + Math.imul(al2, bl7)) | 0;
mid = (mid + Math.imul(al2, bh7)) | 0;
mid = (mid + Math.imul(ah2, bl7)) | 0;
hi = (hi + Math.imul(ah2, bh7)) | 0;
lo = (lo + Math.imul(al1, bl8)) | 0;
mid = (mid + Math.imul(al1, bh8)) | 0;
mid = (mid + Math.imul(ah1, bl8)) | 0;
hi = (hi + Math.imul(ah1, bh8)) | 0;
lo = (lo + Math.imul(al0, bl9)) | 0;
mid = (mid + Math.imul(al0, bh9)) | 0;
mid = (mid + Math.imul(ah0, bl9)) | 0;
hi = (hi + Math.imul(ah0, bh9)) | 0;
var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
w9 &= 0x3ffffff;
/* k = 10 */
lo = Math.imul(al9, bl1);
mid = Math.imul(al9, bh1);
mid = (mid + Math.imul(ah9, bl1)) | 0;
hi = Math.imul(ah9, bh1);
lo = (lo + Math.imul(al8, bl2)) | 0;
mid = (mid + Math.imul(al8, bh2)) | 0;
mid = (mid + Math.imul(ah8, bl2)) | 0;
hi = (hi + Math.imul(ah8, bh2)) | 0;
lo = (lo + Math.imul(al7, bl3)) | 0;
mid = (mid + Math.imul(al7, bh3)) | 0;
mid = (mid + Math.imul(ah7, bl3)) | 0;
hi = (hi + Math.imul(ah7, bh3)) | 0;
lo = (lo + Math.imul(al6, bl4)) | 0;
mid = (mid + Math.imul(al6, bh4)) | 0;
mid = (mid + Math.imul(ah6, bl4)) | 0;
hi = (hi + Math.imul(ah6, bh4)) | 0;
lo = (lo + Math.imul(al5, bl5)) | 0;
mid = (mid + Math.imul(al5, bh5)) | 0;
mid = (mid + Math.imul(ah5, bl5)) | 0;
hi = (hi + Math.imul(ah5, bh5)) | 0;
lo = (lo + Math.imul(al4, bl6)) | 0;
mid = (mid + Math.imul(al4, bh6)) | 0;
mid = (mid + Math.imul(ah4, bl6)) | 0;
hi = (hi + Math.imul(ah4, bh6)) | 0;
lo = (lo + Math.imul(al3, bl7)) | 0;
mid = (mid + Math.imul(al3, bh7)) | 0;
mid = (mid + Math.imul(ah3, bl7)) | 0;
hi = (hi + Math.imul(ah3, bh7)) | 0;
lo = (lo + Math.imul(al2, bl8)) | 0;
mid = (mid + Math.imul(al2, bh8)) | 0;
mid = (mid + Math.imul(ah2, bl8)) | 0;
hi = (hi + Math.imul(ah2, bh8)) | 0;
lo = (lo + Math.imul(al1, bl9)) | 0;
mid = (mid + Math.imul(al1, bh9)) | 0;
mid = (mid + Math.imul(ah1, bl9)) | 0;
hi = (hi + Math.imul(ah1, bh9)) | 0;
var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
w10 &= 0x3ffffff;
/* k = 11 */
lo = Math.imul(al9, bl2);
mid = Math.imul(al9, bh2);
mid = (mid + Math.imul(ah9, bl2)) | 0;
hi = Math.imul(ah9, bh2);
lo = (lo + Math.imul(al8, bl3)) | 0;
mid = (mid + Math.imul(al8, bh3)) | 0;
mid = (mid + Math.imul(ah8, bl3)) | 0;
hi = (hi + Math.imul(ah8, bh3)) | 0;
lo = (lo + Math.imul(al7, bl4)) | 0;
mid = (mid + Math.imul(al7, bh4)) | 0;
mid = (mid + Math.imul(ah7, bl4)) | 0;
hi = (hi + Math.imul(ah7, bh4)) | 0;
lo = (lo + Math.imul(al6, bl5)) | 0;
mid = (mid + Math.imul(al6, bh5)) | 0;
mid = (mid + Math.imul(ah6, bl5)) | 0;
hi = (hi + Math.imul(ah6, bh5)) | 0;
lo = (lo + Math.imul(al5, bl6)) | 0;
mid = (mid + Math.imul(al5, bh6)) | 0;
mid = (mid + Math.imul(ah5, bl6)) | 0;
hi = (hi + Math.imul(ah5, bh6)) | 0;
lo = (lo + Math.imul(al4, bl7)) | 0;
mid = (mid + Math.imul(al4, bh7)) | 0;
mid = (mid + Math.imul(ah4, bl7)) | 0;
hi = (hi + Math.imul(ah4, bh7)) | 0;
lo = (lo + Math.imul(al3, bl8)) | 0;
mid = (mid + Math.imul(al3, bh8)) | 0;
mid = (mid + Math.imul(ah3, bl8)) | 0;
hi = (hi + Math.imul(ah3, bh8)) | 0;
lo = (lo + Math.imul(al2, bl9)) | 0;
mid = (mid + Math.imul(al2, bh9)) | 0;
mid = (mid + Math.imul(ah2, bl9)) | 0;
hi = (hi + Math.imul(ah2, bh9)) | 0;
var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
w11 &= 0x3ffffff;
/* k = 12 */
lo = Math.imul(al9, bl3);
mid = Math.imul(al9, bh3);
mid = (mid + Math.imul(ah9, bl3)) | 0;
hi = Math.imul(ah9, bh3);
lo = (lo + Math.imul(al8, bl4)) | 0;
mid = (mid + Math.imul(al8, bh4)) | 0;
mid = (mid + Math.imul(ah8, bl4)) | 0;
hi = (hi + Math.imul(ah8, bh4)) | 0;
lo = (lo + Math.imul(al7, bl5)) | 0;
mid = (mid + Math.imul(al7, bh5)) | 0;
mid = (mid + Math.imul(ah7, bl5)) | 0;
hi = (hi + Math.imul(ah7, bh5)) | 0;
lo = (lo + Math.imul(al6, bl6)) | 0;
mid = (mid + Math.imul(al6, bh6)) | 0;
mid = (mid + Math.imul(ah6, bl6)) | 0;
hi = (hi + Math.imul(ah6, bh6)) | 0;
lo = (lo + Math.imul(al5, bl7)) | 0;
mid = (mid + Math.imul(al5, bh7)) | 0;
mid = (mid + Math.imul(ah5, bl7)) | 0;
hi = (hi + Math.imul(ah5, bh7)) | 0;
lo = (lo + Math.imul(al4, bl8)) | 0;
mid = (mid + Math.imul(al4, bh8)) | 0;
mid = (mid + Math.imul(ah4, bl8)) | 0;
hi = (hi + Math.imul(ah4, bh8)) | 0;
lo = (lo + Math.imul(al3, bl9)) | 0;
mid = (mid + Math.imul(al3, bh9)) | 0;
mid = (mid + Math.imul(ah3, bl9)) | 0;
hi = (hi + Math.imul(ah3, bh9)) | 0;
var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
w12 &= 0x3ffffff;
/* k = 13 */
lo = Math.imul(al9, bl4);
mid = Math.imul(al9, bh4);
mid = (mid + Math.imul(ah9, bl4)) | 0;
hi = Math.imul(ah9, bh4);
lo = (lo + Math.imul(al8, bl5)) | 0;
mid = (mid + Math.imul(al8, bh5)) | 0;
mid = (mid + Math.imul(ah8, bl5)) | 0;
hi = (hi + Math.imul(ah8, bh5)) | 0;
lo = (lo + Math.imul(al7, bl6)) | 0;
mid = (mid + Math.imul(al7, bh6)) | 0;
mid = (mid + Math.imul(ah7, bl6)) | 0;
hi = (hi + Math.imul(ah7, bh6)) | 0;
lo = (lo + Math.imul(al6, bl7)) | 0;
mid = (mid + Math.imul(al6, bh7)) | 0;
mid = (mid + Math.imul(ah6, bl7)) | 0;
hi = (hi + Math.imul(ah6, bh7)) | 0;
lo = (lo + Math.imul(al5, bl8)) | 0;
mid = (mid + Math.imul(al5, bh8)) | 0;
mid = (mid + Math.imul(ah5, bl8)) | 0;
hi = (hi + Math.imul(ah5, bh8)) | 0;
lo = (lo + Math.imul(al4, bl9)) | 0;
mid = (mid + Math.imul(al4, bh9)) | 0;
mid = (mid + Math.imul(ah4, bl9)) | 0;
hi = (hi + Math.imul(ah4, bh9)) | 0;
var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
w13 &= 0x3ffffff;
/* k = 14 */
lo = Math.imul(al9, bl5);
mid = Math.imul(al9, bh5);
mid = (mid + Math.imul(ah9, bl5)) | 0;
hi = Math.imul(ah9, bh5);
lo = (lo + Math.imul(al8, bl6)) | 0;
mid = (mid + Math.imul(al8, bh6)) | 0;
mid = (mid + Math.imul(ah8, bl6)) | 0;
hi = (hi + Math.imul(ah8, bh6)) | 0;
lo = (lo + Math.imul(al7, bl7)) | 0;
mid = (mid + Math.imul(al7, bh7)) | 0;
mid = (mid + Math.imul(ah7, bl7)) | 0;
hi = (hi + Math.imul(ah7, bh7)) | 0;
lo = (lo + Math.imul(al6, bl8)) | 0;
mid = (mid + Math.imul(al6, bh8)) | 0;
mid = (mid + Math.imul(ah6, bl8)) | 0;
hi = (hi + Math.imul(ah6, bh8)) | 0;
lo = (lo + Math.imul(al5, bl9)) | 0;
mid = (mid + Math.imul(al5, bh9)) | 0;
mid = (mid + Math.imul(ah5, bl9)) | 0;
hi = (hi + Math.imul(ah5, bh9)) | 0;
var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
w14 &= 0x3ffffff;
/* k = 15 */
lo = Math.imul(al9, bl6);
mid = Math.imul(al9, bh6);
mid = (mid + Math.imul(ah9, bl6)) | 0;
hi = Math.imul(ah9, bh6);
lo = (lo + Math.imul(al8, bl7)) | 0;
mid = (mid + Math.imul(al8, bh7)) | 0;
mid = (mid + Math.imul(ah8, bl7)) | 0;
hi = (hi + Math.imul(ah8, bh7)) | 0;
lo = (lo + Math.imul(al7, bl8)) | 0;
mid = (mid + Math.imul(al7, bh8)) | 0;
mid = (mid + Math.imul(ah7, bl8)) | 0;
hi = (hi + Math.imul(ah7, bh8)) | 0;
lo = (lo + Math.imul(al6, bl9)) | 0;
mid = (mid + Math.imul(al6, bh9)) | 0;
mid = (mid + Math.imul(ah6, bl9)) | 0;
hi = (hi + Math.imul(ah6, bh9)) | 0;
var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
w15 &= 0x3ffffff;
/* k = 16 */
lo = Math.imul(al9, bl7);
mid = Math.imul(al9, bh7);
mid = (mid + Math.imul(ah9, bl7)) | 0;
hi = Math.imul(ah9, bh7);
lo = (lo + Math.imul(al8, bl8)) | 0;
mid = (mid + Math.imul(al8, bh8)) | 0;
mid = (mid + Math.imul(ah8, bl8)) | 0;
hi = (hi + Math.imul(ah8, bh8)) | 0;
lo = (lo + Math.imul(al7, bl9)) | 0;
mid = (mid + Math.imul(al7, bh9)) | 0;
mid = (mid + Math.imul(ah7, bl9)) | 0;
hi = (hi + Math.imul(ah7, bh9)) | 0;
var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
w16 &= 0x3ffffff;
/* k = 17 */
lo = Math.imul(al9, bl8);
mid = Math.imul(al9, bh8);
mid = (mid + Math.imul(ah9, bl8)) | 0;
hi = Math.imul(ah9, bh8);
lo = (lo + Math.imul(al8, bl9)) | 0;
mid = (mid + Math.imul(al8, bh9)) | 0;
mid = (mid + Math.imul(ah8, bl9)) | 0;
hi = (hi + Math.imul(ah8, bh9)) | 0;
var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
w17 &= 0x3ffffff;
/* k = 18 */
lo = Math.imul(al9, bl9);
mid = Math.imul(al9, bh9);
mid = (mid + Math.imul(ah9, bl9)) | 0;
hi = Math.imul(ah9, bh9);
var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
w18 &= 0x3ffffff;
o[0] = w0;
o[1] = w1;
o[2] = w2;
o[3] = w3;
o[4] = w4;
o[5] = w5;
o[6] = w6;
o[7] = w7;
o[8] = w8;
o[9] = w9;
o[10] = w10;
o[11] = w11;
o[12] = w12;
o[13] = w13;
o[14] = w14;
o[15] = w15;
o[16] = w16;
o[17] = w17;
o[18] = w18;
if (c !== 0) {
o[19] = c;
out.length++;
}
return out;
};
// Polyfill comb
if (!Math.imul) {
comb10MulTo = smallMulTo;
}
function bigMulTo (self, num, out) {
out.negative = num.negative ^ self.negative;
out.length = self.length + num.length;
var carry = 0;
var hncarry = 0;
for (var k = 0; k < out.length - 1; k++) {
// Sum all words with the same `i + j = k` and accumulate `ncarry`,
// note that ncarry could be >= 0x3ffffff
var ncarry = hncarry;
hncarry = 0;
var rword = carry & 0x3ffffff;
var maxJ = Math.min(k, num.length - 1);
for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
var i = k - j;
var a = self.words[i] | 0;
var b = num.words[j] | 0;
var r = a * b;
var lo = r & 0x3ffffff;
ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
lo = (lo + rword) | 0;
rword = lo & 0x3ffffff;
ncarry = (ncarry + (lo >>> 26)) | 0;
hncarry += ncarry >>> 26;
ncarry &= 0x3ffffff;
}
out.words[k] = rword;
carry = ncarry;
ncarry = hncarry;
}
if (carry !== 0) {
out.words[k] = carry;
} else {
out.length--;
}
return out.strip();
}
function jumboMulTo (self, num, out) {
var fftm = new FFTM();
return fftm.mulp(self, num, out);
}
BN.prototype.mulTo = function mulTo (num, out) {
var res;
var len = this.length + num.length;
if (this.length === 10 && num.length === 10) {
res = comb10MulTo(this, num, out);
} else if (len < 63) {
res = smallMulTo(this, num, out);
} else if (len < 1024) {
res = bigMulTo(this, num, out);
} else {
res = jumboMulTo(this, num, out);
}
return res;
};
// Cooley-Tukey algorithm for FFT
// slightly revisited to rely on looping instead of recursion
function FFTM (x, y) {
this.x = x;
this.y = y;
}
FFTM.prototype.makeRBT = function makeRBT (N) {
var t = new Array(N);
var l = BN.prototype._countBits(N) - 1;
for (var i = 0; i < N; i++) {
t[i] = this.revBin(i, l, N);
}
return t;
};
// Returns binary-reversed representation of `x`
FFTM.prototype.revBin = function revBin (x, l, N) {
if (x === 0 || x === N - 1) return x;
var rb = 0;
for (var i = 0; i < l; i++) {
rb |= (x & 1) << (l - i - 1);
x >>= 1;
}
return rb;
};
// Performs "tweedling" phase, therefore 'emulating'
// behaviour of the recursive algorithm
FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
for (var i = 0; i < N; i++) {
rtws[i] = rws[rbt[i]];
itws[i] = iws[rbt[i]];
}
};
FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
this.permute(rbt, rws, iws, rtws, itws, N);
for (var s = 1; s < N; s <<= 1) {
var l = s << 1;
var rtwdf = Math.cos(2 * Math.PI / l);
var itwdf = Math.sin(2 * Math.PI / l);
for (var p = 0; p < N; p += l) {
var rtwdf_ = rtwdf;
var itwdf_ = itwdf;
for (var j = 0; j < s; j++) {
var re = rtws[p + j];
var ie = itws[p + j];
var ro = rtws[p + j + s];
var io = itws[p + j + s];
var rx = rtwdf_ * ro - itwdf_ * io;
io = rtwdf_ * io + itwdf_ * ro;
ro = rx;
rtws[p + j] = re + ro;
itws[p + j] = ie + io;
rtws[p + j + s] = re - ro;
itws[p + j + s] = ie - io;
/* jshint maxdepth : false */
if (j !== l) {
rx = rtwdf * rtwdf_ - itwdf * itwdf_;
itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
rtwdf_ = rx;
}
}
}
}
};
FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
var N = Math.max(m, n) | 1;
var odd = N & 1;
var i = 0;
for (N = N / 2 | 0; N; N = N >>> 1) {
i++;
}
return 1 << i + 1 + odd;
};
FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
if (N <= 1) return;
for (var i = 0; i < N / 2; i++) {
var t = rws[i];
rws[i] = rws[N - i - 1];
rws[N - i - 1] = t;
t = iws[i];
iws[i] = -iws[N - i - 1];
iws[N - i - 1] = -t;
}
};
FFTM.prototype.normalize13b = function normalize13b (ws, N) {
var carry = 0;
for (var i = 0; i < N / 2; i++) {
var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
Math.round(ws[2 * i] / N) +
carry;
ws[i] = w & 0x3ffffff;
if (w < 0x4000000) {
carry = 0;
} else {
carry = w / 0x4000000 | 0;
}
}
return ws;
};
FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
var carry = 0;
for (var i = 0; i < len; i++) {
carry = carry + (ws[i] | 0);
rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
}
// Pad with zeroes
for (i = 2 * len; i < N; ++i) {
rws[i] = 0;
}
assert(carry === 0);
assert((carry & ~0x1fff) === 0);
};
FFTM.prototype.stub = function stub (N) {
var ph = new Array(N);
for (var i = 0; i < N; i++) {
ph[i] = 0;
}
return ph;
};
FFTM.prototype.mulp = function mulp (x, y, out) {
var N = 2 * this.guessLen13b(x.length, y.length);
var rbt = this.makeRBT(N);
var _ = this.stub(N);
var rws = new Array(N);
var rwst = new Array(N);
var iwst = new Array(N);
var nrws = new Array(N);
var nrwst = new Array(N);
var niwst = new Array(N);
var rmws = out.words;
rmws.length = N;
this.convert13b(x.words, x.length, rws, N);
this.convert13b(y.words, y.length, nrws, N);
this.transform(rws, _, rwst, iwst, N, rbt);
this.transform(nrws, _, nrwst, niwst, N, rbt);
for (var i = 0; i < N; i++) {
var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
rwst[i] = rx;
}
this.conjugate(rwst, iwst, N);
this.transform(rwst, iwst, rmws, _, N, rbt);
this.conjugate(rmws, _, N);
this.normalize13b(rmws, N);
out.negative = x.negative ^ y.negative;
out.length = x.length + y.length;
return out.strip();
};
// Multiply `this` by `num`
BN.prototype.mul = function mul (num) {
var out = new BN(null);
out.words = new Array(this.length + num.length);
return this.mulTo(num, out);
};
// Multiply employing FFT
BN.prototype.mulf = function mulf (num) {
var out = new BN(null);
out.words = new Array(this.length + num.length);
return jumboMulTo(this, num, out);
};
// In-place Multiplication
BN.prototype.imul = function imul (num) {
return this.clone().mulTo(num, this);
};
BN.prototype.imuln = function imuln (num) {
assert(typeof num === 'number');
assert(num < 0x4000000);
// Carry
var carry = 0;
for (var i = 0; i < this.length; i++) {
var w = (this.words[i] | 0) * num;
var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
carry >>= 26;
carry += (w / 0x4000000) | 0;
// NOTE: lo is 27bit maximum
carry += lo >>> 26;
this.words[i] = lo & 0x3ffffff;
}
if (carry !== 0) {
this.words[i] = carry;
this.length++;
}
return this;
};
BN.prototype.muln = function muln (num) {
return this.clone().imuln(num);
};
// `this` * `this`
BN.prototype.sqr = function sqr () {
return this.mul(this);
};
// `this` * `this` in-place
BN.prototype.isqr = function isqr () {
return this.imul(this.clone());
};
// Math.pow(`this`, `num`)
BN.prototype.pow = function pow (num) {
var w = toBitArray(num);
if (w.length === 0) return new BN(1);
// Skip leading zeroes
var res = this;
for (var i = 0; i < w.length; i++, res = res.sqr()) {
if (w[i] !== 0) break;
}
if (++i < w.length) {
for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
if (w[i] === 0) continue;
res = res.mul(q);
}
}
return res;
};
// Shift-left in-place
BN.prototype.iushln = function iushln (bits) {
assert(typeof bits === 'number' && bits >= 0);
var r = bits % 26;
var s = (bits - r) / 26;
var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
var i;
if (r !== 0) {
var carry = 0;
for (i = 0; i < this.length; i++) {
var newCarry = this.words[i] & carryMask;
var c = ((this.words[i] | 0) - newCarry) << r;
this.words[i] = c | carry;
carry = newCarry >>> (26 - r);
}
if (carry) {
this.words[i] = carry;
this.length++;
}
}
if (s !== 0) {
for (i = this.length - 1; i >= 0; i--) {
this.words[i + s] = this.words[i];
}
for (i = 0; i < s; i++) {
this.words[i] = 0;
}
this.length += s;
}
return this.strip();
};
BN.prototype.ishln = function ishln (bits) {
// TODO(indutny): implement me
assert(this.negative === 0);
return this.iushln(bits);
};
// Shift-right in-place
// NOTE: `hint` is a lowest bit before trailing zeroes
// NOTE: if `extended` is present - it will be filled with destroyed bits
BN.prototype.iushrn = function iushrn (bits, hint, extended) {
assert(typeof bits === 'number' && bits >= 0);
var h;
if (hint) {
h = (hint - (hint % 26)) / 26;
} else {
h = 0;
}
var r = bits % 26;
var s = Math.min((bits - r) / 26, this.length);
var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
var maskedWords = extended;
h -= s;
h = Math.max(0, h);
// Extended mode, copy masked part
if (maskedWords) {
for (var i = 0; i < s; i++) {
maskedWords.words[i] = this.words[i];
}
maskedWords.length = s;
}
if (s === 0) {
// No-op, we should not move anything at all
} else if (this.length > s) {
this.length -= s;
for (i = 0; i < this.length; i++) {
this.words[i] = this.words[i + s];
}
} else {
this.words[0] = 0;
this.length = 1;
}
var carry = 0;
for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
var word = this.words[i] | 0;
this.words[i] = (carry << (26 - r)) | (word >>> r);
carry = word & mask;
}
// Push carried bits as a mask
if (maskedWords && carry !== 0) {
maskedWords.words[maskedWords.length++] = carry;
}
if (this.length === 0) {
this.words[0] = 0;
this.length = 1;
}
return this.strip();
};
BN.prototype.ishrn = function ishrn (bits, hint, extended) {
// TODO(indutny): implement me
assert(this.negative === 0);
return this.iushrn(bits, hint, extended);
};
// Shift-left
BN.prototype.shln = function shln (bits) {
return this.clone().ishln(bits);
};
BN.prototype.ushln = function ushln (bits) {
return this.clone().iushln(bits);
};
// Shift-right
BN.prototype.shrn = function shrn (bits) {
return this.clone().ishrn(bits);
};
BN.prototype.ushrn = function ushrn (bits) {
return this.clone().iushrn(bits);
};
// Test if n bit is set
BN.prototype.testn = function testn (bit) {
assert(typeof bit === 'number' && bit >= 0);
var r = bit % 26;
var s = (bit - r) / 26;
var q = 1 << r;
// Fast case: bit is much higher than all existing words
if (this.length <= s) return false;
// Check bit and return
var w = this.words[s];
return !!(w & q);
};
// Return only lowers bits of number (in-place)
BN.prototype.imaskn = function imaskn (bits) {
assert(typeof bits === 'number' && bits >= 0);
var r = bits % 26;
var s = (bits - r) / 26;
assert(this.negative === 0, 'imaskn works only with positive numbers');
if (this.length <= s) {
return this;
}
if (r !== 0) {
s++;
}
this.length = Math.min(s, this.length);
if (r !== 0) {
var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
this.words[this.length - 1] &= mask;
}
return this.strip();
};
// Return only lowers bits of number
BN.prototype.maskn = function maskn (bits) {
return this.clone().imaskn(bits);
};
// Add plain number `num` to `this`
BN.prototype.iaddn = function iaddn (num) {
assert(typeof num === 'number');
assert(num < 0x4000000);
if (num < 0) return this.isubn(-num);
// Possible sign change
if (this.negative !== 0) {
if (this.length === 1 && (this.words[0] | 0) < num) {
this.words[0] = num - (this.words[0] | 0);
this.negative = 0;
return this;
}
this.negative = 0;
this.isubn(num);
this.negative = 1;
return this;
}
// Add without checks
return this._iaddn(num);
};
BN.prototype._iaddn = function _iaddn (num) {
this.words[0] += num;
// Carry
for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
this.words[i] -= 0x4000000;
if (i === this.length - 1) {
this.words[i + 1] = 1;
} else {
this.words[i + 1]++;
}
}
this.length = Math.max(this.length, i + 1);
return this;
};
// Subtract plain number `num` from `this`
BN.prototype.isubn = function isubn (num) {
assert(typeof num === 'number');
assert(num < 0x4000000);
if (num < 0) return this.iaddn(-num);
if (this.negative !== 0) {
this.negative = 0;
this.iaddn(num);
this.negative = 1;
return this;
}
this.words[0] -= num;
if (this.length === 1 && this.words[0] < 0) {
this.words[0] = -this.words[0];
this.negative = 1;
} else {
// Carry
for (var i = 0; i < this.length && this.words[i] < 0; i++) {
this.words[i] += 0x4000000;
this.words[i + 1] -= 1;
}
}
return this.strip();
};
BN.prototype.addn = function addn (num) {
return this.clone().iaddn(num);
};
BN.prototype.subn = function subn (num) {
return this.clone().isubn(num);
};
BN.prototype.iabs = function iabs () {
this.negative = 0;
return this;
};
BN.prototype.abs = function abs () {
return this.clone().iabs();
};
BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
var len = num.length + shift;
var i;
this._expand(len);
var w;
var carry = 0;
for (i = 0; i < num.length; i++) {
w = (this.words[i + shift] | 0) + carry;
var right = (num.words[i] | 0) * mul;
w -= right & 0x3ffffff;
carry = (w >> 26) - ((right / 0x4000000) | 0);
this.words[i + shift] = w & 0x3ffffff;
}
for (; i < this.length - shift; i++) {
w = (this.words[i + shift] | 0) + carry;
carry = w >> 26;
this.words[i + shift] = w & 0x3ffffff;
}
if (carry === 0) return this.strip();
// Subtraction overflow
assert(carry === -1);
carry = 0;
for (i = 0; i < this.length; i++) {
w = -(this.words[i] | 0) + carry;
carry = w >> 26;
this.words[i] = w & 0x3ffffff;
}
this.negative = 1;
return this.strip();
};
BN.prototype._wordDiv = function _wordDiv (num, mode) {
var shift = this.length - num.length;
var a = this.clone();
var b = num;
// Normalize
var bhi = b.words[b.length - 1] | 0;
var bhiBits = this._countBits(bhi);
shift = 26 - bhiBits;
if (shift !== 0) {
b = b.ushln(shift);
a.iushln(shift);
bhi = b.words[b.length - 1] | 0;
}
// Initialize quotient
var m = a.length - b.length;
var q;
if (mode !== 'mod') {
q = new BN(null);
q.length = m + 1;
q.words = new Array(q.length);
for (var i = 0; i < q.length; i++) {
q.words[i] = 0;
}
}
var diff = a.clone()._ishlnsubmul(b, 1, m);
if (diff.negative === 0) {
a = diff;
if (q) {
q.words[m] = 1;
}
}
for (var j = m - 1; j >= 0; j--) {
var qj = (a.words[b.length + j] | 0) * 0x4000000 +
(a.words[b.length + j - 1] | 0);
// NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
// (0x7ffffff)
qj = Math.min((qj / bhi) | 0, 0x3ffffff);
a._ishlnsubmul(b, qj, j);
while (a.negative !== 0) {
qj--;
a.negative = 0;
a._ishlnsubmul(b, 1, j);
if (!a.isZero()) {
a.negative ^= 1;
}
}
if (q) {
q.words[j] = qj;
}
}
if (q) {
q.strip();
}
a.strip();
// Denormalize
if (mode !== 'div' && shift !== 0) {
a.iushrn(shift);
}
return {
div: q || null,
mod: a
};
};
// NOTE: 1) `mode` can be set to `mod` to request mod only,
// to `div` to request div only, or be absent to
// request both div & mod
// 2) `positive` is true if unsigned mod is requested
BN.prototype.divmod = function divmod (num, mode, positive) {
assert(!num.isZero());
if (this.isZero()) {
return {
div: new BN(0),
mod: new BN(0)
};
}
var div, mod, res;
if (this.negative !== 0 && num.negative === 0) {
res = this.neg().divmod(num, mode);
if (mode !== 'mod') {
div = res.div.neg();
}
if (mode !== 'div') {
mod = res.mod.neg();
if (positive && mod.negative !== 0) {
mod.iadd(num);
}
}
return {
div: div,
mod: mod
};
}
if (this.negative === 0 && num.negative !== 0) {
res = this.divmod(num.neg(), mode);
if (mode !== 'mod') {
div = res.div.neg();
}
return {
div: div,
mod: res.mod
};
}
if ((this.negative & num.negative) !== 0) {
res = this.neg().divmod(num.neg(), mode);
if (mode !== 'div') {
mod = res.mod.neg();
if (positive && mod.negative !== 0) {
mod.isub(num);
}
}
return {
div: res.div,
mod: mod
};
}
// Both numbers are positive at this point
// Strip both numbers to approximate shift value
if (num.length > this.length || this.cmp(num) < 0) {
return {
div: new BN(0),
mod: this
};
}
// Very short reduction
if (num.length === 1) {
if (mode === 'div') {
return {
div: this.divn(num.words[0]),
mod: null
};
}
if (mode === 'mod') {
return {
div: null,
mod: new BN(this.modn(num.words[0]))
};
}
return {
div: this.divn(num.words[0]),
mod: new BN(this.modn(num.words[0]))
};
}
return this._wordDiv(num, mode);
};
// Find `this` / `num`
BN.prototype.div = function div (num) {
return this.divmod(num, 'div', false).div;
};
// Find `this` % `num`
BN.prototype.mod = function mod (num) {
return this.divmod(num, 'mod', false).mod;
};
BN.prototype.umod = function umod (num) {
return this.divmod(num, 'mod', true).mod;
};
// Find Round(`this` / `num`)
BN.prototype.divRound = function divRound (num) {
var dm = this.divmod(num);
// Fast case - exact division
if (dm.mod.isZero()) return dm.div;
var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
var half = num.ushrn(1);
var r2 = num.andln(1);
var cmp = mod.cmp(half);
// Round down
if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
// Round up
return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
};
BN.prototype.modn = function modn (num) {
assert(num <= 0x3ffffff);
var p = (1 << 26) % num;
var acc = 0;
for (var i = this.length - 1; i >= 0; i--) {
acc = (p * acc + (this.words[i] | 0)) % num;
}
return acc;
};
// In-place division by number
BN.prototype.idivn = function idivn (num) {
assert(num <= 0x3ffffff);
var carry = 0;
for (var i = this.length - 1; i >= 0; i--) {
var w = (this.words[i] | 0) + carry * 0x4000000;
this.words[i] = (w / num) | 0;
carry = w % num;
}
return this.strip();
};
BN.prototype.divn = function divn (num) {
return this.clone().idivn(num);
};
BN.prototype.egcd = function egcd (p) {
assert(p.negative === 0);
assert(!p.isZero());
var x = this;
var y = p.clone();
if (x.negative !== 0) {
x = x.umod(p);
} else {
x = x.clone();
}
// A * x + B * y = x
var A = new BN(1);
var B = new BN(0);
// C * x + D * y = y
var C = new BN(0);
var D = new BN(1);
var g = 0;
while (x.isEven() && y.isEven()) {
x.iushrn(1);
y.iushrn(1);
++g;
}
var yp = y.clone();
var xp = x.clone();
while (!x.isZero()) {
for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
if (i > 0) {
x.iushrn(i);
while (i-- > 0) {
if (A.isOdd() || B.isOdd()) {
A.iadd(yp);
B.isub(xp);
}
A.iushrn(1);
B.iushrn(1);
}
}
for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
if (j > 0) {
y.iushrn(j);
while (j-- > 0) {
if (C.isOdd() || D.isOdd()) {
C.iadd(yp);
D.isub(xp);
}
C.iushrn(1);
D.iushrn(1);
}
}
if (x.cmp(y) >= 0) {
x.isub(y);
A.isub(C);
B.isub(D);
} else {
y.isub(x);
C.isub(A);
D.isub(B);
}
}
return {
a: C,
b: D,
gcd: y.iushln(g)
};
};
// This is reduced incarnation of the binary EEA
// above, designated to invert members of the
// _prime_ fields F(p) at a maximal speed
BN.prototype._invmp = function _invmp (p) {
assert(p.negative === 0);
assert(!p.isZero());
var a = this;
var b = p.clone();
if (a.negative !== 0) {
a = a.umod(p);
} else {
a = a.clone();
}
var x1 = new BN(1);
var x2 = new BN(0);
var delta = b.clone();
while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
if (i > 0) {
a.iushrn(i);
while (i-- > 0) {
if (x1.isOdd()) {
x1.iadd(delta);
}
x1.iushrn(1);
}
}
for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
if (j > 0) {
b.iushrn(j);
while (j-- > 0) {
if (x2.isOdd()) {
x2.iadd(delta);
}
x2.iushrn(1);
}
}
if (a.cmp(b) >= 0) {
a.isub(b);
x1.isub(x2);
} else {
b.isub(a);
x2.isub(x1);
}
}
var res;
if (a.cmpn(1) === 0) {
res = x1;
} else {
res = x2;
}
if (res.cmpn(0) < 0) {
res.iadd(p);
}
return res;
};
BN.prototype.gcd = function gcd (num) {
if (this.isZero()) return num.abs();
if (num.isZero()) return this.abs();
var a = this.clone();
var b = num.clone();
a.negative = 0;
b.negative = 0;
// Remove common factor of two
for (var shift = 0; a.isEven() && b.isEven(); shift++) {
a.iushrn(1);
b.iushrn(1);
}
do {
while (a.isEven()) {
a.iushrn(1);
}
while (b.isEven()) {
b.iushrn(1);
}
var r = a.cmp(b);
if (r < 0) {
// Swap `a` and `b` to make `a` always bigger than `b`
var t = a;
a = b;
b = t;
} else if (r === 0 || b.cmpn(1) === 0) {
break;
}
a.isub(b);
} while (true);
return b.iushln(shift);
};
// Invert number in the field F(num)
BN.prototype.invm = function invm (num) {
return this.egcd(num).a.umod(num);
};
BN.prototype.isEven = function isEven () {
return (this.words[0] & 1) === 0;
};
BN.prototype.isOdd = function isOdd () {
return (this.words[0] & 1) === 1;
};
// And first word and num
BN.prototype.andln = function andln (num) {
return this.words[0] & num;
};
// Increment at the bit position in-line
BN.prototype.bincn = function bincn (bit) {
assert(typeof bit === 'number');
var r = bit % 26;
var s = (bit - r) / 26;
var q = 1 << r;
// Fast case: bit is much higher than all existing words
if (this.length <= s) {
this._expand(s + 1);
this.words[s] |= q;
return this;
}
// Add bit and propagate, if needed
var carry = q;
for (var i = s; carry !== 0 && i < this.length; i++) {
var w = this.words[i] | 0;
w += carry;
carry = w >>> 26;
w &= 0x3ffffff;
this.words[i] = w;
}
if (carry !== 0) {
this.words[i] = carry;
this.length++;
}
return this;
};
BN.prototype.isZero = function isZero () {
return this.length === 1 && this.words[0] === 0;
};
BN.prototype.cmpn = function cmpn (num) {
var negative = num < 0;
if (this.negative !== 0 && !negative) return -1;
if (this.negative === 0 && negative) return 1;
this.strip();
var res;
if (this.length > 1) {
res = 1;
} else {
if (negative) {
num = -num;
}
assert(num <= 0x3ffffff, 'Number is too big');
var w = this.words[0] | 0;
res = w === num ? 0 : w < num ? -1 : 1;
}
if (this.negative !== 0) return -res | 0;
return res;
};
// Compare two numbers and return:
// 1 - if `this` > `num`
// 0 - if `this` == `num`
// -1 - if `this` < `num`
BN.prototype.cmp = function cmp (num) {
if (this.negative !== 0 && num.negative === 0) return -1;
if (this.negative === 0 && num.negative !== 0) return 1;
var res = this.ucmp(num);
if (this.negative !== 0) return -res | 0;
return res;
};
// Unsigned comparison
BN.prototype.ucmp = function ucmp (num) {
// At this point both numbers have the same sign
if (this.length > num.length) return 1;
if (this.length < num.length) return -1;
var res = 0;
for (var i = this.length - 1; i >= 0; i--) {
var a = this.words[i] | 0;
var b = num.words[i] | 0;
if (a === b) continue;
if (a < b) {
res = -1;
} else if (a > b) {
res = 1;
}
break;
}
return res;
};
BN.prototype.gtn = function gtn (num) {
return this.cmpn(num) === 1;
};
BN.prototype.gt = function gt (num) {
return this.cmp(num) === 1;
};
BN.prototype.gten = function gten (num) {
return this.cmpn(num) >= 0;
};
BN.prototype.gte = function gte (num) {
return this.cmp(num) >= 0;
};
BN.prototype.ltn = function ltn (num) {
return this.cmpn(num) === -1;
};
BN.prototype.lt = function lt (num) {
return this.cmp(num) === -1;
};
BN.prototype.lten = function lten (num) {
return this.cmpn(num) <= 0;
};
BN.prototype.lte = function lte (num) {
return this.cmp(num) <= 0;
};
BN.prototype.eqn = function eqn (num) {
return this.cmpn(num) === 0;
};
BN.prototype.eq = function eq (num) {
return this.cmp(num) === 0;
};
//
// A reduce context, could be using montgomery or something better, depending
// on the `m` itself.
//
BN.red = function red (num) {
return new Red(num);
};
BN.prototype.toRed = function toRed (ctx) {
assert(!this.red, 'Already a number in reduction context');
assert(this.negative === 0, 'red works only with positives');
return ctx.convertTo(this)._forceRed(ctx);
};
BN.prototype.fromRed = function fromRed () {
assert(this.red, 'fromRed works only with numbers in reduction context');
return this.red.convertFrom(this);
};
BN.prototype._forceRed = function _forceRed (ctx) {
this.red = ctx;
return this;
};
BN.prototype.forceRed = function forceRed (ctx) {
assert(!this.red, 'Already a number in reduction context');
return this._forceRed(ctx);
};
BN.prototype.redAdd = function redAdd (num) {
assert(this.red, 'redAdd works only with red numbers');
return this.red.add(this, num);
};
BN.prototype.redIAdd = function redIAdd (num) {
assert(this.red, 'redIAdd works only with red numbers');
return this.red.iadd(this, num);
};
BN.prototype.redSub = function redSub (num) {
assert(this.red, 'redSub works only with red numbers');
return this.red.sub(this, num);
};
BN.prototype.redISub = function redISub (num) {
assert(this.red, 'redISub works only with red numbers');
return this.red.isub(this, num);
};
BN.prototype.redShl = function redShl (num) {
assert(this.red, 'redShl works only with red numbers');
return this.red.shl(this, num);
};
BN.prototype.redMul = function redMul (num) {
assert(this.red, 'redMul works only with red numbers');
this.red._verify2(this, num);
return this.red.mul(this, num);
};
BN.prototype.redIMul = function redIMul (num) {
assert(this.red, 'redMul works only with red numbers');
this.red._verify2(this, num);
return this.red.imul(this, num);
};
BN.prototype.redSqr = function redSqr () {
assert(this.red, 'redSqr works only with red numbers');
this.red._verify1(this);
return this.red.sqr(this);
};
BN.prototype.redISqr = function redISqr () {
assert(this.red, 'redISqr works only with red numbers');
this.red._verify1(this);
return this.red.isqr(this);
};
// Square root over p
BN.prototype.redSqrt = function redSqrt () {
assert(this.red, 'redSqrt works only with red numbers');
this.red._verify1(this);
return this.red.sqrt(this);
};
BN.prototype.redInvm = function redInvm () {
assert(this.red, 'redInvm works only with red numbers');
this.red._verify1(this);
return this.red.invm(this);
};
// Return negative clone of `this` % `red modulo`
BN.prototype.redNeg = function redNeg () {
assert(this.red, 'redNeg works only with red numbers');
this.red._verify1(this);
return this.red.neg(this);
};
BN.prototype.redPow = function redPow (num) {
assert(this.red && !num.red, 'redPow(normalNum)');
this.red._verify1(this);
return this.red.pow(this, num);
};
// Prime numbers with efficient reduction
var primes = {
k256: null,
p224: null,
p192: null,
p25519: null
};
// Pseudo-Mersenne prime
function MPrime (name, p) {
// P = 2 ^ N - K
this.name = name;
this.p = new BN(p, 16);
this.n = this.p.bitLength();
this.k = new BN(1).iushln(this.n).isub(this.p);
this.tmp = this._tmp();
}
MPrime.prototype._tmp = function _tmp () {
var tmp = new BN(null);
tmp.words = new Array(Math.ceil(this.n / 13));
return tmp;
};
MPrime.prototype.ireduce = function ireduce (num) {
// Assumes that `num` is less than `P^2`
// num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
var r = num;
var rlen;
do {
this.split(r, this.tmp);
r = this.imulK(r);
r = r.iadd(this.tmp);
rlen = r.bitLength();
} while (rlen > this.n);
var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
if (cmp === 0) {
r.words[0] = 0;
r.length = 1;
} else if (cmp > 0) {
r.isub(this.p);
} else {
r.strip();
}
return r;
};
MPrime.prototype.split = function split (input, out) {
input.iushrn(this.n, 0, out);
};
MPrime.prototype.imulK = function imulK (num) {
return num.imul(this.k);
};
function K256 () {
MPrime.call(
this,
'k256',
'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
}
inherits(K256, MPrime);
K256.prototype.split = function split (input, output) {
// 256 = 9 * 26 + 22
var mask = 0x3fffff;
var outLen = Math.min(input.length, 9);
for (var i = 0; i < outLen; i++) {
output.words[i] = input.words[i];
}
output.length = outLen;
if (input.length <= 9) {
input.words[0] = 0;
input.length = 1;
return;
}
// Shift by 9 limbs
var prev = input.words[9];
output.words[output.length++] = prev & mask;
for (i = 10; i < input.length; i++) {
var next = input.words[i] | 0;
input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
prev = next;
}
prev >>>= 22;
input.words[i - 10] = prev;
if (prev === 0 && input.length > 10) {
input.length -= 10;
} else {
input.length -= 9;
}
};
K256.prototype.imulK = function imulK (num) {
// K = 0x1000003d1 = [ 0x40, 0x3d1 ]
num.words[num.length] = 0;
num.words[num.length + 1] = 0;
num.length += 2;
// bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
var lo = 0;
for (var i = 0; i < num.length; i++) {
var w = num.words[i] | 0;
lo += w * 0x3d1;
num.words[i] = lo & 0x3ffffff;
lo = w * 0x40 + ((lo / 0x4000000) | 0);
}
// Fast length reduction
if (num.words[num.length - 1] === 0) {
num.length--;
if (num.words[num.length - 1] === 0) {
num.length--;
}
}
return num;
};
function P224 () {
MPrime.call(
this,
'p224',
'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
}
inherits(P224, MPrime);
function P192 () {
MPrime.call(
this,
'p192',
'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
}
inherits(P192, MPrime);
function P25519 () {
// 2 ^ 255 - 19
MPrime.call(
this,
'25519',
'7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
}
inherits(P25519, MPrime);
P25519.prototype.imulK = function imulK (num) {
// K = 0x13
var carry = 0;
for (var i = 0; i < num.length; i++) {
var hi = (num.words[i] | 0) * 0x13 + carry;
var lo = hi & 0x3ffffff;
hi >>>= 26;
num.words[i] = lo;
carry = hi;
}
if (carry !== 0) {
num.words[num.length++] = carry;
}
return num;
};
// Exported mostly for testing purposes, use plain name instead
BN._prime = function prime (name) {
// Cached version of prime
if (primes[name]) return primes[name];
var prime;
if (name === 'k256') {
prime = new K256();
} else if (name === 'p224') {
prime = new P224();
} else if (name === 'p192') {
prime = new P192();
} else if (name === 'p25519') {
prime = new P25519();
} else {
throw new Error('Unknown prime ' + name);
}
primes[name] = prime;
return prime;
};
//
// Base reduction engine
//
function Red (m) {
if (typeof m === 'string') {
var prime = BN._prime(m);
this.m = prime.p;
this.prime = prime;
} else {
assert(m.gtn(1), 'modulus must be greater than 1');
this.m = m;
this.prime = null;
}
}
Red.prototype._verify1 = function _verify1 (a) {
assert(a.negative === 0, 'red works only with positives');
assert(a.red, 'red works only with red numbers');
};
Red.prototype._verify2 = function _verify2 (a, b) {
assert((a.negative | b.negative) === 0, 'red works only with positives');
assert(a.red && a.red === b.red,
'red works only with red numbers');
};
Red.prototype.imod = function imod (a) {
if (this.prime) return this.prime.ireduce(a)._forceRed(this);
return a.umod(this.m)._forceRed(this);
};
Red.prototype.neg = function neg (a) {
if (a.isZero()) {
return a.clone();
}
return this.m.sub(a)._forceRed(this);
};
Red.prototype.add = function add (a, b) {
this._verify2(a, b);
var res = a.add(b);
if (res.cmp(this.m) >= 0) {
res.isub(this.m);
}
return res._forceRed(this);
};
Red.prototype.iadd = function iadd (a, b) {
this._verify2(a, b);
var res = a.iadd(b);
if (res.cmp(this.m) >= 0) {
res.isub(this.m);
}
return res;
};
Red.prototype.sub = function sub (a, b) {
this._verify2(a, b);
var res = a.sub(b);
if (res.cmpn(0) < 0) {
res.iadd(this.m);
}
return res._forceRed(this);
};
Red.prototype.isub = function isub (a, b) {
this._verify2(a, b);
var res = a.isub(b);
if (res.cmpn(0) < 0) {
res.iadd(this.m);
}
return res;
};
Red.prototype.shl = function shl (a, num) {
this._verify1(a);
return this.imod(a.ushln(num));
};
Red.prototype.imul = function imul (a, b) {
this._verify2(a, b);
return this.imod(a.imul(b));
};
Red.prototype.mul = function mul (a, b) {
this._verify2(a, b);
return this.imod(a.mul(b));
};
Red.prototype.isqr = function isqr (a) {
return this.imul(a, a.clone());
};
Red.prototype.sqr = function sqr (a) {
return this.mul(a, a);
};
Red.prototype.sqrt = function sqrt (a) {
if (a.isZero()) return a.clone();
var mod3 = this.m.andln(3);
assert(mod3 % 2 === 1);
// Fast case
if (mod3 === 3) {
var pow = this.m.add(new BN(1)).iushrn(2);
return this.pow(a, pow);
}
// Tonelli-Shanks algorithm (Totally unoptimized and slow)
//
// Find Q and S, that Q * 2 ^ S = (P - 1)
var q = this.m.subn(1);
var s = 0;
while (!q.isZero() && q.andln(1) === 0) {
s++;
q.iushrn(1);
}
assert(!q.isZero());
var one = new BN(1).toRed(this);
var nOne = one.redNeg();
// Find quadratic non-residue
// NOTE: Max is such because of generalized Riemann hypothesis.
var lpow = this.m.subn(1).iushrn(1);
var z = this.m.bitLength();
z = new BN(2 * z * z).toRed(this);
while (this.pow(z, lpow).cmp(nOne) !== 0) {
z.redIAdd(nOne);
}
var c = this.pow(z, q);
var r = this.pow(a, q.addn(1).iushrn(1));
var t = this.pow(a, q);
var m = s;
while (t.cmp(one) !== 0) {
var tmp = t;
for (var i = 0; tmp.cmp(one) !== 0; i++) {
tmp = tmp.redSqr();
}
assert(i < m);
var b = this.pow(c, new BN(1).iushln(m - i - 1));
r = r.redMul(b);
c = b.redSqr();
t = t.redMul(c);
m = i;
}
return r;
};
Red.prototype.invm = function invm (a) {
var inv = a._invmp(this.m);
if (inv.negative !== 0) {
inv.negative = 0;
return this.imod(inv).redNeg();
} else {
return this.imod(inv);
}
};
Red.prototype.pow = function pow (a, num) {
if (num.isZero()) return new BN(1).toRed(this);
if (num.cmpn(1) === 0) return a.clone();
var windowSize = 4;
var wnd = new Array(1 << windowSize);
wnd[0] = new BN(1).toRed(this);
wnd[1] = a;
for (var i = 2; i < wnd.length; i++) {
wnd[i] = this.mul(wnd[i - 1], a);
}
var res = wnd[0];
var current = 0;
var currentLen = 0;
var start = num.bitLength() % 26;
if (start === 0) {
start = 26;
}
for (i = num.length - 1; i >= 0; i--) {
var word = num.words[i];
for (var j = start - 1; j >= 0; j--) {
var bit = (word >> j) & 1;
if (res !== wnd[0]) {
res = this.sqr(res);
}
if (bit === 0 && current === 0) {
currentLen = 0;
continue;
}
current <<= 1;
current |= bit;
currentLen++;
if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
res = this.mul(res, wnd[current]);
currentLen = 0;
current = 0;
}
start = 26;
}
return res;
};
Red.prototype.convertTo = function convertTo (num) {
var r = num.umod(this.m);
return r === num ? r.clone() : r;
};
Red.prototype.convertFrom = function convertFrom (num) {
var res = num.clone();
res.red = null;
return res;
};
//
// Montgomery method engine
//
BN.mont = function mont (num) {
return new Mont(num);
};
function Mont (m) {
Red.call(this, m);
this.shift = this.m.bitLength();
if (this.shift % 26 !== 0) {
this.shift += 26 - (this.shift % 26);
}
this.r = new BN(1).iushln(this.shift);
this.r2 = this.imod(this.r.sqr());
this.rinv = this.r._invmp(this.m);
this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
this.minv = this.minv.umod(this.r);
this.minv = this.r.sub(this.minv);
}
inherits(Mont, Red);
Mont.prototype.convertTo = function convertTo (num) {
return this.imod(num.ushln(this.shift));
};
Mont.prototype.convertFrom = function convertFrom (num) {
var r = this.imod(num.mul(this.rinv));
r.red = null;
return r;
};
Mont.prototype.imul = function imul (a, b) {
if (a.isZero() || b.isZero()) {
a.words[0] = 0;
a.length = 1;
return a;
}
var t = a.imul(b);
var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
var u = t.isub(c).iushrn(this.shift);
var res = u;
if (u.cmp(this.m) >= 0) {
res = u.isub(this.m);
} else if (u.cmpn(0) < 0) {
res = u.iadd(this.m);
}
return res._forceRed(this);
};
Mont.prototype.mul = function mul (a, b) {
if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
var t = a.mul(b);
var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
var u = t.isub(c).iushrn(this.shift);
var res = u;
if (u.cmp(this.m) >= 0) {
res = u.isub(this.m);
} else if (u.cmpn(0) < 0) {
res = u.iadd(this.m);
}
return res._forceRed(this);
};
Mont.prototype.invm = function invm (a) {
// (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
var res = this.imod(a._invmp(this.m).mul(this.r2));
return res._forceRed(this);
};
})(typeof module === 'undefined' || module, this);
},{"buffer":124}],123:[function(require,module,exports){
var r;
module.exports = function rand(len) {
if (!r)
r = new Rand(null);
return r.generate(len);
};
function Rand(rand) {
this.rand = rand;
}
module.exports.Rand = Rand;
Rand.prototype.generate = function generate(len) {
return this._rand(len);
};
// Emulate crypto API using randy
Rand.prototype._rand = function _rand(n) {
if (this.rand.getBytes)
return this.rand.getBytes(n);
var res = new Uint8Array(n);
for (var i = 0; i < res.length; i++)
res[i] = this.rand.getByte();
return res;
};
if (typeof self === 'object') {
if (self.crypto && self.crypto.getRandomValues) {
// Modern browsers
Rand.prototype._rand = function _rand(n) {
var arr = new Uint8Array(n);
self.crypto.getRandomValues(arr);
return arr;
};
} else if (self.msCrypto && self.msCrypto.getRandomValues) {
// IE
Rand.prototype._rand = function _rand(n) {
var arr = new Uint8Array(n);
self.msCrypto.getRandomValues(arr);
return arr;
};
// Safari's WebWorkers do not have `crypto`
} else if (typeof window === 'object') {
// Old junk
Rand.prototype._rand = function() {
throw new Error('Not implemented yet');
};
}
} else {
// Node.js or Web worker with no crypto support
try {
var crypto = require('crypto');
if (typeof crypto.randomBytes !== 'function')
throw new Error('Not supported');
Rand.prototype._rand = function _rand(n) {
return crypto.randomBytes(n);
};
} catch (e) {
}
}
},{"crypto":124}],124:[function(require,module,exports){
},{}],125:[function(require,module,exports){
// based on the aes implimentation in triple sec
// https://github.com/keybase/triplesec
// which is in turn based on the one from crypto-js
// https://code.google.com/p/crypto-js/
var Buffer = require('safe-buffer').Buffer
function asUInt32Array (buf) {
if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
var len = (buf.length / 4) | 0
var out = new Array(len)
for (var i = 0; i < len; i++) {
out[i] = buf.readUInt32BE(i * 4)
}
return out
}
function scrubVec (v) {
for (var i = 0; i < v.length; v++) {
v[i] = 0
}
}
function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {
var SUB_MIX0 = SUB_MIX[0]
var SUB_MIX1 = SUB_MIX[1]
var SUB_MIX2 = SUB_MIX[2]
var SUB_MIX3 = SUB_MIX[3]
var s0 = M[0] ^ keySchedule[0]
var s1 = M[1] ^ keySchedule[1]
var s2 = M[2] ^ keySchedule[2]
var s3 = M[3] ^ keySchedule[3]
var t0, t1, t2, t3
var ksRow = 4
for (var round = 1; round < nRounds; round++) {
t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]
t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]
t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]
t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++]
s0 = t0
s1 = t1
s2 = t2
s3 = t3
}
t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
t0 = t0 >>> 0
t1 = t1 >>> 0
t2 = t2 >>> 0
t3 = t3 >>> 0
return [t0, t1, t2, t3]
}
// AES constants
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
var G = (function () {
// Compute double table
var d = new Array(256)
for (var j = 0; j < 256; j++) {
if (j < 128) {
d[j] = j << 1
} else {
d[j] = (j << 1) ^ 0x11b
}
}
var SBOX = []
var INV_SBOX = []
var SUB_MIX = [[], [], [], []]
var INV_SUB_MIX = [[], [], [], []]
// Walk GF(2^8)
var x = 0
var xi = 0
for (var i = 0; i < 256; ++i) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
SBOX[x] = sx
INV_SBOX[sx] = x
// Compute multiplication
var x2 = d[x]
var x4 = d[x2]
var x8 = d[x4]
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100)
SUB_MIX[0][x] = (t << 24) | (t >>> 8)
SUB_MIX[1][x] = (t << 16) | (t >>> 16)
SUB_MIX[2][x] = (t << 8) | (t >>> 24)
SUB_MIX[3][x] = t
// Compute inv sub bytes, inv mix columns tables
t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
INV_SUB_MIX[3][sx] = t
if (x === 0) {
x = xi = 1
} else {
x = x2 ^ d[d[d[x8 ^ x2]]]
xi ^= d[d[xi]]
}
}
return {
SBOX: SBOX,
INV_SBOX: INV_SBOX,
SUB_MIX: SUB_MIX,
INV_SUB_MIX: INV_SUB_MIX
}
})()
function AES (key) {
this._key = asUInt32Array(key)
this._reset()
}
AES.blockSize = 4 * 4
AES.keySize = 256 / 8
AES.prototype.blockSize = AES.blockSize
AES.prototype.keySize = AES.keySize
AES.prototype._reset = function () {
var keyWords = this._key
var keySize = keyWords.length
var nRounds = keySize + 6
var ksRows = (nRounds + 1) * 4
var keySchedule = []
for (var k = 0; k < keySize; k++) {
keySchedule[k] = keyWords[k]
}
for (k = keySize; k < ksRows; k++) {
var t = keySchedule[k - 1]
if (k % keySize === 0) {
t = (t << 8) | (t >>> 24)
t =
(G.SBOX[t >>> 24] << 24) |
(G.SBOX[(t >>> 16) & 0xff] << 16) |
(G.SBOX[(t >>> 8) & 0xff] << 8) |
(G.SBOX[t & 0xff])
t ^= RCON[(k / keySize) | 0] << 24
} else if (keySize > 6 && k % keySize === 4) {
t =
(G.SBOX[t >>> 24] << 24) |
(G.SBOX[(t >>> 16) & 0xff] << 16) |
(G.SBOX[(t >>> 8) & 0xff] << 8) |
(G.SBOX[t & 0xff])
}
keySchedule[k] = keySchedule[k - keySize] ^ t
}
var invKeySchedule = []
for (var ik = 0; ik < ksRows; ik++) {
var ksR = ksRows - ik
var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]
if (ik < 4 || ksR <= 4) {
invKeySchedule[ik] = tt
} else {
invKeySchedule[ik] =
G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^
G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^
G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^
G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]
}
}
this._nRounds = nRounds
this._keySchedule = keySchedule
this._invKeySchedule = invKeySchedule
}
AES.prototype.encryptBlockRaw = function (M) {
M = asUInt32Array(M)
return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
}
AES.prototype.encryptBlock = function (M) {
var out = this.encryptBlockRaw(M)
var buf = Buffer.allocUnsafe(16)
buf.writeUInt32BE(out[0], 0)
buf.writeUInt32BE(out[1], 4)
buf.writeUInt32BE(out[2], 8)
buf.writeUInt32BE(out[3], 12)
return buf
}
AES.prototype.decryptBlock = function (M) {
M = asUInt32Array(M)
// swap
var m1 = M[1]
M[1] = M[3]
M[3] = m1
var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds)
var buf = Buffer.allocUnsafe(16)
buf.writeUInt32BE(out[0], 0)
buf.writeUInt32BE(out[3], 4)
buf.writeUInt32BE(out[2], 8)
buf.writeUInt32BE(out[1], 12)
return buf
}
AES.prototype.scrub = function () {
scrubVec(this._keySchedule)
scrubVec(this._invKeySchedule)
scrubVec(this._key)
}
module.exports.AES = AES
},{"safe-buffer":381}],126:[function(require,module,exports){
var aes = require('./aes')
var Buffer = require('safe-buffer').Buffer
var Transform = require('cipher-base')
var inherits = require('inherits')
var GHASH = require('./ghash')
var xor = require('buffer-xor')
var incr32 = require('./incr32')
function xorTest (a, b) {
var out = 0
if (a.length !== b.length) out++
var len = Math.min(a.length, b.length)
for (var i = 0; i < len; ++i) {
out += (a[i] ^ b[i])
}
return out
}
function calcIv (self, iv, ck) {
if (iv.length === 12) {
self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])])
return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])])
}
var ghash = new GHASH(ck)
var len = iv.length
var toPad = len % 16
ghash.update(iv)
if (toPad) {
toPad = 16 - toPad
ghash.update(Buffer.alloc(toPad, 0))
}
ghash.update(Buffer.alloc(8, 0))
var ivBits = len * 8
var tail = Buffer.alloc(8)
tail.writeUIntBE(ivBits, 0, 8)
ghash.update(tail)
self._finID = ghash.state
var out = Buffer.from(self._finID)
incr32(out)
return out
}
function StreamCipher (mode, key, iv, decrypt) {
Transform.call(this)
var h = Buffer.alloc(4, 0)
this._cipher = new aes.AES(key)
var ck = this._cipher.encryptBlock(h)
this._ghash = new GHASH(ck)
iv = calcIv(this, iv, ck)
this._prev = Buffer.from(iv)
this._cache = Buffer.allocUnsafe(0)
this._secCache = Buffer.allocUnsafe(0)
this._decrypt = decrypt
this._alen = 0
this._len = 0
this._mode = mode
this._authTag = null
this._called = false
}
inherits(StreamCipher, Transform)
StreamCipher.prototype._update = function (chunk) {
if (!this._called && this._alen) {
var rump = 16 - (this._alen % 16)
if (rump < 16) {
rump = Buffer.alloc(rump, 0)
this._ghash.update(rump)
}
}
this._called = true
var out = this._mode.encrypt(this, chunk)
if (this._decrypt) {
this._ghash.update(chunk)
} else {
this._ghash.update(out)
}
this._len += chunk.length
return out
}
StreamCipher.prototype._final = function () {
if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data')
var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data')
this._authTag = tag
this._cipher.scrub()
}
StreamCipher.prototype.getAuthTag = function getAuthTag () {
if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state')
return this._authTag
}
StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state')
this._authTag = tag
}
StreamCipher.prototype.setAAD = function setAAD (buf) {
if (this._called) throw new Error('Attempting to set AAD in unsupported state')
this._ghash.update(buf)
this._alen += buf.length
}
module.exports = StreamCipher
},{"./aes":125,"./ghash":130,"./incr32":131,"buffer-xor":156,"cipher-base":160,"inherits":287,"safe-buffer":381}],127:[function(require,module,exports){
var ciphers = require('./encrypter')
var deciphers = require('./decrypter')
var modes = require('./modes/list.json')
function getCiphers () {
return Object.keys(modes)
}
exports.createCipher = exports.Cipher = ciphers.createCipher
exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
exports.createDecipher = exports.Decipher = deciphers.createDecipher
exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
exports.listCiphers = exports.getCiphers = getCiphers
},{"./decrypter":128,"./encrypter":129,"./modes/list.json":139}],128:[function(require,module,exports){
var AuthCipher = require('./authCipher')
var Buffer = require('safe-buffer').Buffer
var MODES = require('./modes')
var StreamCipher = require('./streamCipher')
var Transform = require('cipher-base')
var aes = require('./aes')
var ebtk = require('evp_bytestokey')
var inherits = require('inherits')
function Decipher (mode, key, iv) {
Transform.call(this)
this._cache = new Splitter()
this._last = void 0
this._cipher = new aes.AES(key)
this._prev = Buffer.from(iv)
this._mode = mode
this._autopadding = true
}
inherits(Decipher, Transform)
Decipher.prototype._update = function (data) {
this._cache.add(data)
var chunk
var thing
var out = []
while ((chunk = this._cache.get(this._autopadding))) {
thing = this._mode.decrypt(this, chunk)
out.push(thing)
}
return Buffer.concat(out)
}
Decipher.prototype._final = function () {
var chunk = this._cache.flush()
if (this._autopadding) {
return unpad(this._mode.decrypt(this, chunk))
} else if (chunk) {
throw new Error('data not multiple of block length')
}
}
Decipher.prototype.setAutoPadding = function (setTo) {
this._autopadding = !!setTo
return this
}
function Splitter () {
this.cache = Buffer.allocUnsafe(0)
}
Splitter.prototype.add = function (data) {
this.cache = Buffer.concat([this.cache, data])
}
Splitter.prototype.get = function (autoPadding) {
var out
if (autoPadding) {
if (this.cache.length > 16) {
out = this.cache.slice(0, 16)
this.cache = this.cache.slice(16)
return out
}
} else {
if (this.cache.length >= 16) {
out = this.cache.slice(0, 16)
this.cache = this.cache.slice(16)
return out
}
}
return null
}
Splitter.prototype.flush = function () {
if (this.cache.length) return this.cache
}
function unpad (last) {
var padded = last[15]
var i = -1
while (++i < padded) {
if (last[(i + (16 - padded))] !== padded) {
throw new Error('unable to decrypt data')
}
}
if (padded === 16) return
return last.slice(0, 16 - padded)
}
function createDecipheriv (suite, password, iv) {
var config = MODES[suite.toLowerCase()]
if (!config) throw new TypeError('invalid suite type')
if (typeof iv === 'string') iv = Buffer.from(iv)
if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
if (typeof password === 'string') password = Buffer.from(password)
if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
if (config.type === 'stream') {
return new StreamCipher(config.module, password, iv, true)
} else if (config.type === 'auth') {
return new AuthCipher(config.module, password, iv, true)
}
return new Decipher(config.module, password, iv)
}
function createDecipher (suite, password) {
var config = MODES[suite.toLowerCase()]
if (!config) throw new TypeError('invalid suite type')
var keys = ebtk(password, false, config.key, config.iv)
return createDecipheriv(suite, keys.key, keys.iv)
}
exports.createDecipher = createDecipher
exports.createDecipheriv = createDecipheriv
},{"./aes":125,"./authCipher":126,"./modes":138,"./streamCipher":141,"cipher-base":160,"evp_bytestokey":238,"inherits":287,"safe-buffer":381}],129:[function(require,module,exports){
var MODES = require('./modes')
var AuthCipher = require('./authCipher')
var Buffer = require('safe-buffer').Buffer
var StreamCipher = require('./streamCipher')
var Transform = require('cipher-base')
var aes = require('./aes')
var ebtk = require('evp_bytestokey')
var inherits = require('inherits')
function Cipher (mode, key, iv) {
Transform.call(this)
this._cache = new Splitter()
this._cipher = new aes.AES(key)
this._prev = Buffer.from(iv)
this._mode = mode
this._autopadding = true
}
inherits(Cipher, Transform)
Cipher.prototype._update = function (data) {
this._cache.add(data)
var chunk
var thing
var out = []
while ((chunk = this._cache.get())) {
thing = this._mode.encrypt(this, chunk)
out.push(thing)
}
return Buffer.concat(out)
}
var PADDING = Buffer.alloc(16, 0x10)
Cipher.prototype._final = function () {
var chunk = this._cache.flush()
if (this._autopadding) {
chunk = this._mode.encrypt(this, chunk)
this._cipher.scrub()
return chunk
}
if (!chunk.equals(PADDING)) {
this._cipher.scrub()
throw new Error('data not multiple of block length')
}
}
Cipher.prototype.setAutoPadding = function (setTo) {
this._autopadding = !!setTo
return this
}
function Splitter () {
this.cache = Buffer.allocUnsafe(0)
}
Splitter.prototype.add = function (data) {
this.cache = Buffer.concat([this.cache, data])
}
Splitter.prototype.get = function () {
if (this.cache.length > 15) {
var out = this.cache.slice(0, 16)
this.cache = this.cache.slice(16)
return out
}
return null
}
Splitter.prototype.flush = function () {
var len = 16 - this.cache.length
var padBuff = Buffer.allocUnsafe(len)
var i = -1
while (++i < len) {
padBuff.writeUInt8(len, i)
}
return Buffer.concat([this.cache, padBuff])
}
function createCipheriv (suite, password, iv) {
var config = MODES[suite.toLowerCase()]
if (!config) throw new TypeError('invalid suite type')
if (typeof password === 'string') password = Buffer.from(password)
if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
if (typeof iv === 'string') iv = Buffer.from(iv)
if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
if (config.type === 'stream') {
return new StreamCipher(config.module, password, iv)
} else if (config.type === 'auth') {
return new AuthCipher(config.module, password, iv)
}
return new Cipher(config.module, password, iv)
}
function createCipher (suite, password) {
var config = MODES[suite.toLowerCase()]
if (!config) throw new TypeError('invalid suite type')
var keys = ebtk(password, false, config.key, config.iv)
return createCipheriv(suite, keys.key, keys.iv)
}
exports.createCipheriv = createCipheriv
exports.createCipher = createCipher
},{"./aes":125,"./authCipher":126,"./modes":138,"./streamCipher":141,"cipher-base":160,"evp_bytestokey":238,"inherits":287,"safe-buffer":381}],130:[function(require,module,exports){
var Buffer = require('safe-buffer').Buffer
var ZEROES = Buffer.alloc(16, 0)
function toArray (buf) {
return [
buf.readUInt32BE(0),
buf.readUInt32BE(4),
buf.readUInt32BE(8),
buf.readUInt32BE(12)
]
}
function fromArray (out) {
var buf = Buffer.allocUnsafe(16)
buf.writeUInt32BE(out[0] >>> 0, 0)
buf.writeUInt32BE(out[1] >>> 0, 4)
buf.writeUInt32BE(out[2] >>> 0, 8)
buf.writeUInt32BE(out[3] >>> 0, 12)
return buf
}
function GHASH (key) {
this.h = key
this.state = Buffer.alloc(16, 0)
this.cache = Buffer.allocUnsafe(0)
}
// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
// by Juho Vähä-Herttua
GHASH.prototype.ghash = function (block) {
var i = -1
while (++i < block.length) {
this.state[i] ^= block[i]
}
this._multiply()
}
GHASH.prototype._multiply = function () {
var Vi = toArray(this.h)
var Zi = [0, 0, 0, 0]
var j, xi, lsbVi
var i = -1
while (++i < 128) {
xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0
if (xi) {
// Z_i+1 = Z_i ^ V_i
Zi[0] ^= Vi[0]
Zi[1] ^= Vi[1]
Zi[2] ^= Vi[2]
Zi[3] ^= Vi[3]
}
// Store the value of LSB(V_i)
lsbVi = (Vi[3] & 1) !== 0
// V_i+1 = V_i >> 1
for (j = 3; j > 0; j--) {
Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
}
Vi[0] = Vi[0] >>> 1
// If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
if (lsbVi) {
Vi[0] = Vi[0] ^ (0xe1 << 24)
}
}
this.state = fromArray(Zi)
}
GHASH.prototype.update = function (buf) {
this.cache = Buffer.concat([this.cache, buf])
var chunk
while (this.cache.length >= 16) {
chunk = this.cache.slice(0, 16)
this.cache = this.cache.slice(16)
this.ghash(chunk)
}
}
GHASH.prototype.final = function (abl, bl) {
if (this.cache.length) {
this.ghash(Buffer.concat([this.cache, ZEROES], 16))
}
this.ghash(fromArray([0, abl, 0, bl]))
return this.state
}
module.exports = GHASH
},{"safe-buffer":381}],131:[function(require,module,exports){
function incr32 (iv) {
var len = iv.length
var item
while (len--) {
item = iv.readUInt8(len)
if (item === 255) {
iv.writeUInt8(0, len)
} else {
item++
iv.writeUInt8(item, len)
break
}
}
}
module.exports = incr32
},{}],132:[function(require,module,exports){
var xor = require('buffer-xor')
exports.encrypt = function (self, block) {
var data = xor(block, self._prev)
self._prev = self._cipher.encryptBlock(data)
return self._prev
}
exports.decrypt = function (self, block) {
var pad = self._prev
self._prev = block
var out = self._cipher.decryptBlock(block)
return xor(out, pad)
}
},{"buffer-xor":156}],133:[function(require,module,exports){
var Buffer = require('safe-buffer').Buffer
var xor = require('buffer-xor')
function encryptStart (self, data, decrypt) {
var len = data.length
var out = xor(data, self._cache)
self._cache = self._cache.slice(len)
self._prev = Buffer.concat([self._prev, decrypt ? data : out])
return out
}
exports.encrypt = function (self, data, decrypt) {
var out = Buffer.allocUnsafe(0)
var len
while (data.length) {
if (self._cache.length === 0) {
self._cache = self._cipher.encryptBlock(self._prev)
self._prev = Buffer.allocUnsafe(0)
}
if (self._cache.length <= data.length) {
len = self._cache.length
out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
data = data.slice(len)
} else {
out = Buffer.concat([out, encryptStart(self, data, decrypt)])
break
}
}
return out
}
},{"buffer-xor":156,"safe-buffer":381}],134:[function(require,module,exports){
var Buffer = require('safe-buffer').Buffer
function encryptByte (self, byteParam, decrypt) {
var pad
var i = -1
var len = 8
var out = 0
var bit, value
while (++i < len) {
pad = self._cipher.encryptBlock(self._prev)
bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
value = pad[0] ^ bit
out += ((value & 0x80) >> (i % 8))
self._prev = shiftIn(self._prev, decrypt ? bit : value)
}
return out
}
function shiftIn (buffer, value) {
var len = buffer.length
var i = -1
var out = Buffer.allocUnsafe(buffer.length)
buffer = Buffer.concat([buffer, Buffer.from([value])])
while (++i < len) {
out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
}
return out
}
exports.encrypt = function (self, chunk, decrypt) {
var len = chunk.length
var out = Buffer.allocUnsafe(len)
var i = -1
while (++i < len) {
out[i] = encryptByte(self, chunk[i], decrypt)
}
return out
}
},{"safe-buffer":381}],135:[function(require,module,exports){
var Buffer = require('safe-buffer').Buffer
function encryptByte (self, byteParam, decrypt) {
var pad = self._cipher.encryptBlock(self._prev)
var out = pad[0] ^ byteParam
self._prev = Buffer.concat([
self._prev.slice(1),
Buffer.from([decrypt ? byteParam : out])
])
return out
}
exports.encrypt = function (self, chunk, decrypt) {
var len = chunk.length
var out = Buffer.allocUnsafe(len)
var i = -1
while (++i < len) {
out[i] = encryptByte(self, chunk[i], decrypt)
}
return out
}
},{"safe-buffer":381}],136:[function(require,module,exports){
var xor = require('buffer-xor')
var Buffer = require('safe-buffer').Buffer
var incr32 = require('../incr32')
function getBlock (self) {
var out = self._cipher.encryptBlockRaw(self._prev)
incr32(self._prev)
return out
}
var blockSize = 16
exports.encrypt = function (self, chunk) {
var chunkNum = Math.ceil(chunk.length / blockSize)
var start = self._cache.length
self._cache = Buffer.concat([
self._cache,
Buffer.allocUnsafe(chunkNum * blockSize)
])
for (var i = 0; i < chunkNum; i++) {
var out = getBlock(self)
var offset = start + i * blockSize
self._cache.writeUInt32BE(out[0], offset + 0)
self._cache.writeUInt32BE(out[1], offset + 4)
self._cache.writeUInt32BE(out[2], offset + 8)
self._cache.writeUInt32BE(out[3], offset + 12)
}
var pad = self._cache.slice(0, chunk.length)
self._cache = self._cache.slice(chunk.length)
return xor(chunk, pad)
}
},{"../incr32":131,"buffer-xor":156,"safe-buffer":381}],137:[function(require,module,exports){
exports.encrypt = function (self, block) {
return self._cipher.encryptBlock(block)
}
exports.decrypt = function (self, block) {
return self._cipher.decryptBlock(block)
}
},{}],138:[function(require,module,exports){
var modeModules = {
ECB: require('./ecb'),
CBC: require('./cbc'),
CFB: require('./cfb'),
CFB8: require('./cfb8'),
CFB1: require('./cfb1'),
OFB: require('./ofb'),
CTR: require('./ctr'),
GCM: require('./ctr')
}
var modes = require('./list.json')
for (var key in modes) {
modes[key].module = modeModules[modes[key].mode]
}
module.exports = modes
},{"./cbc":132,"./cfb":133,"./cfb1":134,"./cfb8":135,"./ctr":136,"./ecb":137,"./list.json":139,"./ofb":140}],139:[function(require,module,exports){
module.exports={
"aes-128-ecb": {
"cipher": "AES",
"key": 128,
"iv": 0,
"mode": "ECB",
"type": "block"
},
"aes-192-ecb": {
"cipher": "AES",
"key": 192,
"iv": 0,
"mode": "ECB",
"type": "block"
},
"aes-256-ecb": {
"cipher": "AES",
"key": 256,
"iv": 0,
"mode": "ECB",
"type": "block"
},
"aes-128-cbc": {
"cipher": "AES",
"key": 128,
"iv": 16,
"mode": "CBC",
"type": "block"
},
"aes-192-cbc": {
"cipher": "AES",
"key": 192,
"iv": 16,
"mode": "CBC",
"type": "block"
},
"aes-256-cbc": {
"cipher": "AES",
"key": 256,
"iv": 16,
"mode": "CBC",
"type": "block"
},
"aes128": {
"cipher": "AES",
"key": 128,
"iv": 16,
"mode": "CBC",
"type": "block"
},
"aes192": {
"cipher": "AES",
"key": 192,
"iv": 16,
"mode": "CBC",
"type": "block"
},
"aes256": {
"cipher": "AES",
"key": 256,
"iv": 16,
"mode": "CBC",
"type": "block"
},
"aes-128-cfb": {
"cipher": "AES",
"key": 128,
"iv": 16,
"mode": "CFB",
"type": "stream"
},
"aes-192-cfb": {
"cipher": "AES",
"key": 192,
"iv": 16,
"mode": "CFB",
"type": "stream"
},
"aes-256-cfb": {
"cipher": "AES",
"key": 256,
"iv": 16,
"mode": "CFB",
"type": "stream"
},
"aes-128-cfb8": {
"cipher": "AES",
"key": 128,
"iv": 16,
"mode": "CFB8",
"type": "stream"
},
"aes-192-cfb8": {
"cipher": "AES",
"key": 192,
"iv": 16,
"mode": "CFB8",
"type": "stream"
},
"aes-256-cfb8": {
"cipher": "AES",
"key": 256,
"iv": 16,
"mode": "CFB8",
"type": "stream"
},
"aes-128-cfb1": {
"cipher": "AES",
"key": 128,
"iv": 16,
"mode": "CFB1",
"type": "stream"
},
"aes-192-cfb1": {
"cipher": "AES",
"key": 192,
"iv": 16,
"mode": "CFB1",
"type": "stream"
},
"aes-256-cfb1": {
"cipher": "AES",
"key": 256,
"iv": 16,
"mode": "CFB1",
"type": "stream"
},
"aes-128-ofb": {
"cipher": "AES",
"key": 128,
"iv": 16,
"mode": "OFB",
"type": "stream"
},
"aes-192-ofb": {
"cipher": "AES",
"key": 192,
"iv": 16,
"mode": "OFB",
"type": "stream"
},
"aes-256-ofb": {
"cipher": "AES",
"key": 256,
"iv": 16,
"mode": "OFB",
"type": "stream"
},
"aes-128-ctr": {
"cipher": "AES",
"key": 128,
"iv": 16,
"mode": "CTR",
"type": "stream"
},
"aes-192-ctr": {
"cipher": "AES",
"key": 192,
"iv": 16,
"mode": "CTR",
"type": "stream"
},
"aes-256-ctr": {
"cipher": "AES",
"key": 256,
"iv": 16,
"mode": "CTR",
"type": "stream"
},
"aes-128-gcm": {
"cipher": "AES",
"key": 128,
"iv": 12,
"mode": "GCM",
"type": "auth"
},
"aes-192-gcm": {
"cipher": "AES",
"key": 192,
"iv": 12,
"mode": "GCM",
"type": "auth"
},
"aes-256-gcm": {
"cipher": "AES",
"key": 256,
"iv": 12,
"mode": "GCM",
"type": "auth"
}
}
},{}],140:[function(require,module,exports){
(function (Buffer){
var xor = require('buffer-xor')
function getBlock (self) {
self._prev = self._cipher.encryptBlock(self._prev)
return self._prev
}
exports.encrypt = function (self, chunk) {
while (self._cache.length < chunk.length) {
self._cache = Buffer.concat([self._cache, getBlock(self)])
}
var pad = self._cache.slice(0, chunk.length)
self._cache = self._cache.slice(chunk.length)
return xor(chunk, pad)
}
}).call(this,require("buffer").Buffer)
},{"buffer":157,"buffer-xor":156}],141:[function(require,module,exports){
var aes = require('./aes')
var Buffer = require('safe-buffer').Buffer
var Transform = require('cipher-base')
var inherits = require('inherits')
function StreamCipher (mode, key, iv, decrypt) {
Transform.call(this)
this._cipher = new aes.AES(key)
this._prev = Buffer.from(iv)
this._cache = Buffer.allocUnsafe(0)
this._secCache = Buffer.allocUnsafe(0)
this._decrypt = decrypt
this._mode = mode
}
inherits(StreamCipher, Transform)
StreamCipher.prototype._update = function (chunk) {
return this._mode.encrypt(this, chunk, this._decrypt)
}
StreamCipher.prototype._final = function () {
this._cipher.scrub()
}
module.exports = StreamCipher
},{"./aes":125,"cipher-base":160,"inherits":287,"safe-buffer":381}],142:[function(require,module,exports){
var ebtk = require('evp_bytestokey')
var aes = require('browserify-aes/browser')
var DES = require('browserify-des')
var desModes = require('browserify-des/modes')
var aesModes = require('browserify-aes/modes')
function createCipher (suite, password) {
var keyLen, ivLen
suite = suite.toLowerCase()
if (aesModes[suite]) {
keyLen = aesModes[suite].key
ivLen = aesModes[suite].iv
} else if (desModes[suite]) {
keyLen = desModes[suite].key * 8
ivLen = desModes[suite].iv
} else {
throw new TypeError('invalid suite type')
}
var keys = ebtk(password, false, keyLen, ivLen)
return createCipheriv(suite, keys.key, keys.iv)
}
function createDecipher (suite, password) {
var keyLen, ivLen
suite = suite.toLowerCase()
if (aesModes[suite]) {
keyLen = aesModes[suite].key
ivLen = aesModes[suite].iv
} else if (desModes[suite]) {
keyLen = desModes[suite].key * 8
ivLen = desModes[suite].iv
} else {
throw new TypeError('invalid suite type')
}
var keys = ebtk(password, false, keyLen, ivLen)
return createDecipheriv(suite, keys.key, keys.iv)
}
function createCipheriv (suite, key, iv) {
suite = suite.toLowerCase()
if (aesModes[suite]) {
return aes.createCipheriv(suite, key, iv)
} else if (desModes[suite]) {
return new DES({
key: key,
iv: iv,
mode: suite
})
} else {
throw new TypeError('invalid suite type')
}
}
function createDecipheriv (suite, key, iv) {
suite = suite.toLowerCase()
if (aesModes[suite]) {
return aes.createDecipheriv(suite, key, iv)
} else if (desModes[suite]) {
return new DES({
key: key,
iv: iv,
mode: suite,
decrypt: true
})
} else {
throw new TypeError('invalid suite type')
}
}
exports.createCipher = exports.Cipher = createCipher
exports.createCipheriv = exports.Cipheriv = createCipheriv
exports.createDecipher = exports.Decipher = createDecipher
exports.createDecipheriv = exports.Decipheriv = createDecipheriv
function getCiphers () {
return Object.keys(desModes).concat(aes.getCiphers())
}
exports.listCiphers = exports.getCiphers = getCiphers
},{"browserify-aes/browser":127,"browserify-aes/modes":138,"browserify-des":143,"browserify-des/modes":144,"evp_bytestokey":238}],143:[function(require,module,exports){
(function (Buffer){
var CipherBase = require('cipher-base')
var des = require('des.js')
var inherits = require('inherits')
var modes = {
'des-ede3-cbc': des.CBC.instantiate(des.EDE),
'des-ede3': des.EDE,
'des-ede-cbc': des.CBC.instantiate(des.EDE),
'des-ede': des.EDE,
'des-cbc': des.CBC.instantiate(des.DES),
'des-ecb': des.DES
}
modes.des = modes['des-cbc']
modes.des3 = modes['des-ede3-cbc']
module.exports = DES
inherits(DES, CipherBase)
function DES (opts) {
CipherBase.call(this)
var modeName = opts.mode.toLowerCase()
var mode = modes[modeName]
var type
if (opts.decrypt) {
type = 'decrypt'
} else {
type = 'encrypt'
}
var key = opts.key
if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {
key = Buffer.concat([key, key.slice(0, 8)])
}
var iv = opts.iv
this._des = mode.create({
key: key,
iv: iv,
type: type
})
}
DES.prototype._update = function (data) {
return new Buffer(this._des.update(data))
}
DES.prototype._final = function () {
return new Buffer(this._des.final())
}
}).call(this,require("buffer").Buffer)
},{"buffer":157,"cipher-base":160,"des.js":208,"inherits":287}],144:[function(require,module,exports){
exports['des-ecb'] = {
key: 8,
iv: 0
}
exports['des-cbc'] = exports.des = {
key: 8,
iv: 8
}
exports['des-ede3-cbc'] = exports.des3 = {
key: 24,
iv: 8
}
exports['des-ede3'] = {
key: 24,
iv: 0
}
exports['des-ede-cbc'] = {
key: 16,
iv: 8
}
exports['des-ede'] = {
key: 16,
iv: 0
}
},{}],145:[function(require,module,exports){
(function (Buffer){
var bn = require('bn.js');
var randomBytes = require('randombytes');
module.exports = crt;
function blind(priv) {
var r = getr(priv);
var blinder = r.toRed(bn.mont(priv.modulus))
.redPow(new bn(priv.publicExponent)).fromRed();
return {
blinder: blinder,
unblinder:r.invm(priv.modulus)
};
}
function crt(msg, priv) {
var blinds = blind(priv);
var len = priv.modulus.byteLength();
var mod = bn.mont(priv.modulus);
var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus);
var c1 = blinded.toRed(bn.mont(priv.prime1));
var c2 = blinded.toRed(bn.mont(priv.prime2));
var qinv = priv.coefficient;
var p = priv.prime1;
var q = priv.prime2;
var m1 = c1.redPow(priv.exponent1);
var m2 = c2.redPow(priv.exponent2);
m1 = m1.fromRed();
m2 = m2.fromRed();
var h = m1.isub(m2).imul(qinv).umod(p);
h.imul(q);
m2.iadd(h);
return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len));
}
crt.getr = getr;
function getr(priv) {
var len = priv.modulus.byteLength();
var r = new bn(randomBytes(len));
while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) {
r = new bn(randomBytes(len));
}
return r;
}
}).call(this,require("buffer").Buffer)
},{"bn.js":122,"buffer":157,"randombytes":352}],146:[function(require,module,exports){
module.exports = require('./browser/algorithms.json')
},{"./browser/algorithms.json":147}],147:[function(require,module,exports){
module.exports={
"sha224WithRSAEncryption": {
"sign": "rsa",
"hash": "sha224",
"id": "302d300d06096086480165030402040500041c"
},
"RSA-SHA224": {
"sign": "ecdsa/rsa",
"hash": "sha224",
"id": "302d300d06096086480165030402040500041c"
},
"sha256WithRSAEncryption": {
"sign": "rsa",
"hash": "sha256",
"id": "3031300d060960864801650304020105000420"
},
"RSA-SHA256": {
"sign": "ecdsa/rsa",
"hash": "sha256",
"id": "3031300d060960864801650304020105000420"
},
"sha384WithRSAEncryption": {
"sign": "rsa",
"hash": "sha384",
"id": "3041300d060960864801650304020205000430"
},
"RSA-SHA384": {
"sign": "ecdsa/rsa",
"hash": "sha384",
"id": "3041300d060960864801650304020205000430"
},
"sha512WithRSAEncryption": {
"sign": "rsa",
"hash": "sha512",
"id": "3051300d060960864801650304020305000440"
},
"RSA-SHA512": {
"sign": "ecdsa/rsa",
"hash": "sha512",
"id": "3051300d060960864801650304020305000440"
},
"RSA-SHA1": {
"sign": "rsa",
"hash": "sha1",
"id": "3021300906052b0e03021a05000414"
},
"ecdsa-with-SHA1": {
"sign": "ecdsa",
"hash": "sha1",
"id": ""
},
"sha256": {
"sign": "ecdsa",
"hash": "sha256",
"id": ""
},
"sha224": {
"sign": "ecdsa",
"hash": "sha224",
"id": ""
},
"sha384": {
"sign": "ecdsa",
"hash": "sha384",
"id": ""
},
"sha512": {
"sign": "ecdsa",
"hash": "sha512",
"id": ""
},
"DSA-SHA": {
"sign": "dsa",
"hash": "sha1",
"id": ""
},
"DSA-SHA1": {
"sign": "dsa",
"hash": "sha1",
"id": ""
},
"DSA": {
"sign": "dsa",
"hash": "sha1",
"id": ""
},
"DSA-WITH-SHA224": {
"sign": "dsa",
"hash": "sha224",
"id": ""
},
"DSA-SHA224": {
"sign": "dsa",
"hash": "sha224",
"id": ""
},
"DSA-WITH-SHA256": {
"sign": "dsa",
"hash": "sha256",
"id": ""
},
"DSA-SHA256": {
"sign": "dsa",
"hash": "sha256",
"id": ""
},
"DSA-WITH-SHA384": {
"sign": "dsa",
"hash": "sha384",
"id": ""
},
"DSA-SHA384": {
"sign": "dsa",
"hash": "sha384",
"id": ""
},
"DSA-WITH-SHA512": {
"sign": "dsa",
"hash": "sha512",
"id": ""
},
"DSA-SHA512": {
"sign": "dsa",
"hash": "sha512",
"id": ""
},
"DSA-RIPEMD160": {
"sign": "dsa",
"hash": "rmd160",
"id": ""
},
"ripemd160WithRSA": {
"sign": "rsa",
"hash": "rmd160",
"id": "3021300906052b2403020105000414"
},
"RSA-RIPEMD160": {
"sign": "rsa",
"hash": "rmd160",
"id": "3021300906052b2403020105000414"
},
"md5WithRSAEncryption": {
"sign": "rsa",
"hash": "md5",
"id": "3020300c06082a864886f70d020505000410"
},
"RSA-MD5": {
"sign": "rsa",
"hash": "md5",
"id": "3020300c06082a864886f70d020505000410"
}
}
},{}],148:[function(require,module,exports){
module.exports={
"1.3.132.0.10": "secp256k1",
"1.3.132.0.33": "p224",
"1.2.840.10045.3.1.1": "p192",
"1.2.840.10045.3.1.7": "p256",
"1.3.132.0.34": "p384",
"1.3.132.0.35": "p521"
}
},{}],149:[function(require,module,exports){
(function (Buffer){
var createHash = require('create-hash')
var stream = require('stream')
var inherits = require('inherits')
var sign = require('./sign')
var verify = require('./verify')
var algorithms = require('./algorithms.json')
Object.keys(algorithms).forEach(function (key) {
algorithms[key].id = new Buffer(algorithms[key].id, 'hex')
algorithms[key.toLowerCase()] = algorithms[key]
})
function Sign (algorithm) {
stream.Writable.call(this)
var data = algorithms[algorithm]
if (!data) throw new Error('Unknown message digest')
this._hashType = data.hash
this._hash = createHash(data.hash)
this._tag = data.id
this._signType = data.sign
}
inherits(Sign, stream.Writable)
Sign.prototype._write = function _write (data, _, done) {
this._hash.update(data)
done()
}
Sign.prototype.update = function update (data, enc) {
if (typeof data === 'string') data = new Buffer(data, enc)
this._hash.update(data)
return this
}
Sign.prototype.sign = function signMethod (key, enc) {
this.end()
var hash = this._hash.digest()
var sig = sign(hash, key, this._hashType, this._signType, this._tag)
return enc ? sig.toString(enc) : sig
}
function Verify (algorithm) {
stream.Writable.call(this)
var data = algorithms[algorithm]
if (!data) throw new Error('Unknown message digest')
this._hash = createHash(data.hash)
this._tag = data.id
this._signType = data.sign
}
inherits(Verify, stream.Writable)
Verify.prototype._write = function _write (data, _, done) {
this._hash.update(data)
done()
}
Verify.prototype.update = function update (data, enc) {
if (typeof data === 'string') data = new Buffer(data, enc)
this._hash.update(data)
return this
}
Verify.prototype.verify = function verifyMethod (key, sig, enc) {
if (typeof sig === 'string') sig = new Buffer(sig, enc)
this.end()
var hash = this._hash.digest()
return verify(sig, hash, key, this._signType, this._tag)
}
function createSign (algorithm) {
return new Sign(algorithm)
}
function createVerify (algorithm) {
return new Verify(algorithm)
}
module.exports = {
Sign: createSign,
Verify: createVerify,
createSign: createSign,
createVerify: createVerify
}
}).call(this,require("buffer").Buffer)
},{"./algorithms.json":147,"./sign":150,"./verify":151,"buffer":157,"create-hash":165,"inherits":287,"stream":467}],150:[function(require,module,exports){
(function (Buffer){
// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
var createHmac = require('create-hmac')
var crt = require('browserify-rsa')
var EC = require('elliptic').ec
var BN = require('bn.js')
var parseKeys = require('parse-asn1')
var curves = require('./curves.json')
function sign (hash, key, hashType, signType, tag) {
var priv = parseKeys(key)
if (priv.curve) {
// rsa keys can be interpreted as ecdsa ones in openssl
if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
return ecSign(hash, priv)
} else if (priv.type === 'dsa') {
if (signType !== 'dsa') throw new Error('wrong private key type')
return dsaSign(hash, priv, hashType)
} else {
if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
}
hash = Buffer.concat([tag, hash])
var len = priv.modulus.byteLength()
var pad = [ 0, 1 ]
while (hash.length + pad.length + 1 < len) pad.push(0xff)
pad.push(0x00)
var i = -1
while (++i < hash.length) pad.push(hash[i])
var out = crt(pad, priv)
return out
}
function ecSign (hash, priv) {
var curveId = curves[priv.curve.join('.')]
if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.'))
var curve = new EC(curveId)
var key = curve.keyFromPrivate(priv.privateKey)
var out = key.sign(hash)
return new Buffer(out.toDER())
}
function dsaSign (hash, priv, algo) {
var x = priv.params.priv_key
var p = priv.params.p
var q = priv.params.q
var g = priv.params.g
var r = new BN(0)
var k
var H = bits2int(hash, q).mod(q)
var s = false
var kv = getKey(x, q, hash, algo)
while (s === false) {
k = makeKey(q, kv, algo)
r = makeR(g, k, p, q)
s = k.invm(q).imul(H.add(x.mul(r))).mod(q)
if (s.cmpn(0) === 0) {
s = false
r = new BN(0)
}
}
return toDER(r, s)
}
function toDER (r, s) {
r = r.toArray()
s = s.toArray()
// Pad values
if (r[0] & 0x80) r = [ 0 ].concat(r)
if (s[0] & 0x80) s = [ 0 ].concat(s)
var total = r.length + s.length + 4
var res = [ 0x30, total, 0x02, r.length ]
res = res.concat(r, [ 0x02, s.length ], s)
return new Buffer(res)
}
function getKey (x, q, hash, algo) {
x = new Buffer(x.toArray())
if (x.length < q.byteLength()) {
var zeros = new Buffer(q.byteLength() - x.length)
zeros.fill(0)
x = Buffer.concat([ zeros, x ])
}
var hlen = hash.length
var hbits = bits2octets(hash, q)
var v = new Buffer(hlen)
v.fill(1)
var k = new Buffer(hlen)
k.fill(0)
k = createHmac(algo, k).update(v).update(new Buffer([ 0 ])).update(x).update(hbits).digest()
v = createHmac(algo, k).update(v).digest()
k = createHmac(algo, k).update(v).update(new Buffer([ 1 ])).update(x).update(hbits).digest()
v = createHmac(algo, k).update(v).digest()
return { k: k, v: v }
}
function bits2int (obits, q) {
var bits = new BN(obits)
var shift = (obits.length << 3) - q.bitLength()
if (shift > 0) bits.ishrn(shift)
return bits
}
function bits2octets (bits, q) {
bits = bits2int(bits, q)
bits = bits.mod(q)
var out = new Buffer(bits.toArray())
if (out.length < q.byteLength()) {
var zeros = new Buffer(q.byteLength() - out.length)
zeros.fill(0)
out = Buffer.concat([ zeros, out ])
}
return out
}
function makeKey (q, kv, algo) {
var t
var k
do {
t = new Buffer(0)
while (t.length * 8 < q.bitLength()) {
kv.v = createHmac(algo, kv.k).update(kv.v).digest()
t = Buffer.concat([ t, kv.v ])
}
k = bits2int(t, q)
kv.k = createHmac(algo, kv.k).update(kv.v).update(new Buffer([ 0 ])).digest()
kv.v = createHmac(algo, kv.k).update(kv.v).digest()
} while (k.cmp(q) !== -1)
return k
}
function makeR (g, k, p, q) {
return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)
}
module.exports = sign
module.exports.getKey = getKey
module.exports.makeKey = makeKey
}).call(this,require("buffer").Buffer)
},{"./curves.json":148,"bn.js":122,"browserify-rsa":145,"buffer":157,"create-hmac":168,"elliptic":221,"parse-asn1":327}],151:[function(require,module,exports){
(function (Buffer){
// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
var BN = require('bn.js')
var EC = require('elliptic').ec
var parseKeys = require('parse-asn1')
var curves = require('./curves.json')
function verify (sig, hash, key, signType, tag) {
var pub = parseKeys(key)
if (pub.type === 'ec') {
// rsa keys can be interpreted as ecdsa ones in openssl
if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
return ecVerify(sig, hash, pub)
} else if (pub.type === 'dsa') {
if (signType !== 'dsa') throw new Error('wrong public key type')
return dsaVerify(sig, hash, pub)
} else {
if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
}
hash = Buffer.concat([tag, hash])
var len = pub.modulus.byteLength()
var pad = [ 1 ]
var padNum = 0
while (hash.length + pad.length + 2 < len) {
pad.push(0xff)
padNum++
}
pad.push(0x00)
var i = -1
while (++i < hash.length) {
pad.push(hash[i])
}
pad = new Buffer(pad)
var red = BN.mont(pub.modulus)
sig = new BN(sig).toRed(red)
sig = sig.redPow(new BN(pub.publicExponent))
sig = new Buffer(sig.fromRed().toArray())
var out = padNum < 8 ? 1 : 0
len = Math.min(sig.length, pad.length)
if (sig.length !== pad.length) out = 1
i = -1
while (++i < len) out |= sig[i] ^ pad[i]
return out === 0
}
function ecVerify (sig, hash, pub) {
var curveId = curves[pub.data.algorithm.curve.join('.')]
if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.'))
var curve = new EC(curveId)
var pubkey = pub.data.subjectPrivateKey.data
return curve.verify(hash, sig, pubkey)
}
function dsaVerify (sig, hash, pub) {
var p = pub.data.p
var q = pub.data.q
var g = pub.data.g
var y = pub.data.pub_key
var unpacked = parseKeys.signature.decode(sig, 'der')
var s = unpacked.s
var r = unpacked.r
checkValue(s, q)
checkValue(r, q)
var montp = BN.mont(p)
var w = s.invm(q)
var v = g.toRed(montp)
.redPow(new BN(hash).mul(w).mod(q))
.fromRed()
.mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed())
.mod(p)
.mod(q)
return v.cmp(r) === 0
}
function checkValue (b, q) {
if (b.cmpn(0) <= 0) throw new Error('invalid sig')
if (b.cmp(q) >= q) throw new Error('invalid sig')
}
module.exports = verify
}).call(this,require("buffer").Buffer)
},{"./curves.json":148,"bn.js":122,"buffer":157,"elliptic":221,"parse-asn1":327}],152:[function(require,module,exports){
(function (process,Buffer){
var msg = require('pako/lib/zlib/messages');
var zstream = require('pako/lib/zlib/zstream');
var zlib_deflate = require('pako/lib/zlib/deflate.js');
var zlib_inflate = require('pako/lib/zlib/inflate.js');
var constants = require('pako/lib/zlib/constants');
for (var key in constants) {
exports[key] = constants[key];
}
// zlib modes
exports.NONE = 0;
exports.DEFLATE = 1;
exports.INFLATE = 2;
exports.GZIP = 3;
exports.GUNZIP = 4;
exports.DEFLATERAW = 5;
exports.INFLATERAW = 6;
exports.UNZIP = 7;
/**
* Emulate Node's zlib C++ layer for use by the JS layer in index.js
*/
function Zlib(mode) {
if (mode < exports.DEFLATE || mode > exports.UNZIP)
throw new TypeError("Bad argument");
this.mode = mode;
this.init_done = false;
this.write_in_progress = false;
this.pending_close = false;
this.windowBits = 0;
this.level = 0;
this.memLevel = 0;
this.strategy = 0;
this.dictionary = null;
}
Zlib.prototype.init = function(windowBits, level, memLevel, strategy, dictionary) {
this.windowBits = windowBits;
this.level = level;
this.memLevel = memLevel;
this.strategy = strategy;
// dictionary not supported.
if (this.mode === exports.GZIP || this.mode === exports.GUNZIP)
this.windowBits += 16;
if (this.mode === exports.UNZIP)
this.windowBits += 32;
if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW)
this.windowBits = -this.windowBits;
this.strm = new zstream();
switch (this.mode) {
case exports.DEFLATE:
case exports.GZIP:
case exports.DEFLATERAW:
var status = zlib_deflate.deflateInit2(
this.strm,
this.level,
exports.Z_DEFLATED,
this.windowBits,
this.memLevel,
this.strategy
);
break;
case exports.INFLATE:
case exports.GUNZIP:
case exports.INFLATERAW:
case exports.UNZIP:
var status = zlib_inflate.inflateInit2(
this.strm,
this.windowBits
);
break;
default:
throw new Error("Unknown mode " + this.mode);
}
if (status !== exports.Z_OK) {
this._error(status);
return;
}
this.write_in_progress = false;
this.init_done = true;
};
Zlib.prototype.params = function() {
throw new Error("deflateParams Not supported");
};
Zlib.prototype._writeCheck = function() {
if (!this.init_done)
throw new Error("write before init");
if (this.mode === exports.NONE)
throw new Error("already finalized");
if (this.write_in_progress)
throw new Error("write already in progress");
if (this.pending_close)
throw new Error("close is pending");
};
Zlib.prototype.write = function(flush, input, in_off, in_len, out, out_off, out_len) {
this._writeCheck();
this.write_in_progress = true;
var self = this;
process.nextTick(function() {
self.write_in_progress = false;
var res = self._write(flush, input, in_off, in_len, out, out_off, out_len);
self.callback(res[0], res[1]);
if (self.pending_close)
self.close();
});
return this;
};
// set method for Node buffers, used by pako
function bufferSet(data, offset) {
for (var i = 0; i < data.length; i++) {
this[offset + i] = data[i];
}
}
Zlib.prototype.writeSync = function(flush, input, in_off, in_len, out, out_off, out_len) {
this._writeCheck();
return this._write(flush, input, in_off, in_len, out, out_off, out_len);
};
Zlib.prototype._write = function(flush, input, in_off, in_len, out, out_off, out_len) {
this.write_in_progress = true;
if (flush !== exports.Z_NO_FLUSH &&
flush !== exports.Z_PARTIAL_FLUSH &&
flush !== exports.Z_SYNC_FLUSH &&
flush !== exports.Z_FULL_FLUSH &&
flush !== exports.Z_FINISH &&
flush !== exports.Z_BLOCK) {
throw new Error("Invalid flush value");
}
if (input == null) {
input = new Buffer(0);
in_len = 0;
in_off = 0;
}
if (out._set)
out.set = out._set;
else
out.set = bufferSet;
var strm = this.strm;
strm.avail_in = in_len;
strm.input = input;
strm.next_in = in_off;
strm.avail_out = out_len;
strm.output = out;
strm.next_out = out_off;
switch (this.mode) {
case exports.DEFLATE:
case exports.GZIP:
case exports.DEFLATERAW:
var status = zlib_deflate.deflate(strm, flush);
break;
case exports.UNZIP:
case exports.INFLATE:
case exports.GUNZIP:
case exports.INFLATERAW:
var status = zlib_inflate.inflate(strm, flush);
break;
default:
throw new Error("Unknown mode " + this.mode);
}
if (status !== exports.Z_STREAM_END && status !== exports.Z_OK) {
this._error(status);
}
this.write_in_progress = false;
return [strm.avail_in, strm.avail_out];
};
Zlib.prototype.close = function() {
if (this.write_in_progress) {
this.pending_close = true;
return;
}
this.pending_close = false;
if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
zlib_deflate.deflateEnd(this.strm);
} else {
zlib_inflate.inflateEnd(this.strm);
}
this.mode = exports.NONE;
};
Zlib.prototype.reset = function() {
switch (this.mode) {
case exports.DEFLATE:
case exports.DEFLATERAW:
var status = zlib_deflate.deflateReset(this.strm);
break;
case exports.INFLATE:
case exports.INFLATERAW:
var status = zlib_inflate.inflateReset(this.strm);
break;
}
if (status !== exports.Z_OK) {
this._error(status);
}
};
Zlib.prototype._error = function(status) {
this.onerror(msg[status] + ': ' + this.strm.msg, status);
this.write_in_progress = false;
if (this.pending_close)
this.close();
};
exports.Zlib = Zlib;
}).call(this,require('_process'),require("buffer").Buffer)
},{"_process":336,"buffer":157,"pako/lib/zlib/constants":314,"pako/lib/zlib/deflate.js":316,"pako/lib/zlib/inflate.js":318,"pako/lib/zlib/messages":320,"pako/lib/zlib/zstream":322}],153:[function(require,module,exports){
(function (process,Buffer){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var Transform = require('_stream_transform');
var binding = require('./binding');
var util = require('util');
var assert = require('assert').ok;
// zlib doesn't provide these, so kludge them in following the same
// const naming scheme zlib uses.
binding.Z_MIN_WINDOWBITS = 8;
binding.Z_MAX_WINDOWBITS = 15;
binding.Z_DEFAULT_WINDOWBITS = 15;
// fewer than 64 bytes per chunk is stupid.
// technically it could work with as few as 8, but even 64 bytes
// is absurdly low. Usually a MB or more is best.
binding.Z_MIN_CHUNK = 64;
binding.Z_MAX_CHUNK = Infinity;
binding.Z_DEFAULT_CHUNK = (16 * 1024);
binding.Z_MIN_MEMLEVEL = 1;
binding.Z_MAX_MEMLEVEL = 9;
binding.Z_DEFAULT_MEMLEVEL = 8;
binding.Z_MIN_LEVEL = -1;
binding.Z_MAX_LEVEL = 9;
binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
// expose all the zlib constants
Object.keys(binding).forEach(function(k) {
if (k.match(/^Z/)) exports[k] = binding[k];
});
// translation table for return codes.
exports.codes = {
Z_OK: binding.Z_OK,
Z_STREAM_END: binding.Z_STREAM_END,
Z_NEED_DICT: binding.Z_NEED_DICT,
Z_ERRNO: binding.Z_ERRNO,
Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
Z_DATA_ERROR: binding.Z_DATA_ERROR,
Z_MEM_ERROR: binding.Z_MEM_ERROR,
Z_BUF_ERROR: binding.Z_BUF_ERROR,
Z_VERSION_ERROR: binding.Z_VERSION_ERROR
};
Object.keys(exports.codes).forEach(function(k) {
exports.codes[exports.codes[k]] = k;
});
exports.Deflate = Deflate;
exports.Inflate = Inflate;
exports.Gzip = Gzip;
exports.Gunzip = Gunzip;
exports.DeflateRaw = DeflateRaw;
exports.InflateRaw = InflateRaw;
exports.Unzip = Unzip;
exports.createDeflate = function(o) {
return new Deflate(o);
};
exports.createInflate = function(o) {
return new Inflate(o);
};
exports.createDeflateRaw = function(o) {
return new DeflateRaw(o);
};
exports.createInflateRaw = function(o) {
return new InflateRaw(o);
};
exports.createGzip = function(o) {
return new Gzip(o);
};
exports.createGunzip = function(o) {
return new Gunzip(o);
};
exports.createUnzip = function(o) {
return new Unzip(o);
};
// Convenience methods.
// compress/decompress a string or buffer in one step.
exports.deflate = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Deflate(opts), buffer, callback);
};
exports.deflateSync = function(buffer, opts) {
return zlibBufferSync(new Deflate(opts), buffer);
};
exports.gzip = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Gzip(opts), buffer, callback);
};
exports.gzipSync = function(buffer, opts) {
return zlibBufferSync(new Gzip(opts), buffer);
};
exports.deflateRaw = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new DeflateRaw(opts), buffer, callback);
};
exports.deflateRawSync = function(buffer, opts) {
return zlibBufferSync(new DeflateRaw(opts), buffer);
};
exports.unzip = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Unzip(opts), buffer, callback);
};
exports.unzipSync = function(buffer, opts) {
return zlibBufferSync(new Unzip(opts), buffer);
};
exports.inflate = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Inflate(opts), buffer, callback);
};
exports.inflateSync = function(buffer, opts) {
return zlibBufferSync(new Inflate(opts), buffer);
};
exports.gunzip = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new Gunzip(opts), buffer, callback);
};
exports.gunzipSync = function(buffer, opts) {
return zlibBufferSync(new Gunzip(opts), buffer);
};
exports.inflateRaw = function(buffer, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
return zlibBuffer(new InflateRaw(opts), buffer, callback);
};
exports.inflateRawSync = function(buffer, opts) {
return zlibBufferSync(new InflateRaw(opts), buffer);
};
function zlibBuffer(engine, buffer, callback) {
var buffers = [];
var nread = 0;
engine.on('error', onError);
engine.on('end', onEnd);
engine.end(buffer);
flow();
function flow() {
var chunk;
while (null !== (chunk = engine.read())) {
buffers.push(chunk);
nread += chunk.length;
}
engine.once('readable', flow);
}
function onError(err) {
engine.removeListener('end', onEnd);
engine.removeListener('readable', flow);
callback(err);
}
function onEnd() {
var buf = Buffer.concat(buffers, nread);
buffers = [];
callback(null, buf);
engine.close();
}
}
function zlibBufferSync(engine, buffer) {
if (typeof buffer === 'string')
buffer = new Buffer(buffer);
if (!Buffer.isBuffer(buffer))
throw new TypeError('Not a string or buffer');
var flushFlag = binding.Z_FINISH;
return engine._processChunk(buffer, flushFlag);
}
// generic zlib
// minimal 2-byte header
function Deflate(opts) {
if (!(this instanceof Deflate)) return new Deflate(opts);
Zlib.call(this, opts, binding.DEFLATE);
}
function Inflate(opts) {
if (!(this instanceof Inflate)) return new Inflate(opts);
Zlib.call(this, opts, binding.INFLATE);
}
// gzip - bigger header, same deflate compression
function Gzip(opts) {
if (!(this instanceof Gzip)) return new Gzip(opts);
Zlib.call(this, opts, binding.GZIP);
}
function Gunzip(opts) {
if (!(this instanceof Gunzip)) return new Gunzip(opts);
Zlib.call(this, opts, binding.GUNZIP);
}
// raw - no header
function DeflateRaw(opts) {
if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
Zlib.call(this, opts, binding.DEFLATERAW);
}
function InflateRaw(opts) {
if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
Zlib.call(this, opts, binding.INFLATERAW);
}
// auto-detect header.
function Unzip(opts) {
if (!(this instanceof Unzip)) return new Unzip(opts);
Zlib.call(this, opts, binding.UNZIP);
}
// the Zlib class they all inherit from
// This thing manages the queue of requests, and returns
// true or false if there is anything in the queue when
// you call the .write() method.
function Zlib(opts, mode) {
this._opts = opts = opts || {};
this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
Transform.call(this, opts);
if (opts.flush) {
if (opts.flush !== binding.Z_NO_FLUSH &&
opts.flush !== binding.Z_PARTIAL_FLUSH &&
opts.flush !== binding.Z_SYNC_FLUSH &&
opts.flush !== binding.Z_FULL_FLUSH &&
opts.flush !== binding.Z_FINISH &&
opts.flush !== binding.Z_BLOCK) {
throw new Error('Invalid flush flag: ' + opts.flush);
}
}
this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
if (opts.chunkSize) {
if (opts.chunkSize < exports.Z_MIN_CHUNK ||
opts.chunkSize > exports.Z_MAX_CHUNK) {
throw new Error('Invalid chunk size: ' + opts.chunkSize);
}
}
if (opts.windowBits) {
if (opts.windowBits < exports.Z_MIN_WINDOWBITS ||
opts.windowBits > exports.Z_MAX_WINDOWBITS) {
throw new Error('Invalid windowBits: ' + opts.windowBits);
}
}
if (opts.level) {
if (opts.level < exports.Z_MIN_LEVEL ||
opts.level > exports.Z_MAX_LEVEL) {
throw new Error('Invalid compression level: ' + opts.level);
}
}
if (opts.memLevel) {
if (opts.memLevel < exports.Z_MIN_MEMLEVEL ||
opts.memLevel > exports.Z_MAX_MEMLEVEL) {
throw new Error('Invalid memLevel: ' + opts.memLevel);
}
}
if (opts.strategy) {
if (opts.strategy != exports.Z_FILTERED &&
opts.strategy != exports.Z_HUFFMAN_ONLY &&
opts.strategy != exports.Z_RLE &&
opts.strategy != exports.Z_FIXED &&
opts.strategy != exports.Z_DEFAULT_STRATEGY) {
throw new Error('Invalid strategy: ' + opts.strategy);
}
}
if (opts.dictionary) {
if (!Buffer.isBuffer(opts.dictionary)) {
throw new Error('Invalid dictionary: it should be a Buffer instance');
}
}
this._binding = new binding.Zlib(mode);
var self = this;
this._hadError = false;
this._binding.onerror = function(message, errno) {
// there is no way to cleanly recover.
// continuing only obscures problems.
self._binding = null;
self._hadError = true;
var error = new Error(message);
error.errno = errno;
error.code = exports.codes[errno];
self.emit('error', error);
};
var level = exports.Z_DEFAULT_COMPRESSION;
if (typeof opts.level === 'number') level = opts.level;
var strategy = exports.Z_DEFAULT_STRATEGY;
if (typeof opts.strategy === 'number') strategy = opts.strategy;
this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,
level,
opts.memLevel || exports.Z_DEFAULT_MEMLEVEL,
strategy,
opts.dictionary);
this._buffer = new Buffer(this._chunkSize);
this._offset = 0;
this._closed = false;
this._level = level;
this._strategy = strategy;
this.once('end', this.close);
}
util.inherits(Zlib, Transform);
Zlib.prototype.params = function(level, strategy, callback) {
if (level < exports.Z_MIN_LEVEL ||
level > exports.Z_MAX_LEVEL) {
throw new RangeError('Invalid compression level: ' + level);
}
if (strategy != exports.Z_FILTERED &&
strategy != exports.Z_HUFFMAN_ONLY &&
strategy != exports.Z_RLE &&
strategy != exports.Z_FIXED &&
strategy != exports.Z_DEFAULT_STRATEGY) {
throw new TypeError('Invalid strategy: ' + strategy);
}
if (this._level !== level || this._strategy !== strategy) {
var self = this;
this.flush(binding.Z_SYNC_FLUSH, function() {
self._binding.params(level, strategy);
if (!self._hadError) {
self._level = level;
self._strategy = strategy;
if (callback) callback();
}
});
} else {
process.nextTick(callback);
}
};
Zlib.prototype.reset = function() {
return this._binding.reset();
};
// This is the _flush function called by the transform class,
// internally, when the last chunk has been written.
Zlib.prototype._flush = function(callback) {
this._transform(new Buffer(0), '', callback);
};
Zlib.prototype.flush = function(kind, callback) {
var ws = this._writableState;
if (typeof kind === 'function' || (kind === void 0 && !callback)) {
callback = kind;
kind = binding.Z_FULL_FLUSH;
}
if (ws.ended) {
if (callback)
process.nextTick(callback);
} else if (ws.ending) {
if (callback)
this.once('end', callback);
} else if (ws.needDrain) {
var self = this;
this.once('drain', function() {
self.flush(callback);
});
} else {
this._flushFlag = kind;
this.write(new Buffer(0), '', callback);
}
};
Zlib.prototype.close = function(callback) {
if (callback)
process.nextTick(callback);
if (this._closed)
return;
this._closed = true;
this._binding.close();
var self = this;
process.nextTick(function() {
self.emit('close');
});
};
Zlib.prototype._transform = function(chunk, encoding, cb) {
var flushFlag;
var ws = this._writableState;
var ending = ws.ending || ws.ended;
var last = ending && (!chunk || ws.length === chunk.length);
if (!chunk === null && !Buffer.isBuffer(chunk))
return cb(new Error('invalid input'));
// If it's the last chunk, or a final flush, we use the Z_FINISH flush flag.
// If it's explicitly flushing at some other time, then we use
// Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
// goodness.
if (last)
flushFlag = binding.Z_FINISH;
else {
flushFlag = this._flushFlag;
// once we've flushed the last of the queue, stop flushing and
// go back to the normal behavior.
if (chunk.length >= ws.length) {
this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
}
}
var self = this;
this._processChunk(chunk, flushFlag, cb);
};
Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
var availInBefore = chunk && chunk.length;
var availOutBefore = this._chunkSize - this._offset;
var inOff = 0;
var self = this;
var async = typeof cb === 'function';
if (!async) {
var buffers = [];
var nread = 0;
var error;
this.on('error', function(er) {
error = er;
});
do {
var res = this._binding.writeSync(flushFlag,
chunk, // in
inOff, // in_off
availInBefore, // in_len
this._buffer, // out
this._offset, //out_off
availOutBefore); // out_len
} while (!this._hadError && callback(res[0], res[1]));
if (this._hadError) {
throw error;
}
var buf = Buffer.concat(buffers, nread);
this.close();
return buf;
}
var req = this._binding.write(flushFlag,
chunk, // in
inOff, // in_off
availInBefore, // in_len
this._buffer, // out
this._offset, //out_off
availOutBefore); // out_len
req.buffer = chunk;
req.callback = callback;
function callback(availInAfter, availOutAfter) {
if (self._hadError)
return;
var have = availOutBefore - availOutAfter;
assert(have >= 0, 'have should not go down');
if (have > 0) {
var out = self._buffer.slice(self._offset, self._offset + have);
self._offset += have;
// serve some output to the consumer.
if (async) {
self.push(out);
} else {
buffers.push(out);
nread += out.length;
}
}
// exhausted the output buffer, or used all the input create a new one.
if (availOutAfter === 0 || self._offset >= self._chunkSize) {
availOutBefore = self._chunkSize;
self._offset = 0;
self._buffer = new Buffer(self._chunkSize);
}
if (availOutAfter === 0) {
// Not actually done. Need to reprocess.
// Also, update the availInBefore to the availInAfter value,
// so that if we have to hit it a third (fourth, etc.) time,
// it'll have the correct byte counts.
inOff += (availInBefore - availInAfter);
availInBefore = availInAfter;
if (!async)
return true;
var newReq = self._binding.write(flushFlag,
chunk,
inOff,
availInBefore,
self._buffer,
self._offset,
self._chunkSize);
newReq.callback = callback; // this same function
newReq.buffer = chunk;
return;
}
if (!async)
return false;
// finished with the chunk.
cb();
}
};
util.inherits(Deflate, Zlib);
util.inherits(Inflate, Zlib);
util.inherits(Gzip, Zlib);
util.inherits(Gunzip, Zlib);
util.inherits(DeflateRaw, Zlib);
util.inherits(InflateRaw, Zlib);
util.inherits(Unzip, Zlib);
}).call(this,require('_process'),require("buffer").Buffer)
},{"./binding":152,"_process":336,"_stream_transform":365,"assert":116,"buffer":157,"util":491}],154:[function(require,module,exports){
arguments[4][124][0].apply(exports,arguments)
},{"dup":124}],155:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var Buffer = require('buffer').Buffer;
var isBufferEncoding = Buffer.isEncoding
|| function(encoding) {
switch (encoding && encoding.toLowerCase()) {
case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
default: return false;
}
}
function assertEncoding(encoding) {
if (encoding && !isBufferEncoding(encoding)) {
throw new Error('Unknown encoding: ' + encoding);
}
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters. CESU-8 is handled as part of the UTF-8 encoding.
//
// @TODO Handling all encodings inside a single object makes it very difficult
// to reason about this code, so it should be split up in the future.
// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
// points as used by CESU-8.
var StringDecoder = exports.StringDecoder = function(encoding) {
this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
assertEncoding(encoding);
switch (this.encoding) {
case 'utf8':
// CESU-8 represents each of Surrogate Pair by 3-bytes
this.surrogateSize = 3;
break;
case 'ucs2':
case 'utf16le':
// UTF-16 represents each of Surrogate Pair by 2-bytes
this.surrogateSize = 2;
this.detectIncompleteChar = utf16DetectIncompleteChar;
break;
case 'base64':
// Base-64 stores 3 bytes in 4 chars, and pads the remainder.
this.surrogateSize = 3;
this.detectIncompleteChar = base64DetectIncompleteChar;
break;
default:
this.write = passThroughWrite;
return;
}
// Enough space to store all bytes of a single character. UTF-8 needs 4
// bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
this.charBuffer = new Buffer(6);
// Number of bytes received for the current incomplete multi-byte character.
this.charReceived = 0;
// Number of bytes expected for the current incomplete multi-byte character.
this.charLength = 0;
};
// write decodes the given buffer and returns it as JS string that is
// guaranteed to not contain any partial multi-byte characters. Any partial
// character found at the end of the buffer is buffered up, and will be
// returned when calling write again with the remaining bytes.
//
// Note: Converting a Buffer containing an orphan surrogate to a String
// currently works, but converting a String to a Buffer (via `new Buffer`, or
// Buffer#write) will replace incomplete surrogates with the unicode
// replacement character. See https://codereview.chromium.org/121173009/ .
StringDecoder.prototype.write = function(buffer) {
var charStr = '';
// if our last write ended with an incomplete multibyte character
while (this.charLength) {
// determine how many remaining bytes this buffer has to offer for this char
var available = (buffer.length >= this.charLength - this.charReceived) ?
this.charLength - this.charReceived :
buffer.length;
// add the new bytes to the char buffer
buffer.copy(this.charBuffer, this.charReceived, 0, available);
this.charReceived += available;
if (this.charReceived < this.charLength) {
// still not enough chars in this buffer? wait for more ...
return '';
}
// remove bytes belonging to the current character from the buffer
buffer = buffer.slice(available, buffer.length);
// get the character that was split
charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
var charCode = charStr.charCodeAt(charStr.length - 1);
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
this.charLength += this.surrogateSize;
charStr = '';
continue;
}
this.charReceived = this.charLength = 0;
// if there are no more bytes in this buffer, just emit our char
if (buffer.length === 0) {
return charStr;
}
break;
}
// determine and set charLength / charReceived
this.detectIncompleteChar(buffer);
var end = buffer.length;
if (this.charLength) {
// buffer the incomplete character bytes we got
buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
end -= this.charReceived;
}
charStr += buffer.toString(this.encoding, 0, end);
var end = charStr.length - 1;
var charCode = charStr.charCodeAt(end);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
var size = this.surrogateSize;
this.charLength += size;
this.charReceived += size;
this.charBuffer.copy(this.charBuffer, size, 0, size);
buffer.copy(this.charBuffer, 0, 0, size);
return charStr.substring(0, end);
}
// or just emit the charStr
return charStr;
};
// detectIncompleteChar determines if there is an incomplete UTF-8 character at
// the end of the given buffer. If so, it sets this.charLength to the byte
// length that character, and sets this.charReceived to the number of bytes
// that are available for this character.
StringDecoder.prototype.detectIncompleteChar = function(buffer) {
// determine how many bytes we have to check at the end of this buffer
var i = (buffer.length >= 3) ? 3 : buffer.length;
// Figure out if one of the last i bytes of our buffer announces an
// incomplete char.
for (; i > 0; i--) {
var c = buffer[buffer.length - i];
// See http://en.wikipedia.org/wiki/UTF-8#Description
// 110XXXXX
if (i == 1 && c >> 5 == 0x06) {
this.charLength = 2;
break;
}
// 1110XXXX
if (i <= 2 && c >> 4 == 0x0E) {
this.charLength = 3;
break;
}
// 11110XXX
if (i <= 3 && c >> 3 == 0x1E) {
this.charLength = 4;
break;
}
}
this.charReceived = i;
};
StringDecoder.prototype.end = function(buffer) {
var res = '';
if (buffer && buffer.length)
res = this.write(buffer);
if (this.charReceived) {
var cr = this.charReceived;
var buf = this.charBuffer;
var enc = this.encoding;
res += buf.slice(0, cr).toString(enc);
}
return res;
};
function passThroughWrite(buffer) {
return buffer.toString(this.encoding);
}
function utf16DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 2;
this.charLength = this.charReceived ? 2 : 0;
}
function base64DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 3;
this.charLength = this.charReceived ? 3 : 0;
}
},{"buffer":157}],156:[function(require,module,exports){
(function (Buffer){
module.exports = function xor (a, b) {
var length = Math.min(a.length, b.length)
var buffer = new Buffer(length)
for (var i = 0; i < length; ++i) {
buffer[i] = a[i] ^ b[i]
}
return buffer
}
}).call(this,require("buffer").Buffer)
},{"buffer":157}],157:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <https://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42
} catch (e) {
return false
}
}
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('Invalid typed array length')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (isArrayBuffer(value)) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
return fromObject(value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj) {
if (isArrayBufferView(obj) || 'length' in obj) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (isArrayBufferView(string) || isArrayBuffer(string)) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0
if (isFinite(length)) {
length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if (code < 256) {
val = code
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: new Buffer(val, encoding)
var len = bytes.length
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
function isArrayBuffer (obj) {
return obj instanceof ArrayBuffer ||
(obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
typeof obj.byteLength === 'number')
}
// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
function isArrayBufferView (obj) {
return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
}
function numberIsNaN (obj) {
return obj !== obj // eslint-disable-line no-self-compare
}
},{"base64-js":120,"ieee754":285}],158:[function(require,module,exports){
module.exports = {
"100": "Continue",
"101": "Switching Protocols",
"102": "Processing",
"200": "OK",
"201": "Created",
"202": "Accepted",
"203": "Non-Authoritative Information",
"204": "No Content",
"205": "Reset Content",
"206": "Partial Content",
"207": "Multi-Status",
"208": "Already Reported",
"226": "IM Used",
"300": "Multiple Choices",
"301": "Moved Permanently",
"302": "Found",
"303": "See Other",
"304": "Not Modified",
"305": "Use Proxy",
"307": "Temporary Redirect",
"308": "Permanent Redirect",
"400": "Bad Request",
"401": "Unauthorized",
"402": "Payment Required",
"403": "Forbidden",
"404": "Not Found",
"405": "Method Not Allowed",
"406": "Not Acceptable",
"407": "Proxy Authentication Required",
"408": "Request Timeout",
"409": "Conflict",
"410": "Gone",
"411": "Length Required",
"412": "Precondition Failed",
"413": "Payload Too Large",
"414": "URI Too Long",
"415": "Unsupported Media Type",
"416": "Range Not Satisfiable",
"417": "Expectation Failed",
"418": "I'm a teapot",
"421": "Misdirected Request",
"422": "Unprocessable Entity",
"423": "Locked",
"424": "Failed Dependency",
"425": "Unordered Collection",
"426": "Upgrade Required",
"428": "Precondition Required",
"429": "Too Many Requests",
"431": "Request Header Fields Too Large",
"451": "Unavailable For Legal Reasons",
"500": "Internal Server Error",
"501": "Not Implemented",
"502": "Bad Gateway",
"503": "Service Unavailable",
"504": "Gateway Timeout",
"505": "HTTP Version Not Supported",
"506": "Variant Also Negotiates",
"507": "Insufficient Storage",
"508": "Loop Detected",
"509": "Bandwidth Limit Exceeded",
"510": "Not Extended",
"511": "Network Authentication Required"
}
},{}],159:[function(require,module,exports){
function Caseless (dict) {
this.dict = dict || {}
}
Caseless.prototype.set = function (name, value, clobber) {
if (typeof name === 'object') {
for (var i in name) {
this.set(i, name[i], value)
}
} else {
if (typeof clobber === 'undefined') clobber = true
var has = this.has(name)
if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value
else this.dict[has || name] = value
return has
}
}
Caseless.prototype.has = function (name) {
var keys = Object.keys(this.dict)
, name = name.toLowerCase()
;
for (var i=0;i<keys.length;i++) {
if (keys[i].toLowerCase() === name) return keys[i]
}
return false
}
Caseless.prototype.get = function (name) {
name = name.toLowerCase()
var result, _key
var headers = this.dict
Object.keys(headers).forEach(function (key) {
_key = key.toLowerCase()
if (name === _key) result = headers[key]
})
return result
}
Caseless.prototype.swap = function (name) {
var has = this.has(name)
if (has === name) return
if (!has) throw new Error('There is no header than matches "'+name+'"')
this.dict[name] = this.dict[has]
delete this.dict[has]
}
Caseless.prototype.del = function (name) {
var has = this.has(name)
return delete this.dict[has || name]
}
module.exports = function (dict) {return new Caseless(dict)}
module.exports.httpify = function (resp, headers) {
var c = new Caseless(headers)
resp.setHeader = function (key, value, clobber) {
if (typeof value === 'undefined') return
return c.set(key, value, clobber)
}
resp.hasHeader = function (key) {
return c.has(key)
}
resp.getHeader = function (key) {
return c.get(key)
}
resp.removeHeader = function (key) {
return c.del(key)
}
resp.headers = c.dict
return c
}
},{}],160:[function(require,module,exports){
var Buffer = require('safe-buffer').Buffer
var Transform = require('stream').Transform
var StringDecoder = require('string_decoder').StringDecoder
var inherits = require('inherits')
function CipherBase (hashMode) {
Transform.call(this)
this.hashMode = typeof hashMode === 'string'
if (this.hashMode) {
this[hashMode] = this._finalOrDigest
} else {
this.final = this._finalOrDigest
}
if (this._final) {
this.__final = this._final
this._final = null
}
this._decoder = null
this._encoding = null
}
inherits(CipherBase, Transform)
CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
if (typeof data === 'string') {
data = Buffer.from(data, inputEnc)
}
var outData = this._update(data)
if (this.hashMode) return this
if (outputEnc) {
outData = this._toString(outData, outputEnc)
}
return outData
}
CipherBase.prototype.setAutoPadding = function () {}
CipherBase.prototype.getAuthTag = function () {
throw new Error('trying to get auth tag in unsupported state')
}
CipherBase.prototype.setAuthTag = function () {
throw new Error('trying to set auth tag in unsupported state')
}
CipherBase.prototype.setAAD = function () {
throw new Error('trying to set aad in unsupported state')
}
CipherBase.prototype._transform = function (data, _, next) {
var err
try {
if (this.hashMode) {
this._update(data)
} else {
this.push(this._update(data))
}
} catch (e) {
err = e
} finally {
next(err)
}
}
CipherBase.prototype._flush = function (done) {
var err
try {
this.push(this.__final())
} catch (e) {
err = e
}
done(err)
}
CipherBase.prototype._finalOrDigest = function (outputEnc) {
var outData = this.__final() || Buffer.alloc(0)
if (outputEnc) {
outData = this._toString(outData, outputEnc, true)
}
return outData
}
CipherBase.prototype._toString = function (value, enc, fin) {
if (!this._decoder) {
this._decoder = new StringDecoder(enc)
this._encoding = enc
}
if (this._encoding !== enc) throw new Error('can\'t switch encodings')
var out = this._decoder.write(value)
if (fin) {
out += this._decoder.end()
}
return out
}
module.exports = CipherBase
},{"inherits":287,"safe-buffer":381,"stream":467,"string_decoder":155}],161:[function(require,module,exports){
/**
* slice() reference.
*/
var slice = Array.prototype.slice;
/**
* Expose `co`.
*/
module.exports = co['default'] = co.co = co;
/**
* Wrap the given generator `fn` into a
* function that returns a promise.
* This is a separate function so that
* every `co()` call doesn't create a new,
* unnecessary closure.
*
* @param {GeneratorFunction} fn
* @return {Function}
* @api public
*/
co.wrap = function (fn) {
createPromise.__generatorFunction__ = fn;
return createPromise;
function createPromise() {
return co.call(this, fn.apply(this, arguments));
}
};
/**
* Execute the generator function or a generator
* and return a promise.
*
* @param {Function} fn
* @return {Promise}
* @api public
*/
function co(gen) {
var ctx = this;
var args = slice.call(arguments, 1)
// we wrap everything in a promise to avoid promise chaining,
// which leads to memory leak errors.
// see https://github.com/tj/co/issues/180
return new Promise(function(resolve, reject) {
if (typeof gen === 'function') gen = gen.apply(ctx, args);
if (!gen || typeof gen.next !== 'function') return resolve(gen);
onFulfilled();
/**
* @param {Mixed} res
* @return {Promise}
* @api private
*/
function onFulfilled(res) {
var ret;
try {
ret = gen.next(res);
} catch (e) {
return reject(e);
}
next(ret);
}
/**
* @param {Error} err
* @return {Promise}
* @api private
*/
function onRejected(err) {
var ret;
try {
ret = gen.throw(err);
} catch (e) {
return reject(e);
}
next(ret);
}
/**
* Get the next value in the generator,
* return a promise.
*
* @param {Object} ret
* @return {Promise}
* @api private
*/
function next(ret) {
if (ret.done) return resolve(ret.value);
var value = toPromise.call(ctx, ret.value);
if (value && isPromise(value)) return value.then(onFulfilled, onRejected);
return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, '
+ 'but the following object was passed: "' + String(ret.value) + '"'));
}
});
}
/**
* Convert a `yield`ed value into a promise.
*
* @param {Mixed} obj
* @return {Promise}
* @api private
*/
function toPromise(obj) {
if (!obj) return obj;
if (isPromise(obj)) return obj;
if (isGeneratorFunction(obj) || isGenerator(obj)) return co.call(this, obj);
if ('function' == typeof obj) return thunkToPromise.call(this, obj);
if (Array.isArray(obj)) return arrayToPromise.call(this, obj);
if (isObject(obj)) return objectToPromise.call(this, obj);
return obj;
}
/**
* Convert a thunk to a promise.
*
* @param {Function}
* @return {Promise}
* @api private
*/
function thunkToPromise(fn) {
var ctx = this;
return new Promise(function (resolve, reject) {
fn.call(ctx, function (err, res) {
if (err) return reject(err);
if (arguments.length > 2) res = slice.call(arguments, 1);
resolve(res);
});
});
}
/**
* Convert an array of "yieldables" to a promise.
* Uses `Promise.all()` internally.
*
* @param {Array} obj
* @return {Promise}
* @api private
*/
function arrayToPromise(obj) {
return Promise.all(obj.map(toPromise, this));
}
/**
* Convert an object of "yieldables" to a promise.
* Uses `Promise.all()` internally.
*
* @param {Object} obj
* @return {Promise}
* @api private
*/
function objectToPromise(obj){
var results = new obj.constructor();
var keys = Object.keys(obj);
var promises = [];
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var promise = toPromise.call(this, obj[key]);
if (promise && isPromise(promise)) defer(promise, key);
else results[key] = obj[key];
}
return Promise.all(promises).then(function () {
return results;
});
function defer(promise, key) {
// predefine the key in the result
results[key] = undefined;
promises.push(promise.then(function (res) {
results[key] = res;
}));
}
}
/**
* Check if `obj` is a promise.
*
* @param {Object} obj
* @return {Boolean}
* @api private
*/
function isPromise(obj) {
return 'function' == typeof obj.then;
}
/**
* Check if `obj` is a generator.
*
* @param {Mixed} obj
* @return {Boolean}
* @api private
*/
function isGenerator(obj) {
return 'function' == typeof obj.next && 'function' == typeof obj.throw;
}
/**
* Check if `obj` is a generator function.
*
* @param {Mixed} obj
* @return {Boolean}
* @api private
*/
function isGeneratorFunction(obj) {
var constructor = obj.constructor;
if (!constructor) return false;
if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true;
return isGenerator(constructor.prototype);
}
/**
* Check for plain object.
*
* @param {Mixed} val
* @return {Boolean}
* @api private
*/
function isObject(val) {
return Object == val.constructor;
}
},{}],162:[function(require,module,exports){
(function (Buffer){
var util = require('util');
var Stream = require('stream').Stream;
var DelayedStream = require('delayed-stream');
module.exports = CombinedStream;
function CombinedStream() {
this.writable = false;
this.readable = true;
this.dataSize = 0;
this.maxDataSize = 2 * 1024 * 1024;
this.pauseStreams = true;
this._released = false;
this._streams = [];
this._currentStream = null;
}
util.inherits(CombinedStream, Stream);
CombinedStream.create = function(options) {
var combinedStream = new this();
options = options || {};
for (var option in options) {
combinedStream[option] = options[option];
}
return combinedStream;
};
CombinedStream.isStreamLike = function(stream) {
return (typeof stream !== 'function')
&& (typeof stream !== 'string')
&& (typeof stream !== 'boolean')
&& (typeof stream !== 'number')
&& (!Buffer.isBuffer(stream));
};
CombinedStream.prototype.append = function(stream) {
var isStreamLike = CombinedStream.isStreamLike(stream);
if (isStreamLike) {
if (!(stream instanceof DelayedStream)) {
var newStream = DelayedStream.create(stream, {
maxDataSize: Infinity,
pauseStream: this.pauseStreams,
});
stream.on('data', this._checkDataSize.bind(this));
stream = newStream;
}
this._handleErrors(stream);
if (this.pauseStreams) {
stream.pause();
}
}
this._streams.push(stream);
return this;
};
CombinedStream.prototype.pipe = function(dest, options) {
Stream.prototype.pipe.call(this, dest, options);
this.resume();
return dest;
};
CombinedStream.prototype._getNext = function() {
this._currentStream = null;
var stream = this._streams.shift();
if (typeof stream == 'undefined') {
this.end();
return;
}
if (typeof stream !== 'function') {
this._pipeNext(stream);
return;
}
var getStream = stream;
getStream(function(stream) {
var isStreamLike = CombinedStream.isStreamLike(stream);
if (isStreamLike) {
stream.on('data', this._checkDataSize.bind(this));
this._handleErrors(stream);
}
this._pipeNext(stream);
}.bind(this));
};
CombinedStream.prototype._pipeNext = function(stream) {
this._currentStream = stream;
var isStreamLike = CombinedStream.isStreamLike(stream);
if (isStreamLike) {
stream.on('end', this._getNext.bind(this));
stream.pipe(this, {end: false});
return;
}
var value = stream;
this.write(value);
this._getNext();
};
CombinedStream.prototype._handleErrors = function(stream) {
var self = this;
stream.on('error', function(err) {
self._emitError(err);
});
};
CombinedStream.prototype.write = function(data) {
this.emit('data', data);
};
CombinedStream.prototype.pause = function() {
if (!this.pauseStreams) {
return;
}
if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause();
this.emit('pause');
};
CombinedStream.prototype.resume = function() {
if (!this._released) {
this._released = true;
this.writable = true;
this._getNext();
}
if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume();
this.emit('resume');
};
CombinedStream.prototype.end = function() {
this._reset();
this.emit('end');
};
CombinedStream.prototype.destroy = function() {
this._reset();
this.emit('close');
};
CombinedStream.prototype._reset = function() {
this.writable = false;
this._streams = [];
this._currentStream = null;
};
CombinedStream.prototype._checkDataSize = function() {
this._updateDataSize();
if (this.dataSize <= this.maxDataSize) {
return;
}
var message =
'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
this._emitError(new Error(message));
};
CombinedStream.prototype._updateDataSize = function() {
this.dataSize = 0;
var self = this;
this._streams.forEach(function(stream) {
if (!stream.dataSize) {
return;
}
self.dataSize += stream.dataSize;
});
if (this._currentStream && this._currentStream.dataSize) {
this.dataSize += this._currentStream.dataSize;
}
};
CombinedStream.prototype._emitError = function(err) {
this._reset();
this.emit('error', err);
};
}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
},{"../../is-buffer/index.js":288,"delayed-stream":207,"stream":467,"util":491}],163:[function(require,module,exports){
(function (Buffer){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
},{"../../is-buffer/index.js":288}],164:[function(require,module,exports){
(function (Buffer){
var elliptic = require('elliptic');
var BN = require('bn.js');
module.exports = function createECDH(curve) {
return new ECDH(curve);
};
var aliases = {
secp256k1: {
name: 'secp256k1',
byteLength: 32
},
secp224r1: {
name: 'p224',
byteLength: 28
},
prime256v1: {
name: 'p256',
byteLength: 32
},
prime192v1: {
name: 'p192',
byteLength: 24
},
ed25519: {
name: 'ed25519',
byteLength: 32
},
secp384r1: {
name: 'p384',
byteLength: 48
},
secp521r1: {
name: 'p521',
byteLength: 66
}
};
aliases.p224 = aliases.secp224r1;
aliases.p256 = aliases.secp256r1 = aliases.prime256v1;
aliases.p192 = aliases.secp192r1 = aliases.prime192v1;
aliases.p384 = aliases.secp384r1;
aliases.p521 = aliases.secp521r1;
function ECDH(curve) {
this.curveType = aliases[curve];
if (!this.curveType ) {
this.curveType = {
name: curve
};
}
this.curve = new elliptic.ec(this.curveType.name);
this.keys = void 0;
}
ECDH.prototype.generateKeys = function (enc, format) {
this.keys = this.curve.genKeyPair();
return this.getPublicKey(enc, format);
};
ECDH.prototype.computeSecret = function (other, inenc, enc) {
inenc = inenc || 'utf8';
if (!Buffer.isBuffer(other)) {
other = new Buffer(other, inenc);
}
var otherPub = this.curve.keyFromPublic(other).getPublic();
var out = otherPub.mul(this.keys.getPrivate()).getX();
return formatReturnValue(out, enc, this.curveType.byteLength);
};
ECDH.prototype.getPublicKey = function (enc, format) {
var key = this.keys.getPublic(format === 'compressed', true);
if (format === 'hybrid') {
if (key[key.length - 1] % 2) {
key[0] = 7;
} else {
key [0] = 6;
}
}
return formatReturnValue(key, enc);
};
ECDH.prototype.getPrivateKey = function (enc) {
return formatReturnValue(this.keys.getPrivate(), enc);
};
ECDH.prototype.setPublicKey = function (pub, enc) {
enc = enc || 'utf8';
if (!Buffer.isBuffer(pub)) {
pub = new Buffer(pub, enc);
}
this.keys._importPublic(pub);
return this;
};
ECDH.prototype.setPrivateKey = function (priv, enc) {
enc = enc || 'utf8';
if (!Buffer.isBuffer(priv)) {
priv = new Buffer(priv, enc);
}
var _priv = new BN(priv);
_priv = _priv.toString(16);
this.keys._importPrivate(_priv);
return this;
};
function formatReturnValue(bn, enc, len) {
if (!Array.isArray(bn)) {
bn = bn.toArray();
}
var buf = new Buffer(bn);
if (len && buf.length < len) {
var zeros = new Buffer(len - buf.length);
zeros.fill(0);
buf = Buffer.concat([zeros, buf]);
}
if (!enc) {
return buf;
} else {
return buf.toString(enc);
}
}
}).call(this,require("buffer").Buffer)
},{"bn.js":122,"buffer":157,"elliptic":221}],165:[function(require,module,exports){
(function (Buffer){
'use strict'
var inherits = require('inherits')
var md5 = require('./md5')
var RIPEMD160 = require('ripemd160')
var sha = require('sha.js')
var Base = require('cipher-base')
function HashNoConstructor (hash) {
Base.call(this, 'digest')
this._hash = hash
this.buffers = []
}
inherits(HashNoConstructor, Base)
HashNoConstructor.prototype._update = function (data) {
this.buffers.push(data)
}
HashNoConstructor.prototype._final = function () {
var buf = Buffer.concat(this.buffers)
var r = this._hash(buf)
this.buffers = null
return r
}
function Hash (hash) {
Base.call(this, 'digest')
this._hash = hash
}
inherits(Hash, Base)
Hash.prototype._update = function (data) {
this._hash.update(data)
}
Hash.prototype._final = function () {
return this._hash.digest()
}
module.exports = function createHash (alg) {
alg = alg.toLowerCase()
if (alg === 'md5') return new HashNoConstructor(md5)
if (alg === 'rmd160' || alg === 'ripemd160') return new Hash(new RIPEMD160())
return new Hash(sha(alg))
}
}).call(this,require("buffer").Buffer)
},{"./md5":167,"buffer":157,"cipher-base":160,"inherits":287,"ripemd160":380,"sha.js":383}],166:[function(require,module,exports){
(function (Buffer){
'use strict'
var intSize = 4
var zeroBuffer = new Buffer(intSize)
zeroBuffer.fill(0)
var charSize = 8
var hashSize = 16
function toArray (buf) {
if ((buf.length % intSize) !== 0) {
var len = buf.length + (intSize - (buf.length % intSize))
buf = Buffer.concat([buf, zeroBuffer], len)
}
var arr = new Array(buf.length >>> 2)
for (var i = 0, j = 0; i < buf.length; i += intSize, j++) {
arr[j] = buf.readInt32LE(i)
}
return arr
}
module.exports = function hash (buf, fn) {
var arr = fn(toArray(buf), buf.length * charSize)
buf = new Buffer(hashSize)
for (var i = 0; i < arr.length; i++) {
buf.writeInt32LE(arr[i], i << 2, true)
}
return buf
}
}).call(this,require("buffer").Buffer)
},{"buffer":157}],167:[function(require,module,exports){
'use strict'
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
var makeHash = require('./make-hash')
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
function core_md5 (x, len) {
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32)
x[(((len + 64) >>> 9) << 4) + 14] = len
var a = 1732584193
var b = -271733879
var c = -1732584194
var d = 271733878
for (var i = 0; i < x.length; i += 16) {
var olda = a
var oldb = b
var oldc = c
var oldd = d
a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936)
d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586)
c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819)
b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330)
a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897)
d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426)
c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341)
b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983)
a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416)
d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417)
c = md5_ff(c, d, a, b, x[i + 10], 17, -42063)
b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162)
a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682)
d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101)
c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290)
b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329)
a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510)
d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632)
c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713)
b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302)
a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691)
d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083)
c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335)
b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848)
a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438)
d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690)
c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961)
b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501)
a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467)
d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784)
c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473)
b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734)
a = md5_hh(a, b, c, d, x[i + 5], 4, -378558)
d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463)
c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562)
b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556)
a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060)
d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353)
c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632)
b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640)
a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174)
d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222)
c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979)
b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189)
a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487)
d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835)
c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520)
b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651)
a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844)
d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415)
c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905)
b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055)
a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571)
d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606)
c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523)
b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799)
a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359)
d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744)
c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380)
b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649)
a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070)
d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379)
c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259)
b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551)
a = safe_add(a, olda)
b = safe_add(b, oldb)
c = safe_add(c, oldc)
d = safe_add(d, oldd)
}
return [a, b, c, d]
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn (q, a, b, x, s, t) {
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
}
function md5_ff (a, b, c, d, x, s, t) {
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t)
}
function md5_gg (a, b, c, d, x, s, t) {
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t)
}
function md5_hh (a, b, c, d, x, s, t) {
return md5_cmn(b ^ c ^ d, a, b, x, s, t)
}
function md5_ii (a, b, c, d, x, s, t) {
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t)
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add (x, y) {
var lsw = (x & 0xFFFF) + (y & 0xFFFF)
var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
return (msw << 16) | (lsw & 0xFFFF)
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol (num, cnt) {
return (num << cnt) | (num >>> (32 - cnt))
}
module.exports = function md5 (buf) {
return makeHash(buf, core_md5)
}
},{"./make-hash":166}],168:[function(require,module,exports){
'use strict'
var inherits = require('inherits')
var Legacy = require('./legacy')
var Base = require('cipher-base')
var Buffer = require('safe-buffer').Buffer
var md5 = require('create-hash/md5')
var RIPEMD160 = require('ripemd160')
var sha = require('sha.js')
var ZEROS = Buffer.alloc(128)
function Hmac (alg, key) {
Base.call(this, 'digest')
if (typeof key === 'string') {
key = Buffer.from(key)
}
var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
this._alg = alg
this._key = key
if (key.length > blocksize) {
var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
key = hash.update(key).digest()
} else if (key.length < blocksize) {
key = Buffer.concat([key, ZEROS], blocksize)
}
var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
var opad = this._opad = Buffer.allocUnsafe(blocksize)
for (var i = 0; i < blocksize; i++) {
ipad[i] = key[i] ^ 0x36
opad[i] = key[i] ^ 0x5C
}
this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
this._hash.update(ipad)
}
inherits(Hmac, Base)
Hmac.prototype._update = function (data) {
this._hash.update(data)
}
Hmac.prototype._final = function () {
var h = this._hash.digest()
var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
return hash.update(this._opad).update(h).digest()
}
module.exports = function createHmac (alg, key) {
alg = alg.toLowerCase()
if (alg === 'rmd160' || alg === 'ripemd160') {
return new Hmac('rmd160', key)
}
if (alg === 'md5') {
return new Legacy(md5, key)
}
return new Hmac(alg, key)
}
},{"./legacy":169,"cipher-base":160,"create-hash/md5":167,"inherits":287,"ripemd160":380,"safe-buffer":381,"sha.js":383}],169:[function(require,module,exports){
'use strict'
var inherits = require('inherits')
var Buffer = require('safe-buffer').Buffer
var Base = require('cipher-base')
var ZEROS = Buffer.alloc(128)
var blocksize = 64
function Hmac (alg, key) {
Base.call(this, 'digest')
if (typeof key === 'string') {
key = Buffer.from(key)
}
this._alg = alg
this._key = key
if (key.length > blocksize) {
key = alg(key)
} else if (key.length < blocksize) {
key = Buffer.concat([key, ZEROS], blocksize)
}
var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
var opad = this._opad = Buffer.allocUnsafe(blocksize)
for (var i = 0; i < blocksize; i++) {
ipad[i] = key[i] ^ 0x36
opad[i] = key[i] ^ 0x5C
}
this._hash = [ipad]
}
inherits(Hmac, Base)
Hmac.prototype._update = function (data) {
this._hash.push(data)
}
Hmac.prototype._final = function () {
var h = this._alg(Buffer.concat(this._hash))
return this._alg(Buffer.concat([this._opad, h]))
}
module.exports = Hmac
},{"cipher-base":160,"inherits":287,"safe-buffer":381}],170:[function(require,module,exports){
'use strict'
exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes')
exports.createHash = exports.Hash = require('create-hash')
exports.createHmac = exports.Hmac = require('create-hmac')
var algos = require('browserify-sign/algos')
var algoKeys = Object.keys(algos)
var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys)
exports.getHashes = function () {
return hashes
}
var p = require('pbkdf2')
exports.pbkdf2 = p.pbkdf2
exports.pbkdf2Sync = p.pbkdf2Sync
var aes = require('browserify-cipher')
exports.Cipher = aes.Cipher
exports.createCipher = aes.createCipher
exports.Cipheriv = aes.Cipheriv
exports.createCipheriv = aes.createCipheriv
exports.Decipher = aes.Decipher
exports.createDecipher = aes.createDecipher
exports.Decipheriv = aes.Decipheriv
exports.createDecipheriv = aes.createDecipheriv
exports.getCiphers = aes.getCiphers
exports.listCiphers = aes.listCiphers
var dh = require('diffie-hellman')
exports.DiffieHellmanGroup = dh.DiffieHellmanGroup
exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup
exports.getDiffieHellman = dh.getDiffieHellman
exports.createDiffieHellman = dh.createDiffieHellman
exports.DiffieHellman = dh.DiffieHellman
var sign = require('browserify-sign')
exports.createSign = sign.createSign
exports.Sign = sign.Sign
exports.createVerify = sign.createVerify
exports.Verify = sign.Verify
exports.createECDH = require('create-ecdh')
var publicEncrypt = require('public-encrypt')
exports.publicEncrypt = publicEncrypt.publicEncrypt
exports.privateEncrypt = publicEncrypt.privateEncrypt
exports.publicDecrypt = publicEncrypt.publicDecrypt
exports.privateDecrypt = publicEncrypt.privateDecrypt
// the least I can do is make error messages for the rest of the node.js/crypto api.
// ;[
// 'createCredentials'
// ].forEach(function (name) {
// exports[name] = function () {
// throw new Error([
// 'sorry, ' + name + ' is not implemented yet',
// 'we accept pull requests',
// 'https://github.com/crypto-browserify/crypto-browserify'
// ].join('\n'))
// }
// })
var rf = require('randomfill')
exports.randomFill = rf.randomFill
exports.randomFillSync = rf.randomFillSync
exports.createCredentials = function () {
throw new Error([
'sorry, createCredentials is not implemented yet',
'we accept pull requests',
'https://github.com/crypto-browserify/crypto-browserify'
].join('\n'))
}
exports.constants = {
'DH_CHECK_P_NOT_SAFE_PRIME': 2,
'DH_CHECK_P_NOT_PRIME': 1,
'DH_UNABLE_TO_CHECK_GENERATOR': 4,
'DH_NOT_SUITABLE_GENERATOR': 8,
'NPN_ENABLED': 1,
'ALPN_ENABLED': 1,
'RSA_PKCS1_PADDING': 1,
'RSA_SSLV23_PADDING': 2,
'RSA_NO_PADDING': 3,
'RSA_PKCS1_OAEP_PADDING': 4,
'RSA_X931_PADDING': 5,
'RSA_PKCS1_PSS_PADDING': 6,
'POINT_CONVERSION_COMPRESSED': 2,
'POINT_CONVERSION_UNCOMPRESSED': 4,
'POINT_CONVERSION_HYBRID': 6
}
},{"browserify-cipher":142,"browserify-sign":149,"browserify-sign/algos":146,"create-ecdh":164,"create-hash":165,"create-hmac":168,"diffie-hellman":214,"pbkdf2":329,"public-encrypt":337,"randombytes":352,"randomfill":353}],171:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./enc-base64"), require("./md5"), require("./evpkdf"), require("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Lookup tables
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX_0 = [];
var SUB_MIX_1 = [];
var SUB_MIX_2 = [];
var SUB_MIX_3 = [];
var INV_SUB_MIX_0 = [];
var INV_SUB_MIX_1 = [];
var INV_SUB_MIX_2 = [];
var INV_SUB_MIX_3 = [];
// Compute lookup tables
(function () {
// Compute double table
var d = [];
for (var i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; i++) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX_0[x] = (t << 24) | (t >>> 8);
SUB_MIX_1[x] = (t << 16) | (t >>> 16);
SUB_MIX_2[x] = (t << 8) | (t >>> 24);
SUB_MIX_3[x] = t;
// Compute inv sub bytes, inv mix columns tables
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX_3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
}());
// Precomputed Rcon lookup
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
/**
* AES block cipher algorithm.
*/
var AES = C_algo.AES = BlockCipher.extend({
_doReset: function () {
// Skip reset of nRounds has been set before and key did not change
if (this._nRounds && this._keyPriorReset === this._key) {
return;
}
// Shortcuts
var key = this._keyPriorReset = this._key;
var keyWords = key.words;
var keySize = key.sigBytes / 4;
// Compute number of rounds
var nRounds = this._nRounds = keySize + 6;
// Compute number of key schedule rows
var ksRows = (nRounds + 1) * 4;
// Compute key schedule
var keySchedule = this._keySchedule = [];
for (var ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
keySchedule[ksRow] = keyWords[ksRow];
} else {
var t = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
// Rot word
t = (t << 8) | (t >>> 24);
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
// Mix Rcon
t ^= RCON[(ksRow / keySize) | 0] << 24;
} else if (keySize > 6 && ksRow % keySize == 4) {
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
}
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
}
}
// Compute inv key schedule
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t = keySchedule[ksRow];
} else {
var t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
}
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function (M, offset) {
// Swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
// Inv swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
},
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
// Shortcut
var nRounds = this._nRounds;
// Get input, add round key
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s2 = M[offset + 2] ^ keySchedule[2];
var s3 = M[offset + 3] ^ keySchedule[3];
// Key schedule row counter
var ksRow = 4;
// Rounds
for (var round = 1; round < nRounds; round++) {
// Shift rows, sub bytes, mix columns, add round key
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Shift rows, sub bytes, add round key
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
// Set output
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t2;
M[offset + 3] = t3;
},
keySize: 256/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
*/
C.AES = BlockCipher._createHelper(AES);
}());
return CryptoJS.AES;
}));
},{"./cipher-core":172,"./core":173,"./enc-base64":174,"./evpkdf":176,"./md5":181}],172:[function(require,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(require("./core"), require("./evpkdf"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./evpkdf"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher core components.
*/
CryptoJS.lib.Cipher || (function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var Base64 = C_enc.Base64;
var C_algo = C.algo;
var EvpKDF = C_algo.EvpKDF;
/**
* Abstract base cipher template.
*
* @property {number} keySize This cipher's key size. Default: 4 (128 bits)
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
*/
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*
* @property {WordArray} iv The IV to use for this operation.
*/
cfg: Base.extend(),
/**
* Creates this cipher in encryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
*/
createEncryptor: function (key, cfg) {
return this.create(this._ENC_XFORM_MODE, key, cfg);
},
/**
* Creates this cipher in decryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
*/
createDecryptor: function (key, cfg) {
return this.create(this._DEC_XFORM_MODE, key, cfg);
},
/**
* Initializes a newly created cipher.
*
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @example
*
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
*/
init: function (xformMode, key, cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Store transform mode and key
this._xformMode = xformMode;
this._key = key;
// Set initial values
this.reset();
},
/**
* Resets this cipher to its initial state.
*
* @example
*
* cipher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-cipher logic
this._doReset();
},
/**
* Adds data to be encrypted or decrypted.
*
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
*
* @return {WordArray} The data after processing.
*
* @example
*
* var encrypted = cipher.process('data');
* var encrypted = cipher.process(wordArray);
*/
process: function (dataUpdate) {
// Append
this._append(dataUpdate);
// Process available blocks
return this._process();
},
/**
* Finalizes the encryption or decryption process.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
*
* @return {WordArray} The data after final processing.
*
* @example
*
* var encrypted = cipher.finalize();
* var encrypted = cipher.finalize('data');
* var encrypted = cipher.finalize(wordArray);
*/
finalize: function (dataUpdate) {
// Final data update
if (dataUpdate) {
this._append(dataUpdate);
}
// Perform concrete-cipher logic
var finalProcessedData = this._doFinalize();
return finalProcessedData;
},
keySize: 128/32,
ivSize: 128/32,
_ENC_XFORM_MODE: 1,
_DEC_XFORM_MODE: 2,
/**
* Creates shortcut functions to a cipher's object interface.
*
* @param {Cipher} cipher The cipher to create a helper for.
*
* @return {Object} An object with encrypt and decrypt shortcut functions.
*
* @static
*
* @example
*
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
*/
_createHelper: (function () {
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
return function (cipher) {
return {
encrypt: function (message, key, cfg) {
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
},
decrypt: function (ciphertext, key, cfg) {
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
}
};
};
}())
});
/**
* Abstract base stream cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
*/
var StreamCipher = C_lib.StreamCipher = Cipher.extend({
_doFinalize: function () {
// Process partial blocks
var finalProcessedBlocks = this._process(!!'flush');
return finalProcessedBlocks;
},
blockSize: 1
});
/**
* Mode namespace.
*/
var C_mode = C.mode = {};
/**
* Abstract base block cipher mode template.
*/
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
/**
* Creates this mode for encryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
*/
createEncryptor: function (cipher, iv) {
return this.Encryptor.create(cipher, iv);
},
/**
* Creates this mode for decryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
*/
createDecryptor: function (cipher, iv) {
return this.Decryptor.create(cipher, iv);
},
/**
* Initializes a newly created mode.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @example
*
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
*/
init: function (cipher, iv) {
this._cipher = cipher;
this._iv = iv;
}
});
/**
* Cipher Block Chaining mode.
*/
var CBC = C_mode.CBC = (function () {
/**
* Abstract base CBC mode.
*/
var CBC = BlockCipherMode.extend();
/**
* CBC encryptor.
*/
CBC.Encryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// XOR and encrypt
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
/**
* CBC decryptor.
*/
CBC.Decryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
// Decrypt and XOR
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
// Shortcut
var iv = this._iv;
// Choose mixing block
if (iv) {
var block = iv;
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var block = this._prevBlock;
}
// XOR blocks
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= block[i];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment