PHP WebShell
Текущая директория: /usr/lib/node_modules/bitgo/node_modules/stellar-sdk/dist
Просмотр файла: stellar-sdk.js
var StellarSdk =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 176);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _curr_generated = __webpack_require__(199);
var _curr_generated2 = _interopRequireDefault(_curr_generated);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = _curr_generated2.default;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
var base64 = __webpack_require__(192)
var ieee754 = __webpack_require__(193)
var isArray = __webpack_require__(99)
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use 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+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport()
/*
* Export kMaxLength after typed array support is determined.
*/
exports.kMaxLength = kMaxLength()
function typedArraySupport () {
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
}
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
function createBuffer (that, length) {
if (kMaxLength() < length) {
throw new RangeError('Invalid typed array length')
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array(length)
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
if (that === null) {
that = new Buffer(length)
}
that.length = length
}
return that
}
/**
* 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) {
if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
return new 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(this, arg)
}
return from(this, arg, encodingOrOffset, length)
}
Buffer.poolSize = 8192 // not used by this implementation
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
arr.__proto__ = Buffer.prototype
return arr
}
function from (that, value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
return fromArrayBuffer(that, value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(that, value, encodingOrOffset)
}
return fromObject(that, 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(null, value, encodingOrOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true
})
}
}
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 (that, size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(that, 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(that, size).fill(fill, encoding)
: createBuffer(that, size).fill(fill)
}
return createBuffer(that, size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(null, size, fill, encoding)
}
function allocUnsafe (that, size) {
assertSize(size)
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < size; ++i) {
that[i] = 0
}
}
return that
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(null, size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(null, size)
}
function fromString (that, 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
that = createBuffer(that, length)
var actual = that.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')
that = that.slice(0, actual)
}
return that
}
function fromArrayLike (that, array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
that = createBuffer(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function fromArrayBuffer (that, array, byteOffset, length) {
array.byteLength // this throws if `array` is not a valid ArrayBuffer
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')
}
if (byteOffset === undefined && length === undefined) {
array = new Uint8Array(array)
} else if (length === undefined) {
array = new Uint8Array(array, byteOffset)
} else {
array = new Uint8Array(array, byteOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = array
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
that = fromArrayLike(that, array)
}
return that
}
function fromObject (that, obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
that = createBuffer(that, len)
if (that.length === 0) {
return that
}
obj.copy(that, 0, 0, len)
return that
}
if (obj) {
if ((typeof ArrayBuffer !== 'undefined' &&
obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
if (typeof obj.length !== 'number' || isnan(obj.length)) {
return createBuffer(that, 0)
}
return fromArrayLike(that, obj)
}
if (obj.type === 'Buffer' && isArray(obj.data)) {
return fromArrayLike(that, 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 < kMaxLength()` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().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)
}
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 (!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 (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
(ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
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
}
}
}
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
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 | 0
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 (isNaN(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 (Buffer.TYPED_ARRAY_SUPPORT &&
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 (isNaN(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
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} 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
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = this.subarray(start, end)
newBuf.__proto__ = Buffer.prototype
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; ++i) {
newBuf[i] = this[i + start]
}
}
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) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
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) {
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) {
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) {
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) {
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) {
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) {
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) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
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)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = (value & 0xff)
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
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)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, true)
}
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)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
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 (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
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)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
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)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
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)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
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
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
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) {
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) {
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 || !Buffer.TYPED_ARRAY_SUPPORT) {
// 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
: utf8ToBytes(new Buffer(val, encoding).toString())
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 = stringtrim(str).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 stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
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
}
function isnan (val) {
return val !== val // eslint-disable-line no-self-compare
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5)))
/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__createBinding", function() { return __createBinding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spreadArrays", function() { return __spreadArrays; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__classPrivateFieldGet", function() { return __classPrivateFieldGet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__classPrivateFieldSet", function() { return __classPrivateFieldSet; });
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
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.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}
return __assign.apply(this, arguments);
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __createBinding(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}
function __exportStar(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
/***/ }),
/* 3 */
/***/ (function(module, exports) {
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
module.exports = isArray;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = includeIoMixin;
var _extend = __webpack_require__(200);
var _extend2 = _interopRequireDefault(_extend);
var _isFunction = __webpack_require__(50);
var _isFunction2 = _interopRequireDefault(_isFunction);
var _cursor = __webpack_require__(213);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// TODO: build a system to grow a buffer as we write to it
var BUFFER_SIZE = Math.pow(2, 16);
var staticMethods = {
toXDR: function toXDR(val) {
var cursor = new _cursor.Cursor(BUFFER_SIZE);
this.write(val, cursor);
var bytesWritten = cursor.tell();
cursor.rewind();
return cursor.slice(bytesWritten).buffer();
},
fromXDR: function fromXDR(input) {
var format = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'raw';
var buffer = void 0;
switch (format) {
case 'raw':
buffer = input;
break;
case 'hex':
buffer = Buffer.from(input, 'hex');
break;
case 'base64':
buffer = Buffer.from(input, 'base64');
break;
default:
throw new Error('Invalid format ' + format + ', must be "raw", "hex", "base64"');
}
var cursor = new _cursor.Cursor(buffer);
var result = this.read(cursor);
// TODO: error out if the entire buffer isn't consumed
return result;
},
validateXDR: function validateXDR(input) {
var format = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'raw';
try {
this.fromXDR(input, format);
return true;
} catch (e) {
return false;
}
}
};
var instanceMethods = {
toXDR: function toXDR() {
var format = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'raw';
var buffer = this.constructor.toXDR(this);
switch (format) {
case 'raw':
return buffer;
case 'hex':
return buffer.toString('hex');
case 'base64':
return buffer.toString('base64');
default:
throw new Error('Invalid format ' + format + ', must be "raw", "hex", "base64"');
}
}
};
function includeIoMixin(obj) {
(0, _extend2.default)(obj, staticMethods);
if ((0, _isFunction2.default)(obj)) {
(0, _extend2.default)(obj.prototype, instanceMethods);
}
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 5 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || new Function("return this")();
} catch (e) {
// This works if the window reference is available
if (typeof window === "object") g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.CallBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var detect_node_1 = tslib_1.__importDefault(__webpack_require__(372));
var urijs_1 = tslib_1.__importDefault(__webpack_require__(37));
var URITemplate_1 = tslib_1.__importDefault(__webpack_require__(373));
var errors_1 = __webpack_require__(36);
var horizon_axios_client_1 = tslib_1.__importDefault(__webpack_require__(91));
var version = __webpack_require__(65).version;
var JOINABLE = ["transaction"];
var EventSource;
var anyGlobal = global;
if (anyGlobal.EventSource) {
EventSource = anyGlobal.EventSource;
}
else if (detect_node_1.default) {
EventSource = __webpack_require__(164);
}
else if (anyGlobal.window.EventSource) {
EventSource = anyGlobal.window.EventSource;
}
else {
EventSource = __webpack_require__(164);
}
var CallBuilder = (function () {
function CallBuilder(serverUrl, neighborRoot) {
if (neighborRoot === void 0) { neighborRoot = ""; }
this.url = serverUrl.clone();
this.filter = [];
this.originalSegments = this.url.segment() || [];
this.neighborRoot = neighborRoot;
}
CallBuilder.prototype.call = function () {
var _this = this;
this.checkFilter();
return this._sendNormalRequest(this.url).then(function (r) {
return _this._parseResponse(r);
});
};
CallBuilder.prototype.stream = function (options) {
var _this = this;
if (options === void 0) { options = {}; }
this.checkFilter();
this.url.setQuery("X-Client-Name", "js-stellar-sdk");
this.url.setQuery("X-Client-Version", version);
var es;
var timeout;
var createTimeout = function () {
timeout = setTimeout(function () {
if (es) {
es.close();
}
es = createEventSource();
}, options.reconnectTimeout || 15 * 1000);
};
var createEventSource = function () {
try {
es = new EventSource(_this.url.toString());
}
catch (err) {
if (options.onerror) {
options.onerror(err);
}
}
createTimeout();
if (es) {
var closed_1 = false;
var onClose_1 = function () {
if (closed_1) {
return;
}
clearTimeout(timeout);
es.close();
createEventSource();
closed_1 = true;
};
var onMessage = function (message) {
if (message.type === "close") {
onClose_1();
return;
}
var result = message.data
? _this._parseRecord(JSON.parse(message.data))
: message;
if (result.paging_token) {
_this.url.setQuery("cursor", result.paging_token);
}
clearTimeout(timeout);
createTimeout();
if (typeof options.onmessage !== "undefined") {
options.onmessage(result);
}
};
var onError = function (error) {
if (options.onerror) {
options.onerror(error);
}
};
if (es.addEventListener) {
es.addEventListener("message", onMessage.bind(_this));
es.addEventListener("error", onError.bind(_this));
es.addEventListener("close", onClose_1.bind(_this));
}
else {
es.onmessage = onMessage.bind(_this);
es.onerror = onError.bind(_this);
}
}
return es;
};
createEventSource();
return function close() {
clearTimeout(timeout);
if (es) {
es.close();
}
};
};
CallBuilder.prototype.cursor = function (cursor) {
this.url.setQuery("cursor", cursor);
return this;
};
CallBuilder.prototype.limit = function (recordsNumber) {
this.url.setQuery("limit", recordsNumber.toString());
return this;
};
CallBuilder.prototype.order = function (direction) {
this.url.setQuery("order", direction);
return this;
};
CallBuilder.prototype.join = function (include) {
this.url.setQuery("join", include);
return this;
};
CallBuilder.prototype.forEndpoint = function (endpoint, param) {
if (this.neighborRoot === "") {
throw new Error("Invalid usage: neighborRoot not set in constructor");
}
this.filter.push([endpoint, param, this.neighborRoot]);
return this;
};
CallBuilder.prototype.checkFilter = function () {
if (this.filter.length >= 2) {
throw new errors_1.BadRequestError("Too many filters specified", this.filter);
}
if (this.filter.length === 1) {
var newSegment = this.originalSegments.concat(this.filter[0]);
this.url.segment(newSegment);
}
};
CallBuilder.prototype._requestFnForLink = function (link) {
var _this = this;
return function (opts) {
if (opts === void 0) { opts = {}; }
return tslib_1.__awaiter(_this, void 0, void 0, function () {
var uri, template, r;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
if (link.templated) {
template = URITemplate_1.default(link.href);
uri = urijs_1.default(template.expand(opts));
}
else {
uri = urijs_1.default(link.href);
}
return [4, this._sendNormalRequest(uri)];
case 1:
r = _a.sent();
return [2, this._parseResponse(r)];
}
});
});
};
};
CallBuilder.prototype._parseRecord = function (json) {
var _this = this;
if (!json._links) {
return json;
}
var _loop_1 = function (key) {
var n = json._links[key];
var included = false;
if (typeof json[key] !== "undefined") {
json[key + "_attr"] = json[key];
included = true;
}
if (included && JOINABLE.indexOf(key) >= 0) {
var record_1 = this_1._parseRecord(json[key]);
json[key] = function () { return tslib_1.__awaiter(_this, void 0, void 0, function () { return tslib_1.__generator(this, function (_a) {
return [2, record_1];
}); }); };
}
else {
json[key] = this_1._requestFnForLink(n);
}
};
var this_1 = this;
for (var _i = 0, _a = Object.keys(json._links); _i < _a.length; _i++) {
var key = _a[_i];
_loop_1(key);
}
return json;
};
CallBuilder.prototype._sendNormalRequest = function (initialUrl) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url;
return tslib_1.__generator(this, function (_a) {
url = initialUrl;
if (url.authority() === "") {
url = url.authority(this.url.authority());
}
if (url.protocol() === "") {
url = url.protocol(this.url.protocol());
}
return [2, horizon_axios_client_1.default.get(url.toString())
.then(function (response) { return response.data; })
.catch(this._handleNetworkError)];
});
});
};
CallBuilder.prototype._parseResponse = function (json) {
if (json._embedded && json._embedded.records) {
return this._toCollectionPage(json);
}
return this._parseRecord(json);
};
CallBuilder.prototype._toCollectionPage = function (json) {
var _this = this;
for (var i = 0; i < json._embedded.records.length; i += 1) {
json._embedded.records[i] = this._parseRecord(json._embedded.records[i]);
}
return {
records: json._embedded.records,
next: function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
var r;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4, this._sendNormalRequest(urijs_1.default(json._links.next.href))];
case 1:
r = _a.sent();
return [2, this._toCollectionPage(r)];
}
});
}); },
prev: function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
var r;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4, this._sendNormalRequest(urijs_1.default(json._links.prev.href))];
case 1:
r = _a.sent();
return [2, this._toCollectionPage(r)];
}
});
}); },
};
};
CallBuilder.prototype._handleNetworkError = function (error) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
return tslib_1.__generator(this, function (_a) {
if (error.response && error.response.status && error.response.statusText) {
switch (error.response.status) {
case 404:
return [2, Promise.reject(new errors_1.NotFoundError(error.response.statusText, error.response.data))];
default:
return [2, Promise.reject(new errors_1.NetworkError(error.response.statusText, error.response.data))];
}
}
else {
return [2, Promise.reject(new Error(error.message))];
}
return [2];
});
});
};
return CallBuilder;
}());
exports.CallBuilder = CallBuilder;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5)))
/***/ }),
/* 7 */
/***/ (function(module, exports) {
/**
* Checks if `value` is `undefined`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
*/
function isUndefined(value) {
return value === undefined;
}
module.exports = isUndefined;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.StrKey = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* eslint no-bitwise: ["error", {"allow": ["<<"]}] */
exports.decodeCheck = decodeCheck;
exports.encodeCheck = encodeCheck;
var _base = __webpack_require__(321);
var _base2 = _interopRequireDefault(_base);
var _crc = __webpack_require__(322);
var _crc2 = _interopRequireDefault(_crc);
var _isUndefined = __webpack_require__(7);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _isNull = __webpack_require__(132);
var _isNull2 = _interopRequireDefault(_isNull);
var _isString = __webpack_require__(9);
var _isString2 = _interopRequireDefault(_isString);
var _checksum = __webpack_require__(334);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var versionBytes = {
ed25519PublicKey: 6 << 3, // G (when encoded in base32)
ed25519SecretSeed: 18 << 3, // S
med25519PublicKey: 12 << 3, // M
preAuthTx: 19 << 3, // T
sha256Hash: 23 << 3, // X
signedPayload: 15 << 3 // P
};
var strkeyTypes = {
G: 'ed25519PublicKey',
S: 'ed25519SecretSeed',
M: 'med25519PublicKey',
T: 'preAuthTx',
X: 'sha256Hash',
P: 'signedPayload'
};
/**
* StrKey is a helper class that allows encoding and decoding Stellar keys
* to/from strings, i.e. between their binary (Buffer, xdr.PublicKey, etc.) and
* string (i.e. "GABCD...", etc.) representations.
*/
var StrKey = exports.StrKey = function () {
function StrKey() {
_classCallCheck(this, StrKey);
}
_createClass(StrKey, null, [{
key: 'encodeEd25519PublicKey',
/**
* Encodes `data` to strkey ed25519 public key.
*
* @param {Buffer} data raw data to encode
* @returns {string} "G..." representation of the key
*/
value: function encodeEd25519PublicKey(data) {
return encodeCheck('ed25519PublicKey', data);
}
/**
* Decodes strkey ed25519 public key to raw data.
*
* If the parameter is a muxed account key ("M..."), this will only encode it
* as a basic Ed25519 key (as if in "G..." format).
*
* @param {string} data "G..." (or "M...") key representation to decode
* @returns {Buffer} raw key
*/
}, {
key: 'decodeEd25519PublicKey',
value: function decodeEd25519PublicKey(data) {
return decodeCheck('ed25519PublicKey', data);
}
/**
* Returns true if the given Stellar public key is a valid ed25519 public key.
* @param {string} publicKey public key to check
* @returns {boolean}
*/
}, {
key: 'isValidEd25519PublicKey',
value: function isValidEd25519PublicKey(publicKey) {
return isValid('ed25519PublicKey', publicKey);
}
/**
* Encodes data to strkey ed25519 seed.
* @param {Buffer} data data to encode
* @returns {string}
*/
}, {
key: 'encodeEd25519SecretSeed',
value: function encodeEd25519SecretSeed(data) {
return encodeCheck('ed25519SecretSeed', data);
}
/**
* Decodes strkey ed25519 seed to raw data.
* @param {string} address data to decode
* @returns {Buffer}
*/
}, {
key: 'decodeEd25519SecretSeed',
value: function decodeEd25519SecretSeed(address) {
return decodeCheck('ed25519SecretSeed', address);
}
/**
* Returns true if the given Stellar secret key is a valid ed25519 secret seed.
* @param {string} seed seed to check
* @returns {boolean}
*/
}, {
key: 'isValidEd25519SecretSeed',
value: function isValidEd25519SecretSeed(seed) {
return isValid('ed25519SecretSeed', seed);
}
/**
* Encodes data to strkey med25519 public key.
* @param {Buffer} data data to encode
* @returns {string}
*/
}, {
key: 'encodeMed25519PublicKey',
value: function encodeMed25519PublicKey(data) {
return encodeCheck('med25519PublicKey', data);
}
/**
* Decodes strkey med25519 public key to raw data.
* @param {string} address data to decode
* @returns {Buffer}
*/
}, {
key: 'decodeMed25519PublicKey',
value: function decodeMed25519PublicKey(address) {
return decodeCheck('med25519PublicKey', address);
}
/**
* Returns true if the given Stellar public key is a valid med25519 public key.
* @param {string} publicKey public key to check
* @returns {boolean}
*/
}, {
key: 'isValidMed25519PublicKey',
value: function isValidMed25519PublicKey(publicKey) {
return isValid('med25519PublicKey', publicKey);
}
/**
* Encodes data to strkey preAuthTx.
* @param {Buffer} data data to encode
* @returns {string}
*/
}, {
key: 'encodePreAuthTx',
value: function encodePreAuthTx(data) {
return encodeCheck('preAuthTx', data);
}
/**
* Decodes strkey PreAuthTx to raw data.
* @param {string} address data to decode
* @returns {Buffer}
*/
}, {
key: 'decodePreAuthTx',
value: function decodePreAuthTx(address) {
return decodeCheck('preAuthTx', address);
}
/**
* Encodes data to strkey sha256 hash.
* @param {Buffer} data data to encode
* @returns {string}
*/
}, {
key: 'encodeSha256Hash',
value: function encodeSha256Hash(data) {
return encodeCheck('sha256Hash', data);
}
/**
* Decodes strkey sha256 hash to raw data.
* @param {string} address data to decode
* @returns {Buffer}
*/
}, {
key: 'decodeSha256Hash',
value: function decodeSha256Hash(address) {
return decodeCheck('sha256Hash', address);
}
/**
* Encodes raw data to strkey signed payload (P...).
* @param {Buffer} data data to encode
* @returns {string}
*/
}, {
key: 'encodeSignedPayload',
value: function encodeSignedPayload(data) {
return encodeCheck('signedPayload', data);
}
/**
* Decodes strkey signed payload (P...) to raw data.
* @param {string} address address to decode
* @returns {Buffer}
*/
}, {
key: 'decodeSignedPayload',
value: function decodeSignedPayload(address) {
return decodeCheck('signedPayload', address);
}
/**
* Checks validity of alleged signed payload (P...) strkey address.
* @param {string} address signer key to check
* @returns {boolean}
*/
}, {
key: 'isValidSignedPayload',
value: function isValidSignedPayload(address) {
return isValid('signedPayload', address);
}
}, {
key: 'getVersionByteForPrefix',
value: function getVersionByteForPrefix(address) {
return strkeyTypes[address[0]];
}
}]);
return StrKey;
}();
/**
* Sanity-checks whether or not a strkey *appears* valid.
*
* @param {string} versionByteName the type of strkey to expect in `encoded`
* @param {string} encoded the strkey to validate
*
* @return {Boolean} whether or not the `encoded` strkey appears valid for the
* `versionByteName` strkey type (see `versionBytes`, above).
*
* @note This isn't a *definitive* check of validity, but rather a best-effort
* check based on (a) input length, (b) whether or not it can be decoded,
* and (c) output length.
*/
function isValid(versionByteName, encoded) {
if (!(0, _isString2.default)(encoded)) {
return false;
}
// basic length checks on the strkey lengths
switch (versionByteName) {
case 'ed25519PublicKey': // falls through
case 'ed25519SecretSeed': // falls through
case 'preAuthTx': // falls through
case 'sha256Hash':
if (encoded.length !== 56) {
return false;
}
break;
case 'med25519PublicKey':
if (encoded.length !== 69) {
return false;
}
break;
case 'signedPayload':
if (encoded.length < 56 || encoded.length > 165) {
return false;
}
break;
default:
return false;
}
var decoded = '';
try {
decoded = decodeCheck(versionByteName, encoded);
} catch (err) {
return false;
}
// basic length checks on the resulting buffer sizes
switch (versionByteName) {
case 'ed25519PublicKey': // falls through
case 'ed25519SecretSeed': // falls through
case 'preAuthTx': // falls through
case 'sha256Hash':
return decoded.length === 32;
case 'med25519PublicKey':
return decoded.length === 40; // +8 bytes for the ID
case 'signedPayload':
return (
// 32 for the signer, +4 for the payload size, then either +4 for the
// min or +64 for the max payload
decoded.length >= 32 + 4 + 4 && decoded.length <= 32 + 4 + 64
);
default:
return false;
}
}
function decodeCheck(versionByteName, encoded) {
if (!(0, _isString2.default)(encoded)) {
throw new TypeError('encoded argument must be of type String');
}
var decoded = _base2.default.decode(encoded);
var versionByte = decoded[0];
var payload = decoded.slice(0, -2);
var data = payload.slice(1);
var checksum = decoded.slice(-2);
if (encoded !== _base2.default.encode(decoded)) {
throw new Error('invalid encoded string');
}
var expectedVersion = versionBytes[versionByteName];
if ((0, _isUndefined2.default)(expectedVersion)) {
throw new Error(versionByteName + ' is not a valid version byte name. ' + ('Expected one of ' + Object.keys(versionBytes).join(', ')));
}
if (versionByte !== expectedVersion) {
throw new Error('invalid version byte. expected ' + expectedVersion + ', got ' + versionByte);
}
var expectedChecksum = calculateChecksum(payload);
if (!(0, _checksum.verifyChecksum)(expectedChecksum, checksum)) {
throw new Error('invalid checksum');
}
return Buffer.from(data);
}
function encodeCheck(versionByteName, data) {
if ((0, _isNull2.default)(data) || (0, _isUndefined2.default)(data)) {
throw new Error('cannot encode null data');
}
var versionByte = versionBytes[versionByteName];
if ((0, _isUndefined2.default)(versionByte)) {
throw new Error(versionByteName + ' is not a valid version byte name. ' + ('Expected one of ' + Object.keys(versionBytes).join(', ')));
}
data = Buffer.from(data);
var versionBuffer = Buffer.from([versionByte]);
var payload = Buffer.concat([versionBuffer, data]);
var checksum = calculateChecksum(payload);
var unencoded = Buffer.concat([payload, checksum]);
return _base2.default.encode(unencoded);
}
// Computes the CRC16-XModem checksum of `payload` in little-endian order
function calculateChecksum(payload) {
var checksum = Buffer.alloc(2);
checksum.writeUInt16LE(_crc2.default.crc16xmodem(payload), 0);
return checksum;
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(20),
isArray = __webpack_require__(3),
isObjectLike = __webpack_require__(12);
/** `Object#toString` result references. */
var stringTag = '[object String]';
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
}
module.exports = isString;
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(156);
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Array, otherwise false
*/
function isArray(val) {
return Array.isArray(val);
}
/**
* Determine if a value is undefined
*
* @param {Object} val The value to test
* @returns {boolean} True if the value is undefined, otherwise false
*/
function isUndefined(val) {
return typeof val === 'undefined';
}
/**
* Determine if a value is a Buffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
&& typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
function isArrayBuffer(val) {
return toString.call(val) === '[object ArrayBuffer]';
}
/**
* Determine if a value is a FormData
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(val) {
return toString.call(val) === '[object FormData]';
}
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
}
return result;
}
/**
* Determine if a value is a String
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a String, otherwise false
*/
function isString(val) {
return typeof val === 'string';
}
/**
* Determine if a value is a Number
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Number, otherwise false
*/
function isNumber(val) {
return typeof val === 'number';
}
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject(val) {
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a plain Object
*
* @param {Object} val The value to test
* @return {boolean} True if value is a plain Object, otherwise false
*/
function isPlainObject(val) {
if (toString.call(val) !== '[object Object]') {
return false;
}
var prototype = Object.getPrototypeOf(val);
return prototype === null || prototype === Object.prototype;
}
/**
* Determine if a value is a Date
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Date, otherwise false
*/
function isDate(val) {
return toString.call(val) === '[object Date]';
}
/**
* Determine if a value is a File
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
function isFile(val) {
return toString.call(val) === '[object File]';
}
/**
* Determine if a value is a Blob
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Blob, otherwise false
*/
function isBlob(val) {
return toString.call(val) === '[object Blob]';
}
/**
* Determine if a value is a Function
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
function isFunction(val) {
return toString.call(val) === '[object Function]';
}
/**
* Determine if a value is a Stream
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Stream, otherwise false
*/
function isStream(val) {
return isObject(val) && isFunction(val.pipe);
}
/**
* Determine if a value is a URLSearchParams object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
function isURLSearchParams(val) {
return toString.call(val) === '[object URLSearchParams]';
}
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
* @returns {String} The String freed of excess whitespace
*/
function trim(str) {
return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
}
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*/
function isStandardBrowserEnv() {
if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
navigator.product === 'NativeScript' ||
navigator.product === 'NS')) {
return false;
}
return (
typeof window !== 'undefined' &&
typeof document !== 'undefined'
);
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
function forEach(obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (isPlainObject(result[key]) && isPlainObject(val)) {
result[key] = merge(result[key], val);
} else if (isPlainObject(val)) {
result[key] = merge({}, val);
} else if (isArray(val)) {
result[key] = val.slice();
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
* @return {Object} The resulting value of object a
*/
function extend(a, b, thisArg) {
forEach(b, function assignValue(val, key) {
if (thisArg && typeof val === 'function') {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
});
return a;
}
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
* @return {string} content value without BOM
*/
function stripBOM(content) {
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
}
module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
isBuffer: isBuffer,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isObject: isObject,
isPlainObject: isPlainObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isFunction: isFunction,
isStream: isStream,
isURLSearchParams: isURLSearchParams,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
extend: extend,
trim: trim,
stripBOM: stripBOM
};
/***/ }),
/* 11 */
/***/ (function(module, exports) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
})
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
}
/***/ }),
/* 12 */
/***/ (function(module, exports) {
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return value != null && typeof value == 'object';
}
module.exports = isObjectLike;
/***/ }),
/* 13 */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
var freeGlobal = __webpack_require__(98);
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
module.exports = root;
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _buffer = __webpack_require__(1);
var createBuffer = _buffer.Buffer.from && _buffer.Buffer.alloc && _buffer.Buffer.allocUnsafe && _buffer.Buffer.allocUnsafeSlow ? _buffer.Buffer.from : // support for Node < 5.10
function (val) {
return new _buffer.Buffer(val);
};
exports.default = createBuffer;
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (model, calc) {
var fn = function fn(buf, previous) {
return calc(buf, previous) >>> 0;
};
fn.signed = calc;
fn.unsigned = fn;
fn.model = model;
return fn;
};
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.decodeAddressToMuxedAccount = decodeAddressToMuxedAccount;
exports.encodeMuxedAccountToAddress = encodeMuxedAccountToAddress;
exports.encodeMuxedAccount = encodeMuxedAccount;
exports.extractBaseAddress = extractBaseAddress;
var _isString = __webpack_require__(9);
var _isString2 = _interopRequireDefault(_isString);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _strkey = __webpack_require__(8);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Converts a Stellar address (in G... or M... form) to an `xdr.MuxedAccount`
* structure, using the ed25519 representation when possible.
*
* This supports full muxed accounts, where an `M...` address will resolve to
* both its underlying `G...` address and an integer ID.
*
* @param {string} address G... or M... address to encode into XDR
* @returns {xdr.MuxedAccount} a muxed account object for this address string
*/
function decodeAddressToMuxedAccount(address) {
if (_strkey.StrKey.isValidMed25519PublicKey(address)) {
return _decodeAddressFullyToMuxedAccount(address);
}
return _xdr2.default.MuxedAccount.keyTypeEd25519(_strkey.StrKey.decodeEd25519PublicKey(address));
}
/**
* Converts an xdr.MuxedAccount to its StrKey representation.
*
* This returns its "M..." string representation if there is a muxing ID within
* the object and returns the "G..." representation otherwise.
*
* @param {xdr.MuxedAccount} muxedAccount Raw account to stringify
* @returns {string} Stringified G... (corresponding to the underlying pubkey)
* or M... address (corresponding to both the key and the muxed ID)
*
* @see https://stellar.org/protocol/sep-23
*/
function encodeMuxedAccountToAddress(muxedAccount) {
if (muxedAccount.switch().value === _xdr2.default.CryptoKeyType.keyTypeMuxedEd25519().value) {
return _encodeMuxedAccountFullyToAddress(muxedAccount);
}
return _strkey.StrKey.encodeEd25519PublicKey(muxedAccount.ed25519());
}
/**
* Transform a Stellar address (G...) and an ID into its XDR representation.
*
* @param {string} address - a Stellar G... address
* @param {string} id - a Uint64 ID represented as a string
*
* @return {xdr.MuxedAccount} - XDR representation of the above muxed account
*/
function encodeMuxedAccount(address, id) {
if (!_strkey.StrKey.isValidEd25519PublicKey(address)) {
throw new Error('address should be a Stellar account ID (G...)');
}
if (!(0, _isString2.default)(id)) {
throw new Error('id should be a string representing a number (uint64)');
}
return _xdr2.default.MuxedAccount.keyTypeMuxedEd25519(new _xdr2.default.MuxedAccountMed25519({
id: _xdr2.default.Uint64.fromString(id),
ed25519: _strkey.StrKey.decodeEd25519PublicKey(address)
}));
}
/**
* Extracts the underlying base (G...) address from an M-address.
* @param {string} address an account address (either M... or G...)
* @return {string} a Stellar public key address (G...)
*/
function extractBaseAddress(address) {
if (_strkey.StrKey.isValidEd25519PublicKey(address)) {
return address;
}
if (!_strkey.StrKey.isValidMed25519PublicKey(address)) {
throw new TypeError('expected muxed account (M...), got ' + address);
}
var muxedAccount = decodeAddressToMuxedAccount(address);
return _strkey.StrKey.encodeEd25519PublicKey(muxedAccount.med25519().ed25519());
}
// Decodes an "M..." account ID into its MuxedAccount object representation.
function _decodeAddressFullyToMuxedAccount(address) {
var rawBytes = _strkey.StrKey.decodeMed25519PublicKey(address);
// Decoding M... addresses cannot be done through a simple
// MuxedAccountMed25519.fromXDR() call, because the definition is:
//
// constructor(attributes: { id: Uint64; ed25519: Buffer });
//
// Note the ID is the first attribute. However, the ID comes *last* in the
// stringified (base32-encoded) address itself (it's the last 8-byte suffix).
// The `fromXDR()` method interprets bytes in order, so we need to parse out
// the raw binary into its requisite parts, i.e. use the MuxedAccountMed25519
// constructor directly.
//
// Refer to https://github.com/stellar/go/blob/master/xdr/muxed_account.go#L26
// for the Golang implementation of the M... parsing.
return _xdr2.default.MuxedAccount.keyTypeMuxedEd25519(new _xdr2.default.MuxedAccountMed25519({
id: _xdr2.default.Uint64.fromXDR(rawBytes.slice(-8)),
ed25519: rawBytes.slice(0, -8)
}));
}
// Converts an xdr.MuxedAccount into its *true* "M..." string representation.
function _encodeMuxedAccountFullyToAddress(muxedAccount) {
if (muxedAccount.switch() === _xdr2.default.CryptoKeyType.keyTypeEd25519()) {
return encodeMuxedAccountToAddress(muxedAccount);
}
var muxed = muxedAccount.med25519();
return _strkey.StrKey.encodeMed25519PublicKey(Buffer.concat([muxed.ed25519(), muxed.id().toXDR('raw')]));
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 18 */
/***/ (function(module, exports) {
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return value != null && (type == 'object' || type == 'function');
}
module.exports = isObject;
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Keypair = undefined;
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; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* eslint no-bitwise: ["error", {"allow": ["^"]}] */
var _tweetnacl = __webpack_require__(103);
var _tweetnacl2 = _interopRequireDefault(_tweetnacl);
var _isUndefined = __webpack_require__(7);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _isString = __webpack_require__(9);
var _isString2 = _interopRequireDefault(_isString);
var _signing = __webpack_require__(102);
var _strkey = __webpack_require__(8);
var _hashing = __webpack_require__(30);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* `Keypair` represents public (and secret) keys of the account.
*
* Currently `Keypair` only supports ed25519 but in a future this class can be abstraction layer for other
* public-key signature systems.
*
* Use more convenient methods to create `Keypair` object:
* * `{@link Keypair.fromPublicKey}`
* * `{@link Keypair.fromSecret}`
* * `{@link Keypair.random}`
*
* @constructor
* @param {object} keys At least one of keys must be provided.
* @param {string} keys.type Public-key signature system name. (currently only `ed25519` keys are supported)
* @param {Buffer} [keys.publicKey] Raw public key
* @param {Buffer} [keys.secretKey] Raw secret key (32-byte secret seed in ed25519`)
*/
var Keypair = exports.Keypair = function () {
function Keypair(keys) {
_classCallCheck(this, Keypair);
if (keys.type !== 'ed25519') {
throw new Error('Invalid keys type');
}
this.type = keys.type;
if (keys.secretKey) {
keys.secretKey = Buffer.from(keys.secretKey);
if (keys.secretKey.length !== 32) {
throw new Error('secretKey length is invalid');
}
this._secretSeed = keys.secretKey;
this._publicKey = (0, _signing.generate)(keys.secretKey);
this._secretKey = Buffer.concat([keys.secretKey, this._publicKey]);
if (keys.publicKey && !this._publicKey.equals(Buffer.from(keys.publicKey))) {
throw new Error('secretKey does not match publicKey');
}
} else {
this._publicKey = Buffer.from(keys.publicKey);
if (this._publicKey.length !== 32) {
throw new Error('publicKey length is invalid');
}
}
}
/**
* Creates a new `Keypair` instance from secret. This can either be secret key or secret seed depending
* on underlying public-key signature system. Currently `Keypair` only supports ed25519.
* @param {string} secret secret key (ex. `SDAKFNYEIAORZKKCYRILFQKLLOCNPL5SWJ3YY5NM3ZH6GJSZGXHZEPQS`)
* @returns {Keypair}
*/
_createClass(Keypair, [{
key: 'xdrAccountId',
value: function xdrAccountId() {
return new _xdr2.default.AccountId.publicKeyTypeEd25519(this._publicKey);
}
}, {
key: 'xdrPublicKey',
value: function xdrPublicKey() {
return new _xdr2.default.PublicKey.publicKeyTypeEd25519(this._publicKey);
}
/**
* Creates a {@link xdr.MuxedAccount} object from the public key.
*
* You will get a different type of muxed account depending on whether or not
* you pass an ID.
*
* @param {string} [id] - stringified integer indicating the underlying muxed
* ID of the new account object
*
* @return {xdr.MuxedAccount}
*/
}, {
key: 'xdrMuxedAccount',
value: function xdrMuxedAccount(id) {
if (!(0, _isUndefined2.default)(id)) {
if (!(0, _isString2.default)(id)) {
throw new TypeError('expected string for ID, got ' + (typeof id === 'undefined' ? 'undefined' : _typeof(id)));
}
return _xdr2.default.MuxedAccount.keyTypeMuxedEd25519(new _xdr2.default.MuxedAccountMed25519({
id: _xdr2.default.Uint64.fromString(id),
ed25519: this._publicKey
}));
}
return new _xdr2.default.MuxedAccount.keyTypeEd25519(this._publicKey);
}
/**
* Returns raw public key
* @returns {Buffer}
*/
}, {
key: 'rawPublicKey',
value: function rawPublicKey() {
return this._publicKey;
}
}, {
key: 'signatureHint',
value: function signatureHint() {
var a = this.xdrAccountId().toXDR();
return a.slice(a.length - 4);
}
/**
* Returns public key associated with this `Keypair` object.
* @returns {string}
*/
}, {
key: 'publicKey',
value: function publicKey() {
return _strkey.StrKey.encodeEd25519PublicKey(this._publicKey);
}
/**
* Returns secret key associated with this `Keypair` object
* @returns {string}
*/
}, {
key: 'secret',
value: function secret() {
if (!this._secretSeed) {
throw new Error('no secret key available');
}
if (this.type === 'ed25519') {
return _strkey.StrKey.encodeEd25519SecretSeed(this._secretSeed);
}
throw new Error('Invalid Keypair type');
}
/**
* Returns raw secret key.
* @returns {Buffer}
*/
}, {
key: 'rawSecretKey',
value: function rawSecretKey() {
return this._secretSeed;
}
/**
* Returns `true` if this `Keypair` object contains secret key and can sign.
* @returns {boolean}
*/
}, {
key: 'canSign',
value: function canSign() {
return !!this._secretKey;
}
/**
* Signs data.
* @param {Buffer} data Data to sign
* @returns {Buffer}
*/
}, {
key: 'sign',
value: function sign(data) {
if (!this.canSign()) {
throw new Error('cannot sign: no secret key available');
}
return (0, _signing.sign)(data, this._secretKey);
}
/**
* Verifies if `signature` for `data` is valid.
* @param {Buffer} data Signed data
* @param {Buffer} signature Signature
* @returns {boolean}
*/
}, {
key: 'verify',
value: function verify(data, signature) {
return (0, _signing.verify)(data, signature, this._publicKey);
}
/**
* Returns the decorated signature (hint+sig) for arbitrary data.
*
* @param {Buffer} data arbitrary data to sign
* @return {xdr.DecoratedSignature} the raw signature structure which can be
* added directly to a transaction envelope
*
* @see TransactionBase.addDecoratedSignature
*/
}, {
key: 'signDecorated',
value: function signDecorated(data) {
var signature = this.sign(data);
var hint = this.signatureHint();
return new _xdr2.default.DecoratedSignature({ hint: hint, signature: signature });
}
/**
* Returns the raw decorated signature (hint+sig) for a signed payload signer.
*
* The hint is defined as the last 4 bytes of the signer key XORed with last
* 4 bytes of the payload (zero-left-padded if necessary).
*
* @param {Buffer} data data to both sign and treat as the payload
* @return {xdr.DecoratedSignature}
*
* @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0040.md#signature-hint
* @see TransactionBase.addDecoratedSignature
*/
}, {
key: 'signPayloadDecorated',
value: function signPayloadDecorated(data) {
var signature = this.sign(data);
var keyHint = this.signatureHint();
var hint = Buffer.from(data.slice(-4));
if (hint.length < 4) {
// append zeroes as needed
hint = Buffer.concat([hint, Buffer.alloc(4 - data.length, 0)]);
}
return new _xdr2.default.DecoratedSignature({
hint: hint.map(function (byte, i) {
return byte ^ keyHint[i];
}),
signature: signature
});
}
}], [{
key: 'fromSecret',
value: function fromSecret(secret) {
var rawSecret = _strkey.StrKey.decodeEd25519SecretSeed(secret);
return this.fromRawEd25519Seed(rawSecret);
}
/**
* Creates a new `Keypair` object from ed25519 secret key seed raw bytes.
*
* @param {Buffer} rawSeed Raw 32-byte ed25519 secret key seed
* @returns {Keypair}
*/
}, {
key: 'fromRawEd25519Seed',
value: function fromRawEd25519Seed(rawSeed) {
return new this({ type: 'ed25519', secretKey: rawSeed });
}
/**
* Returns `Keypair` object representing network master key.
* @param {string} networkPassphrase passphrase of the target stellar network (e.g. "Public Global Stellar Network ; September 2015").
* @returns {Keypair}
*/
}, {
key: 'master',
value: function master(networkPassphrase) {
if (!networkPassphrase) {
throw new Error('No network selected. Please pass a network argument, e.g. `Keypair.master(Networks.PUBLIC)`.');
}
return this.fromRawEd25519Seed((0, _hashing.hash)(networkPassphrase));
}
/**
* Creates a new `Keypair` object from public key.
* @param {string} publicKey public key (ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`)
* @returns {Keypair}
*/
}, {
key: 'fromPublicKey',
value: function fromPublicKey(publicKey) {
publicKey = _strkey.StrKey.decodeEd25519PublicKey(publicKey);
if (publicKey.length !== 32) {
throw new Error('Invalid Stellar public key');
}
return new this({ type: 'ed25519', publicKey: publicKey });
}
/**
* Create a random `Keypair` object.
* @returns {Keypair}
*/
}, {
key: 'random',
value: function random() {
var secret = _tweetnacl2.default.randomBytes(32);
return this.fromRawEd25519Seed(secret);
}
}]);
return Keypair;
}();
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(39),
getRawTag = __webpack_require__(184),
objectToString = __webpack_require__(185);
/** `Object#toString` result references. */
var nullTag = '[object Null]',
undefinedTag = '[object Undefined]';
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag && symToStringTag in Object(value))
? getRawTag(value)
: objectToString(value);
}
module.exports = baseGetTag;
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
/* eslint-disable node/no-deprecated-api */
var buffer = __webpack_require__(1)
var Buffer = buffer.Buffer
// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
for (var key in src) {
dst[key] = src[key]
}
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
module.exports = buffer
} else {
// Copy properties from require('buffer')
copyProps(buffer, exports)
exports.Buffer = SafeBuffer
}
function SafeBuffer (arg, encodingOrOffset, length) {
return Buffer(arg, encodingOrOffset, length)
}
SafeBuffer.prototype = Object.create(Buffer.prototype)
// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)
SafeBuffer.from = function (arg, encodingOrOffset, length) {
if (typeof arg === 'number') {
throw new TypeError('Argument must not be a number')
}
return Buffer(arg, encodingOrOffset, length)
}
SafeBuffer.alloc = function (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
var buf = Buffer(size)
if (fill !== undefined) {
if (typeof encoding === 'string') {
buf.fill(fill, encoding)
} else {
buf.fill(fill)
}
} else {
buf.fill(0)
}
return buf
}
SafeBuffer.allocUnsafe = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return Buffer(size)
}
SafeBuffer.allocUnsafeSlow = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return buffer.SlowBuffer(size)
}
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _types = __webpack_require__(105);
Object.keys(_types).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _types[key];
}
});
});
var _config = __webpack_require__(292);
Object.keys(_config).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _config[key];
}
});
});
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/*! bignumber.js v4.1.0 https://github.com/MikeMcl/bignumber.js/LICENCE */
;(function (globalObj) {
'use strict';
/*
bignumber.js v4.1.0
A JavaScript library for arbitrary-precision arithmetic.
https://github.com/MikeMcl/bignumber.js
Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com>
MIT Expat Licence
*/
var BigNumber,
isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
mathceil = Math.ceil,
mathfloor = Math.floor,
notBool = ' not a boolean or binary digit',
roundingMode = 'rounding mode',
tooManyDigits = 'number type has more than 15 significant digits',
ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_',
BASE = 1e14,
LOG_BASE = 14,
MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1
// MAX_INT32 = 0x7fffffff, // 2^31 - 1
POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
SQRT_BASE = 1e7,
/*
* The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
* the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an
* exception is thrown (if ERRORS is true).
*/
MAX = 1E9; // 0 to MAX_INT32
/*
* Create and return a BigNumber constructor.
*/
function constructorFactory(config) {
var div, parseNumeric,
// id tracks the caller function, so its name can be included in error messages.
id = 0,
P = BigNumber.prototype,
ONE = new BigNumber(1),
/********************************* EDITABLE DEFAULTS **********************************/
/*
* The default values below must be integers within the inclusive ranges stated.
* The values can also be changed at run-time using BigNumber.config.
*/
// The maximum number of decimal places for operations involving division.
DECIMAL_PLACES = 20, // 0 to MAX
/*
* The rounding mode used when rounding to the above decimal places, and when using
* toExponential, toFixed, toFormat and toPrecision, and round (default value).
* UP 0 Away from zero.
* DOWN 1 Towards zero.
* CEIL 2 Towards +Infinity.
* FLOOR 3 Towards -Infinity.
* HALF_UP 4 Towards nearest neighbour. If equidistant, up.
* HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
* HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
* HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
* HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
*/
ROUNDING_MODE = 4, // 0 to 8
// EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
// The exponent value at and beneath which toString returns exponential notation.
// Number type: -7
TO_EXP_NEG = -7, // 0 to -MAX
// The exponent value at and above which toString returns exponential notation.
// Number type: 21
TO_EXP_POS = 21, // 0 to MAX
// RANGE : [MIN_EXP, MAX_EXP]
// The minimum exponent value, beneath which underflow to zero occurs.
// Number type: -324 (5e-324)
MIN_EXP = -1e7, // -1 to -MAX
// The maximum exponent value, above which overflow to Infinity occurs.
// Number type: 308 (1.7976931348623157e+308)
// For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
MAX_EXP = 1e7, // 1 to MAX
// Whether BigNumber Errors are ever thrown.
ERRORS = true, // true or false
// Change to intValidatorNoErrors if ERRORS is false.
isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors
// Whether to use cryptographically-secure random number generation, if available.
CRYPTO = false, // true or false
/*
* The modulo mode used when calculating the modulus: a mod n.
* The quotient (q = a / n) is calculated according to the corresponding rounding mode.
* The remainder (r) is calculated as: r = a - n * q.
*
* UP 0 The remainder is positive if the dividend is negative, else is negative.
* DOWN 1 The remainder has the same sign as the dividend.
* This modulo mode is commonly known as 'truncated division' and is
* equivalent to (a % n) in JavaScript.
* FLOOR 3 The remainder has the same sign as the divisor (Python %).
* HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
* EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
* The remainder is always positive.
*
* The truncated division, floored division, Euclidian division and IEEE 754 remainder
* modes are commonly used for the modulus operation.
* Although the other rounding modes can also be used, they may not give useful results.
*/
MODULO_MODE = 1, // 0 to 9
// The maximum number of significant digits of the result of the toPower operation.
// If POW_PRECISION is 0, there will be unlimited significant digits.
POW_PRECISION = 0, // 0 to MAX
// The format specification used by the BigNumber.prototype.toFormat method.
FORMAT = {
decimalSeparator: '.',
groupSeparator: ',',
groupSize: 3,
secondaryGroupSize: 0,
fractionGroupSeparator: '\xA0', // non-breaking space
fractionGroupSize: 0
};
/******************************************************************************************/
// CONSTRUCTOR
/*
* The BigNumber constructor and exported function.
* Create and return a new instance of a BigNumber object.
*
* n {number|string|BigNumber} A numeric value.
* [b] {number} The base of n. Integer, 2 to 64 inclusive.
*/
function BigNumber( n, b ) {
var c, e, i, num, len, str,
x = this;
// Enable constructor usage without new.
if ( !( x instanceof BigNumber ) ) {
// 'BigNumber() constructor call without new: {n}'
if (ERRORS) raise( 26, 'constructor call without new', n );
return new BigNumber( n, b );
}
// 'new BigNumber() base not an integer: {b}'
// 'new BigNumber() base out of range: {b}'
if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) {
// Duplicate.
if ( n instanceof BigNumber ) {
x.s = n.s;
x.e = n.e;
x.c = ( n = n.c ) ? n.slice() : n;
id = 0;
return;
}
if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) {
x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1;
// Fast path for integers.
if ( n === ~~n ) {
for ( e = 0, i = n; i >= 10; i /= 10, e++ );
x.e = e;
x.c = [n];
id = 0;
return;
}
str = n + '';
} else {
if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num );
x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
}
} else {
b = b | 0;
str = n + '';
// Ensure return value is rounded to DECIMAL_PLACES as with other bases.
// Allow exponential notation to be used with base 10 argument.
if ( b == 10 ) {
x = new BigNumber( n instanceof BigNumber ? n : str );
return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE );
}
// Avoid potential interpretation of Infinity and NaN as base 44+ values.
// Any number in exponential form will fail due to the [Ee][+-].
if ( ( num = typeof n == 'number' ) && n * 0 != 0 ||
!( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) +
'(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) {
return parseNumeric( x, str, num, b );
}
if (num) {
x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1;
if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) {
// 'new BigNumber() number type has more than 15 significant digits: {n}'
raise( id, tooManyDigits, n );
}
// Prevent later check for length on converted number.
num = false;
} else {
x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
}
str = convertBase( str, 10, b, x.s );
}
// Decimal point?
if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' );
// Exponential form?
if ( ( i = str.search( /e/i ) ) > 0 ) {
// Determine exponent.
if ( e < 0 ) e = i;
e += +str.slice( i + 1 );
str = str.substring( 0, i );
} else if ( e < 0 ) {
// Integer.
e = str.length;
}
// Determine leading zeros.
for ( i = 0; str.charCodeAt(i) === 48; i++ );
// Determine trailing zeros.
for ( len = str.length; str.charCodeAt(--len) === 48; );
str = str.slice( i, len + 1 );
if (str) {
len = str.length;
// Disallow numbers with over 15 significant digits if number type.
// 'new BigNumber() number type has more than 15 significant digits: {n}'
if ( num && ERRORS && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) {
raise( id, tooManyDigits, x.s * n );
}
e = e - i - 1;
// Overflow?
if ( e > MAX_EXP ) {
// Infinity.
x.c = x.e = null;
// Underflow?
} else if ( e < MIN_EXP ) {
// Zero.
x.c = [ x.e = 0 ];
} else {
x.e = e;
x.c = [];
// Transform base
// e is the base 10 exponent.
// i is where to slice str to get the first element of the coefficient array.
i = ( e + 1 ) % LOG_BASE;
if ( e < 0 ) i += LOG_BASE;
if ( i < len ) {
if (i) x.c.push( +str.slice( 0, i ) );
for ( len -= LOG_BASE; i < len; ) {
x.c.push( +str.slice( i, i += LOG_BASE ) );
}
str = str.slice(i);
i = LOG_BASE - str.length;
} else {
i -= len;
}
for ( ; i--; str += '0' );
x.c.push( +str );
}
} else {
// Zero.
x.c = [ x.e = 0 ];
}
id = 0;
}
// CONSTRUCTOR PROPERTIES
BigNumber.another = constructorFactory;
BigNumber.ROUND_UP = 0;
BigNumber.ROUND_DOWN = 1;
BigNumber.ROUND_CEIL = 2;
BigNumber.ROUND_FLOOR = 3;
BigNumber.ROUND_HALF_UP = 4;
BigNumber.ROUND_HALF_DOWN = 5;
BigNumber.ROUND_HALF_EVEN = 6;
BigNumber.ROUND_HALF_CEIL = 7;
BigNumber.ROUND_HALF_FLOOR = 8;
BigNumber.EUCLID = 9;
/*
* Configure infrequently-changing library-wide settings.
*
* Accept an object or an argument list, with one or many of the following properties or
* parameters respectively:
*
* DECIMAL_PLACES {number} Integer, 0 to MAX inclusive
* ROUNDING_MODE {number} Integer, 0 to 8 inclusive
* EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or
* [integer -MAX to 0 incl., 0 to MAX incl.]
* RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
* [integer -MAX to -1 incl., integer 1 to MAX incl.]
* ERRORS {boolean|number} true, false, 1 or 0
* CRYPTO {boolean|number} true, false, 1 or 0
* MODULO_MODE {number} 0 to 9 inclusive
* POW_PRECISION {number} 0 to MAX inclusive
* FORMAT {object} See BigNumber.prototype.toFormat
* decimalSeparator {string}
* groupSeparator {string}
* groupSize {number}
* secondaryGroupSize {number}
* fractionGroupSeparator {string}
* fractionGroupSize {number}
*
* (The values assigned to the above FORMAT object properties are not checked for validity.)
*
* E.g.
* BigNumber.config(20, 4) is equivalent to
* BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
*
* Ignore properties/parameters set to null or undefined.
* Return an object with the properties current values.
*/
BigNumber.config = BigNumber.set = function () {
var v, p,
i = 0,
r = {},
a = arguments,
o = a[0],
has = o && typeof o == 'object'
? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; }
: function () { if ( a.length > i ) return ( v = a[i++] ) != null; };
// DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
// 'config() DECIMAL_PLACES not an integer: {v}'
// 'config() DECIMAL_PLACES out of range: {v}'
if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) {
DECIMAL_PLACES = v | 0;
}
r[p] = DECIMAL_PLACES;
// ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
// 'config() ROUNDING_MODE not an integer: {v}'
// 'config() ROUNDING_MODE out of range: {v}'
if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) {
ROUNDING_MODE = v | 0;
}
r[p] = ROUNDING_MODE;
// EXPONENTIAL_AT {number|number[]}
// Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive].
// 'config() EXPONENTIAL_AT not an integer: {v}'
// 'config() EXPONENTIAL_AT out of range: {v}'
if ( has( p = 'EXPONENTIAL_AT' ) ) {
if ( isArray(v) ) {
if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) {
TO_EXP_NEG = v[0] | 0;
TO_EXP_POS = v[1] | 0;
}
} else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 );
}
}
r[p] = [ TO_EXP_NEG, TO_EXP_POS ];
// RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
// [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
// 'config() RANGE not an integer: {v}'
// 'config() RANGE cannot be zero: {v}'
// 'config() RANGE out of range: {v}'
if ( has( p = 'RANGE' ) ) {
if ( isArray(v) ) {
if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) {
MIN_EXP = v[0] | 0;
MAX_EXP = v[1] | 0;
}
} else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 );
else if (ERRORS) raise( 2, p + ' cannot be zero', v );
}
}
r[p] = [ MIN_EXP, MAX_EXP ];
// ERRORS {boolean|number} true, false, 1 or 0.
// 'config() ERRORS not a boolean or binary digit: {v}'
if ( has( p = 'ERRORS' ) ) {
if ( v === !!v || v === 1 || v === 0 ) {
id = 0;
isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors;
} else if (ERRORS) {
raise( 2, p + notBool, v );
}
}
r[p] = ERRORS;
// CRYPTO {boolean|number} true, false, 1 or 0.
// 'config() CRYPTO not a boolean or binary digit: {v}'
// 'config() crypto unavailable: {crypto}'
if ( has( p = 'CRYPTO' ) ) {
if ( v === true || v === false || v === 1 || v === 0 ) {
if (v) {
v = typeof crypto == 'undefined';
if ( !v && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
CRYPTO = true;
} else if (ERRORS) {
raise( 2, 'crypto unavailable', v ? void 0 : crypto );
} else {
CRYPTO = false;
}
} else {
CRYPTO = false;
}
} else if (ERRORS) {
raise( 2, p + notBool, v );
}
}
r[p] = CRYPTO;
// MODULO_MODE {number} Integer, 0 to 9 inclusive.
// 'config() MODULO_MODE not an integer: {v}'
// 'config() MODULO_MODE out of range: {v}'
if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) {
MODULO_MODE = v | 0;
}
r[p] = MODULO_MODE;
// POW_PRECISION {number} Integer, 0 to MAX inclusive.
// 'config() POW_PRECISION not an integer: {v}'
// 'config() POW_PRECISION out of range: {v}'
if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) {
POW_PRECISION = v | 0;
}
r[p] = POW_PRECISION;
// FORMAT {object}
// 'config() FORMAT not an object: {v}'
if ( has( p = 'FORMAT' ) ) {
if ( typeof v == 'object' ) {
FORMAT = v;
} else if (ERRORS) {
raise( 2, p + ' not an object', v );
}
}
r[p] = FORMAT;
return r;
};
/*
* Return a new BigNumber whose value is the maximum of the arguments.
*
* arguments {number|string|BigNumber}
*/
BigNumber.max = function () { return maxOrMin( arguments, P.lt ); };
/*
* Return a new BigNumber whose value is the minimum of the arguments.
*
* arguments {number|string|BigNumber}
*/
BigNumber.min = function () { return maxOrMin( arguments, P.gt ); };
/*
* Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
* and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
* zeros are produced).
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
*
* 'random() decimal places not an integer: {dp}'
* 'random() decimal places out of range: {dp}'
* 'random() crypto unavailable: {crypto}'
*/
BigNumber.random = (function () {
var pow2_53 = 0x20000000000000;
// Return a 53 bit integer n, where 0 <= n < 9007199254740992.
// Check if Math.random() produces more than 32 bits of randomness.
// If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
// 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
? function () { return mathfloor( Math.random() * pow2_53 ); }
: function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
(Math.random() * 0x800000 | 0); };
return function (dp) {
var a, b, e, k, v,
i = 0,
c = [],
rand = new BigNumber(ONE);
dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0;
k = mathceil( dp / LOG_BASE );
if (CRYPTO) {
// Browsers supporting crypto.getRandomValues.
if (crypto.getRandomValues) {
a = crypto.getRandomValues( new Uint32Array( k *= 2 ) );
for ( ; i < k; ) {
// 53 bits:
// ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
// 11111 11111111 11111111 11111111 11100000 00000000 00000000
// ((Math.pow(2, 32) - 1) >>> 11).toString(2)
// 11111 11111111 11111111
// 0x20000 is 2^21.
v = a[i] * 0x20000 + (a[i + 1] >>> 11);
// Rejection sampling:
// 0 <= v < 9007199254740992
// Probability that v >= 9e15, is
// 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
if ( v >= 9e15 ) {
b = crypto.getRandomValues( new Uint32Array(2) );
a[i] = b[0];
a[i + 1] = b[1];
} else {
// 0 <= v <= 8999999999999999
// 0 <= (v % 1e14) <= 99999999999999
c.push( v % 1e14 );
i += 2;
}
}
i = k / 2;
// Node.js supporting crypto.randomBytes.
} else if (crypto.randomBytes) {
// buffer
a = crypto.randomBytes( k *= 7 );
for ( ; i < k; ) {
// 0x1000000000000 is 2^48, 0x10000000000 is 2^40
// 0x100000000 is 2^32, 0x1000000 is 2^24
// 11111 11111111 11111111 11111111 11111111 11111111 11111111
// 0 <= v < 9007199254740992
v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) +
( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) +
( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6];
if ( v >= 9e15 ) {
crypto.randomBytes(7).copy( a, i );
} else {
// 0 <= (v % 1e14) <= 99999999999999
c.push( v % 1e14 );
i += 7;
}
}
i = k / 7;
} else {
CRYPTO = false;
if (ERRORS) raise( 14, 'crypto unavailable', crypto );
}
}
// Use Math.random.
if (!CRYPTO) {
for ( ; i < k; ) {
v = random53bitInt();
if ( v < 9e15 ) c[i++] = v % 1e14;
}
}
k = c[--i];
dp %= LOG_BASE;
// Convert trailing digits to zeros according to dp.
if ( k && dp ) {
v = POWS_TEN[LOG_BASE - dp];
c[i] = mathfloor( k / v ) * v;
}
// Remove trailing elements which are zero.
for ( ; c[i] === 0; c.pop(), i-- );
// Zero?
if ( i < 0 ) {
c = [ e = 0 ];
} else {
// Remove leading elements which are zero and adjust exponent accordingly.
for ( e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);
// Count the digits of the first element of c to determine leading zeros, and...
for ( i = 1, v = c[0]; v >= 10; v /= 10, i++);
// adjust the exponent accordingly.
if ( i < LOG_BASE ) e -= LOG_BASE - i;
}
rand.e = e;
rand.c = c;
return rand;
};
})();
// PRIVATE FUNCTIONS
// Convert a numeric string of baseIn to a numeric string of baseOut.
function convertBase( str, baseOut, baseIn, sign ) {
var d, e, k, r, x, xc, y,
i = str.indexOf( '.' ),
dp = DECIMAL_PLACES,
rm = ROUNDING_MODE;
if ( baseIn < 37 ) str = str.toLowerCase();
// Non-integer.
if ( i >= 0 ) {
k = POW_PRECISION;
// Unlimited precision.
POW_PRECISION = 0;
str = str.replace( '.', '' );
y = new BigNumber(baseIn);
x = y.pow( str.length - i );
POW_PRECISION = k;
// Convert str as if an integer, then restore the fraction part by dividing the
// result by its base raised to a power.
y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );
y.e = y.c.length;
}
// Convert the number as integer.
xc = toBaseOut( str, baseIn, baseOut );
e = k = xc.length;
// Remove trailing zeros.
for ( ; xc[--k] == 0; xc.pop() );
if ( !xc[0] ) return '0';
if ( i < 0 ) {
--e;
} else {
x.c = xc;
x.e = e;
// sign is needed for correct rounding.
x.s = sign;
x = div( x, y, dp, rm, baseOut );
xc = x.c;
r = x.r;
e = x.e;
}
d = e + dp + 1;
// The rounding digit, i.e. the digit to the right of the digit that may be rounded up.
i = xc[d];
k = baseOut / 2;
r = r || d < 0 || xc[d + 1] != null;
r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
: i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
rm == ( x.s < 0 ? 8 : 7 ) );
if ( d < 1 || !xc[0] ) {
// 1^-dp or 0.
str = r ? toFixedPoint( '1', -dp ) : '0';
} else {
xc.length = d;
if (r) {
// Rounding up may mean the previous digit has to be rounded up and so on.
for ( --baseOut; ++xc[--d] > baseOut; ) {
xc[d] = 0;
if ( !d ) {
++e;
xc = [1].concat(xc);
}
}
}
// Determine trailing zeros.
for ( k = xc.length; !xc[--k]; );
// E.g. [4, 11, 15] becomes 4bf.
for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );
str = toFixedPoint( str, e );
}
// The caller will add the sign.
return str;
}
// Perform division in the specified base. Called by div and convertBase.
div = (function () {
// Assume non-zero x and k.
function multiply( x, k, base ) {
var m, temp, xlo, xhi,
carry = 0,
i = x.length,
klo = k % SQRT_BASE,
khi = k / SQRT_BASE | 0;
for ( x = x.slice(); i--; ) {
xlo = x[i] % SQRT_BASE;
xhi = x[i] / SQRT_BASE | 0;
m = khi * xlo + xhi * klo;
temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;
carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;
x[i] = temp % base;
}
if (carry) x = [carry].concat(x);
return x;
}
function compare( a, b, aL, bL ) {
var i, cmp;
if ( aL != bL ) {
cmp = aL > bL ? 1 : -1;
} else {
for ( i = cmp = 0; i < aL; i++ ) {
if ( a[i] != b[i] ) {
cmp = a[i] > b[i] ? 1 : -1;
break;
}
}
}
return cmp;
}
function subtract( a, b, aL, base ) {
var i = 0;
// Subtract b from a.
for ( ; aL--; ) {
a[aL] -= i;
i = a[aL] < b[aL] ? 1 : 0;
a[aL] = i * base + a[aL] - b[aL];
}
// Remove leading zeros.
for ( ; !a[0] && a.length > 1; a.splice(0, 1) );
}
// x: dividend, y: divisor.
return function ( x, y, dp, rm, base ) {
var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
yL, yz,
s = x.s == y.s ? 1 : -1,
xc = x.c,
yc = y.c;
// Either NaN, Infinity or 0?
if ( !xc || !xc[0] || !yc || !yc[0] ) {
return new BigNumber(
// Return NaN if either NaN, or both Infinity or 0.
!x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :
// Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
xc && xc[0] == 0 || !yc ? s * 0 : s / 0
);
}
q = new BigNumber(s);
qc = q.c = [];
e = x.e - y.e;
s = dp + e + 1;
if ( !base ) {
base = BASE;
e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE );
s = s / LOG_BASE | 0;
}
// Result exponent may be one less then the current value of e.
// The coefficients of the BigNumbers from convertBase may have trailing zeros.
for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );
if ( yc[i] > ( xc[i] || 0 ) ) e--;
if ( s < 0 ) {
qc.push(1);
more = true;
} else {
xL = xc.length;
yL = yc.length;
i = 0;
s += 2;
// Normalise xc and yc so highest order digit of yc is >= base / 2.
n = mathfloor( base / ( yc[0] + 1 ) );
// Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1.
// if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) {
if ( n > 1 ) {
yc = multiply( yc, n, base );
xc = multiply( xc, n, base );
yL = yc.length;
xL = xc.length;
}
xi = yL;
rem = xc.slice( 0, yL );
remL = rem.length;
// Add zeros to make remainder as long as divisor.
for ( ; remL < yL; rem[remL++] = 0 );
yz = yc.slice();
yz = [0].concat(yz);
yc0 = yc[0];
if ( yc[1] >= base / 2 ) yc0++;
// Not necessary, but to prevent trial digit n > base, when using base 3.
// else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15;
do {
n = 0;
// Compare divisor and remainder.
cmp = compare( yc, rem, yL, remL );
// If divisor < remainder.
if ( cmp < 0 ) {
// Calculate trial digit, n.
rem0 = rem[0];
if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 );
// n is how many times the divisor goes into the current remainder.
n = mathfloor( rem0 / yc0 );
// Algorithm:
// 1. product = divisor * trial digit (n)
// 2. if product > remainder: product -= divisor, n--
// 3. remainder -= product
// 4. if product was < remainder at 2:
// 5. compare new remainder and divisor
// 6. If remainder > divisor: remainder -= divisor, n++
if ( n > 1 ) {
// n may be > base only when base is 3.
if (n >= base) n = base - 1;
// product = divisor * trial digit.
prod = multiply( yc, n, base );
prodL = prod.length;
remL = rem.length;
// Compare product and remainder.
// If product > remainder.
// Trial digit n too high.
// n is 1 too high about 5% of the time, and is not known to have
// ever been more than 1 too high.
while ( compare( prod, rem, prodL, remL ) == 1 ) {
n--;
// Subtract divisor from product.
subtract( prod, yL < prodL ? yz : yc, prodL, base );
prodL = prod.length;
cmp = 1;
}
} else {
// n is 0 or 1, cmp is -1.
// If n is 0, there is no need to compare yc and rem again below,
// so change cmp to 1 to avoid it.
// If n is 1, leave cmp as -1, so yc and rem are compared again.
if ( n == 0 ) {
// divisor < remainder, so n must be at least 1.
cmp = n = 1;
}
// product = divisor
prod = yc.slice();
prodL = prod.length;
}
if ( prodL < remL ) prod = [0].concat(prod);
// Subtract product from remainder.
subtract( rem, prod, remL, base );
remL = rem.length;
// If product was < remainder.
if ( cmp == -1 ) {
// Compare divisor and new remainder.
// If divisor < new remainder, subtract divisor from remainder.
// Trial digit n too low.
// n is 1 too low about 5% of the time, and very rarely 2 too low.
while ( compare( yc, rem, yL, remL ) < 1 ) {
n++;
// Subtract divisor from remainder.
subtract( rem, yL < remL ? yz : yc, remL, base );
remL = rem.length;
}
}
} else if ( cmp === 0 ) {
n++;
rem = [0];
} // else cmp === 1 and n will be 0
// Add the next digit, n, to the result array.
qc[i++] = n;
// Update the remainder.
if ( rem[0] ) {
rem[remL++] = xc[xi] || 0;
} else {
rem = [ xc[xi] ];
remL = 1;
}
} while ( ( xi++ < xL || rem[0] != null ) && s-- );
more = rem[0] != null;
// Leading zero?
if ( !qc[0] ) qc.splice(0, 1);
}
if ( base == BASE ) {
// To calculate q.e, first get the number of digits of qc[0].
for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );
round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more );
// Caller is convertBase.
} else {
q.e = e;
q.r = +more;
}
return q;
};
})();
/*
* Return a string representing the value of BigNumber n in fixed-point or exponential
* notation rounded to the specified decimal places or significant digits.
*
* n is a BigNumber.
* i is the index of the last digit required (i.e. the digit that may be rounded up).
* rm is the rounding mode.
* caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24.
*/
function format( n, i, rm, caller ) {
var c0, e, ne, len, str;
rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode )
? rm | 0 : ROUNDING_MODE;
if ( !n.c ) return n.toString();
c0 = n.c[0];
ne = n.e;
if ( i == null ) {
str = coeffToString( n.c );
str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG
? toExponential( str, ne )
: toFixedPoint( str, ne );
} else {
n = round( new BigNumber(n), i, rm );
// n.e may have changed if the value was rounded up.
e = n.e;
str = coeffToString( n.c );
len = str.length;
// toPrecision returns exponential notation if the number of significant digits
// specified is less than the number of digits necessary to represent the integer
// part of the value in fixed-point notation.
// Exponential notation.
if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) {
// Append zeros?
for ( ; len < i; str += '0', len++ );
str = toExponential( str, e );
// Fixed-point notation.
} else {
i -= ne;
str = toFixedPoint( str, e );
// Append zeros?
if ( e + 1 > len ) {
if ( --i > 0 ) for ( str += '.'; i--; str += '0' );
} else {
i += e - len;
if ( i > 0 ) {
if ( e + 1 == len ) str += '.';
for ( ; i--; str += '0' );
}
}
}
}
return n.s < 0 && c0 ? '-' + str : str;
}
// Handle BigNumber.max and BigNumber.min.
function maxOrMin( args, method ) {
var m, n,
i = 0;
if ( isArray( args[0] ) ) args = args[0];
m = new BigNumber( args[0] );
for ( ; ++i < args.length; ) {
n = new BigNumber( args[i] );
// If any number is NaN, return NaN.
if ( !n.s ) {
m = n;
break;
} else if ( method.call( m, n ) ) {
m = n;
}
}
return m;
}
/*
* Return true if n is an integer in range, otherwise throw.
* Use for argument validation when ERRORS is true.
*/
function intValidatorWithErrors( n, min, max, caller, name ) {
if ( n < min || n > max || n != truncate(n) ) {
raise( caller, ( name || 'decimal places' ) +
( n < min || n > max ? ' out of range' : ' not an integer' ), n );
}
return true;
}
/*
* Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
* Called by minus, plus and times.
*/
function normalise( n, c, e ) {
var i = 1,
j = c.length;
// Remove trailing zeros.
for ( ; !c[--j]; c.pop() );
// Calculate the base 10 exponent. First get the number of digits of c[0].
for ( j = c[0]; j >= 10; j /= 10, i++ );
// Overflow?
if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) {
// Infinity.
n.c = n.e = null;
// Underflow?
} else if ( e < MIN_EXP ) {
// Zero.
n.c = [ n.e = 0 ];
} else {
n.e = e;
n.c = c;
}
return n;
}
// Handle values that fail the validity test in BigNumber.
parseNumeric = (function () {
var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,
dotAfter = /^([^.]+)\.$/,
dotBefore = /^\.([^.]+)$/,
isInfinityOrNaN = /^-?(Infinity|NaN)$/,
whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
return function ( x, str, num, b ) {
var base,
s = num ? str : str.replace( whitespaceOrPlus, '' );
// No exception on ±Infinity or NaN.
if ( isInfinityOrNaN.test(s) ) {
x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
} else {
if ( !num ) {
// basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
s = s.replace( basePrefix, function ( m, p1, p2 ) {
base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
return !b || b == base ? p1 : m;
});
if (b) {
base = b;
// E.g. '1.' to '1', '.1' to '0.1'
s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' );
}
if ( str != s ) return new BigNumber( s, base );
}
// 'new BigNumber() not a number: {n}'
// 'new BigNumber() not a base {b} number: {n}'
if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str );
x.s = null;
}
x.c = x.e = null;
id = 0;
}
})();
// Throw a BigNumber Error.
function raise( caller, msg, val ) {
var error = new Error( [
'new BigNumber', // 0
'cmp', // 1
'config', // 2
'div', // 3
'divToInt', // 4
'eq', // 5
'gt', // 6
'gte', // 7
'lt', // 8
'lte', // 9
'minus', // 10
'mod', // 11
'plus', // 12
'precision', // 13
'random', // 14
'round', // 15
'shift', // 16
'times', // 17
'toDigits', // 18
'toExponential', // 19
'toFixed', // 20
'toFormat', // 21
'toFraction', // 22
'pow', // 23
'toPrecision', // 24
'toString', // 25
'BigNumber' // 26
][caller] + '() ' + msg + ': ' + val );
error.name = 'BigNumber Error';
id = 0;
throw error;
}
/*
* Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
* If r is truthy, it is known that there are more digits after the rounding digit.
*/
function round( x, sd, rm, r ) {
var d, i, j, k, n, ni, rd,
xc = x.c,
pows10 = POWS_TEN;
// if x is not Infinity or NaN...
if (xc) {
// rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
// n is a base 1e14 number, the value of the element of array x.c containing rd.
// ni is the index of n within x.c.
// d is the number of digits of n.
// i is the index of rd within n including leading zeros.
// j is the actual index of rd within n (if < 0, rd is a leading zero).
out: {
// Get the number of digits of the first element of xc.
for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );
i = sd - d;
// If the rounding digit is in the first element of xc...
if ( i < 0 ) {
i += LOG_BASE;
j = sd;
n = xc[ ni = 0 ];
// Get the rounding digit at index j of n.
rd = n / pows10[ d - j - 1 ] % 10 | 0;
} else {
ni = mathceil( ( i + 1 ) / LOG_BASE );
if ( ni >= xc.length ) {
if (r) {
// Needed by sqrt.
for ( ; xc.length <= ni; xc.push(0) );
n = rd = 0;
d = 1;
i %= LOG_BASE;
j = i - LOG_BASE + 1;
} else {
break out;
}
} else {
n = k = xc[ni];
// Get the number of digits of n.
for ( d = 1; k >= 10; k /= 10, d++ );
// Get the index of rd within n.
i %= LOG_BASE;
// Get the index of rd within n, adjusted for leading zeros.
// The number of leading zeros of n is given by LOG_BASE - d.
j = i - LOG_BASE + d;
// Get the rounding digit at index j of n.
rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;
}
}
r = r || sd < 0 ||
// Are there any non-zero digits after the rounding digit?
// The expression n % pows10[ d - j - 1 ] returns all digits of n to the right
// of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );
r = rm < 4
? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
: rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&
// Check whether the digit to the left of the rounding digit is odd.
( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||
rm == ( x.s < 0 ? 8 : 7 ) );
if ( sd < 1 || !xc[0] ) {
xc.length = 0;
if (r) {
// Convert sd to decimal places.
sd -= x.e + 1;
// 1, 0.1, 0.01, 0.001, 0.0001 etc.
xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ];
x.e = -sd || 0;
} else {
// Zero.
xc[0] = x.e = 0;
}
return x;
}
// Remove excess digits.
if ( i == 0 ) {
xc.length = ni;
k = 1;
ni--;
} else {
xc.length = ni + 1;
k = pows10[ LOG_BASE - i ];
// E.g. 56700 becomes 56000 if 7 is the rounding digit.
// j > 0 means i > number of leading zeros of n.
xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;
}
// Round up?
if (r) {
for ( ; ; ) {
// If the digit to be rounded up is in the first element of xc...
if ( ni == 0 ) {
// i will be the length of xc[0] before k is added.
for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );
j = xc[0] += k;
for ( k = 1; j >= 10; j /= 10, k++ );
// if i != k the length has increased.
if ( i != k ) {
x.e++;
if ( xc[0] == BASE ) xc[0] = 1;
}
break;
} else {
xc[ni] += k;
if ( xc[ni] != BASE ) break;
xc[ni--] = 0;
k = 1;
}
}
}
// Remove trailing zeros.
for ( i = xc.length; xc[--i] === 0; xc.pop() );
}
// Overflow? Infinity.
if ( x.e > MAX_EXP ) {
x.c = x.e = null;
// Underflow? Zero.
} else if ( x.e < MIN_EXP ) {
x.c = [ x.e = 0 ];
}
}
return x;
}
// PROTOTYPE/INSTANCE METHODS
/*
* Return a new BigNumber whose value is the absolute value of this BigNumber.
*/
P.absoluteValue = P.abs = function () {
var x = new BigNumber(this);
if ( x.s < 0 ) x.s = 1;
return x;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
* number in the direction of Infinity.
*/
P.ceil = function () {
return round( new BigNumber(this), this.e + 1, 2 );
};
/*
* Return
* 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
* -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
* 0 if they have the same value,
* or null if the value of either is NaN.
*/
P.comparedTo = P.cmp = function ( y, b ) {
id = 1;
return compare( this, new BigNumber( y, b ) );
};
/*
* Return the number of decimal places of the value of this BigNumber, or null if the value
* of this BigNumber is ±Infinity or NaN.
*/
P.decimalPlaces = P.dp = function () {
var n, v,
c = this.c;
if ( !c ) return null;
n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE;
// Subtract the number of trailing zeros of the last number.
if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- );
if ( n < 0 ) n = 0;
return n;
};
/*
* n / 0 = I
* n / N = N
* n / I = 0
* 0 / n = 0
* 0 / 0 = N
* 0 / N = N
* 0 / I = 0
* N / n = N
* N / 0 = N
* N / N = N
* N / I = N
* I / n = I
* I / 0 = I
* I / N = N
* I / I = N
*
* Return a new BigNumber whose value is the value of this BigNumber divided by the value of
* BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
*/
P.dividedBy = P.div = function ( y, b ) {
id = 3;
return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE );
};
/*
* Return a new BigNumber whose value is the integer part of dividing the value of this
* BigNumber by the value of BigNumber(y, b).
*/
P.dividedToIntegerBy = P.divToInt = function ( y, b ) {
id = 4;
return div( this, new BigNumber( y, b ), 0, 1 );
};
/*
* Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
* otherwise returns false.
*/
P.equals = P.eq = function ( y, b ) {
id = 5;
return compare( this, new BigNumber( y, b ) ) === 0;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
* number in the direction of -Infinity.
*/
P.floor = function () {
return round( new BigNumber(this), this.e + 1, 3 );
};
/*
* Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
* otherwise returns false.
*/
P.greaterThan = P.gt = function ( y, b ) {
id = 6;
return compare( this, new BigNumber( y, b ) ) > 0;
};
/*
* Return true if the value of this BigNumber is greater than or equal to the value of
* BigNumber(y, b), otherwise returns false.
*/
P.greaterThanOrEqualTo = P.gte = function ( y, b ) {
id = 7;
return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0;
};
/*
* Return true if the value of this BigNumber is a finite number, otherwise returns false.
*/
P.isFinite = function () {
return !!this.c;
};
/*
* Return true if the value of this BigNumber is an integer, otherwise return false.
*/
P.isInteger = P.isInt = function () {
return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2;
};
/*
* Return true if the value of this BigNumber is NaN, otherwise returns false.
*/
P.isNaN = function () {
return !this.s;
};
/*
* Return true if the value of this BigNumber is negative, otherwise returns false.
*/
P.isNegative = P.isNeg = function () {
return this.s < 0;
};
/*
* Return true if the value of this BigNumber is 0 or -0, otherwise returns false.
*/
P.isZero = function () {
return !!this.c && this.c[0] == 0;
};
/*
* Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
* otherwise returns false.
*/
P.lessThan = P.lt = function ( y, b ) {
id = 8;
return compare( this, new BigNumber( y, b ) ) < 0;
};
/*
* Return true if the value of this BigNumber is less than or equal to the value of
* BigNumber(y, b), otherwise returns false.
*/
P.lessThanOrEqualTo = P.lte = function ( y, b ) {
id = 9;
return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0;
};
/*
* n - 0 = n
* n - N = N
* n - I = -I
* 0 - n = -n
* 0 - 0 = 0
* 0 - N = N
* 0 - I = -I
* N - n = N
* N - 0 = N
* N - N = N
* N - I = N
* I - n = I
* I - 0 = I
* I - N = N
* I - I = N
*
* Return a new BigNumber whose value is the value of this BigNumber minus the value of
* BigNumber(y, b).
*/
P.minus = P.sub = function ( y, b ) {
var i, j, t, xLTy,
x = this,
a = x.s;
id = 10;
y = new BigNumber( y, b );
b = y.s;
// Either NaN?
if ( !a || !b ) return new BigNumber(NaN);
// Signs differ?
if ( a != b ) {
y.s = -b;
return x.plus(y);
}
var xe = x.e / LOG_BASE,
ye = y.e / LOG_BASE,
xc = x.c,
yc = y.c;
if ( !xe || !ye ) {
// Either Infinity?
if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN );
// Either zero?
if ( !xc[0] || !yc[0] ) {
// Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x :
// IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
ROUNDING_MODE == 3 ? -0 : 0 );
}
}
xe = bitFloor(xe);
ye = bitFloor(ye);
xc = xc.slice();
// Determine which is the bigger number.
if ( a = xe - ye ) {
if ( xLTy = a < 0 ) {
a = -a;
t = xc;
} else {
ye = xe;
t = yc;
}
t.reverse();
// Prepend zeros to equalise exponents.
for ( b = a; b--; t.push(0) );
t.reverse();
} else {
// Exponents equal. Check digit by digit.
j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b;
for ( a = b = 0; b < j; b++ ) {
if ( xc[b] != yc[b] ) {
xLTy = xc[b] < yc[b];
break;
}
}
}
// x < y? Point xc to the array of the bigger number.
if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
b = ( j = yc.length ) - ( i = xc.length );
// Append zeros to xc if shorter.
// No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
if ( b > 0 ) for ( ; b--; xc[i++] = 0 );
b = BASE - 1;
// Subtract yc from xc.
for ( ; j > a; ) {
if ( xc[--j] < yc[j] ) {
for ( i = j; i && !xc[--i]; xc[i] = b );
--xc[i];
xc[j] += BASE;
}
xc[j] -= yc[j];
}
// Remove leading zeros and adjust exponent accordingly.
for ( ; xc[0] == 0; xc.splice(0, 1), --ye );
// Zero?
if ( !xc[0] ) {
// Following IEEE 754 (2008) 6.3,
// n - n = +0 but n - n = -0 when rounding towards -Infinity.
y.s = ROUNDING_MODE == 3 ? -1 : 1;
y.c = [ y.e = 0 ];
return y;
}
// No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
// for finite x and y.
return normalise( y, xc, ye );
};
/*
* n % 0 = N
* n % N = N
* n % I = n
* 0 % n = 0
* -0 % n = -0
* 0 % 0 = N
* 0 % N = N
* 0 % I = 0
* N % n = N
* N % 0 = N
* N % N = N
* N % I = N
* I % n = N
* I % 0 = N
* I % N = N
* I % I = N
*
* Return a new BigNumber whose value is the value of this BigNumber modulo the value of
* BigNumber(y, b). The result depends on the value of MODULO_MODE.
*/
P.modulo = P.mod = function ( y, b ) {
var q, s,
x = this;
id = 11;
y = new BigNumber( y, b );
// Return NaN if x is Infinity or NaN, or y is NaN or zero.
if ( !x.c || !y.s || y.c && !y.c[0] ) {
return new BigNumber(NaN);
// Return x if y is Infinity or x is zero.
} else if ( !y.c || x.c && !x.c[0] ) {
return new BigNumber(x);
}
if ( MODULO_MODE == 9 ) {
// Euclidian division: q = sign(y) * floor(x / abs(y))
// r = x - qy where 0 <= r < abs(y)
s = y.s;
y.s = 1;
q = div( x, y, 0, 3 );
y.s = s;
q.s *= s;
} else {
q = div( x, y, 0, MODULO_MODE );
}
return x.minus( q.times(y) );
};
/*
* Return a new BigNumber whose value is the value of this BigNumber negated,
* i.e. multiplied by -1.
*/
P.negated = P.neg = function () {
var x = new BigNumber(this);
x.s = -x.s || null;
return x;
};
/*
* n + 0 = n
* n + N = N
* n + I = I
* 0 + n = n
* 0 + 0 = 0
* 0 + N = N
* 0 + I = I
* N + n = N
* N + 0 = N
* N + N = N
* N + I = N
* I + n = I
* I + 0 = I
* I + N = N
* I + I = I
*
* Return a new BigNumber whose value is the value of this BigNumber plus the value of
* BigNumber(y, b).
*/
P.plus = P.add = function ( y, b ) {
var t,
x = this,
a = x.s;
id = 12;
y = new BigNumber( y, b );
b = y.s;
// Either NaN?
if ( !a || !b ) return new BigNumber(NaN);
// Signs differ?
if ( a != b ) {
y.s = -b;
return x.minus(y);
}
var xe = x.e / LOG_BASE,
ye = y.e / LOG_BASE,
xc = x.c,
yc = y.c;
if ( !xe || !ye ) {
// Return ±Infinity if either ±Infinity.
if ( !xc || !yc ) return new BigNumber( a / 0 );
// Either zero?
// Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 );
}
xe = bitFloor(xe);
ye = bitFloor(ye);
xc = xc.slice();
// Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
if ( a = xe - ye ) {
if ( a > 0 ) {
ye = xe;
t = yc;
} else {
a = -a;
t = xc;
}
t.reverse();
for ( ; a--; t.push(0) );
t.reverse();
}
a = xc.length;
b = yc.length;
// Point xc to the longer array, and b to the shorter length.
if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a;
// Only start adding at yc.length - 1 as the further digits of xc can be ignored.
for ( a = 0; b; ) {
a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0;
xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;
}
if (a) {
xc = [a].concat(xc);
++ye;
}
// No need to check for zero, as +x + +y != 0 && -x + -y != 0
// ye = MAX_EXP + 1 possible
return normalise( y, xc, ye );
};
/*
* Return the number of significant digits of the value of this BigNumber.
*
* [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
*/
P.precision = P.sd = function (z) {
var n, v,
x = this,
c = x.c;
// 'precision() argument not a boolean or binary digit: {z}'
if ( z != null && z !== !!z && z !== 1 && z !== 0 ) {
if (ERRORS) raise( 13, 'argument' + notBool, z );
if ( z != !!z ) z = null;
}
if ( !c ) return null;
v = c.length - 1;
n = v * LOG_BASE + 1;
if ( v = c[v] ) {
// Subtract the number of trailing zeros of the last element.
for ( ; v % 10 == 0; v /= 10, n-- );
// Add the number of digits of the first element.
for ( v = c[0]; v >= 10; v /= 10, n++ );
}
if ( z && x.e + 1 > n ) n = x.e + 1;
return n;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
* dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if
* omitted.
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'round() decimal places out of range: {dp}'
* 'round() decimal places not an integer: {dp}'
* 'round() rounding mode not an integer: {rm}'
* 'round() rounding mode out of range: {rm}'
*/
P.round = function ( dp, rm ) {
var n = new BigNumber(this);
if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) {
round( n, ~~dp + this.e + 1, rm == null ||
!isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 );
}
return n;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber shifted by k places
* (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
*
* k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
*
* If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity
* otherwise.
*
* 'shift() argument not an integer: {k}'
* 'shift() argument out of range: {k}'
*/
P.shift = function (k) {
var n = this;
return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' )
// k < 1e+21, or truncate(k) will produce exponential notation.
? n.times( '1e' + truncate(k) )
: new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER )
? n.s * ( k < 0 ? 0 : 1 / 0 )
: n );
};
/*
* sqrt(-n) = N
* sqrt( N) = N
* sqrt(-I) = N
* sqrt( I) = I
* sqrt( 0) = 0
* sqrt(-0) = -0
*
* Return a new BigNumber whose value is the square root of the value of this BigNumber,
* rounded according to DECIMAL_PLACES and ROUNDING_MODE.
*/
P.squareRoot = P.sqrt = function () {
var m, n, r, rep, t,
x = this,
c = x.c,
s = x.s,
e = x.e,
dp = DECIMAL_PLACES + 4,
half = new BigNumber('0.5');
// Negative/NaN/Infinity/zero?
if ( s !== 1 || !c || !c[0] ) {
return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );
}
// Initial estimate.
s = Math.sqrt( +x );
// Math.sqrt underflow/overflow?
// Pass x to Math.sqrt as integer, then adjust the exponent of the result.
if ( s == 0 || s == 1 / 0 ) {
n = coeffToString(c);
if ( ( n.length + e ) % 2 == 0 ) n += '0';
s = Math.sqrt(n);
e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
if ( s == 1 / 0 ) {
n = '1e' + e;
} else {
n = s.toExponential();
n = n.slice( 0, n.indexOf('e') + 1 ) + e;
}
r = new BigNumber(n);
} else {
r = new BigNumber( s + '' );
}
// Check for zero.
// r could be zero if MIN_EXP is changed after the this value was created.
// This would cause a division by zero (x/t) and hence Infinity below, which would cause
// coeffToString to throw.
if ( r.c[0] ) {
e = r.e;
s = e + dp;
if ( s < 3 ) s = 0;
// Newton-Raphson iteration.
for ( ; ; ) {
t = r;
r = half.times( t.plus( div( x, t, dp, 1 ) ) );
if ( coeffToString( t.c ).slice( 0, s ) === ( n =
coeffToString( r.c ) ).slice( 0, s ) ) {
// The exponent of r may here be one less than the final result exponent,
// e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
// are indexed correctly.
if ( r.e < e ) --s;
n = n.slice( s - 3, s + 1 );
// The 4th rounding digit may be in error by -1 so if the 4 rounding digits
// are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
// iteration.
if ( n == '9999' || !rep && n == '4999' ) {
// On the first iteration only, check to see if rounding up gives the
// exact result as the nines may infinitely repeat.
if ( !rep ) {
round( t, t.e + DECIMAL_PLACES + 2, 0 );
if ( t.times(t).eq(x) ) {
r = t;
break;
}
}
dp += 4;
s += 4;
rep = 1;
} else {
// If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
// result. If not, then there are further digits and m will be truthy.
if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {
// Truncate to the first rounding digit.
round( r, r.e + DECIMAL_PLACES + 2, 1 );
m = !r.times(r).eq(x);
}
break;
}
}
}
}
return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m );
};
/*
* n * 0 = 0
* n * N = N
* n * I = I
* 0 * n = 0
* 0 * 0 = 0
* 0 * N = N
* 0 * I = N
* N * n = N
* N * 0 = N
* N * N = N
* N * I = N
* I * n = I
* I * 0 = N
* I * N = N
* I * I = I
*
* Return a new BigNumber whose value is the value of this BigNumber times the value of
* BigNumber(y, b).
*/
P.times = P.mul = function ( y, b ) {
var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
base, sqrtBase,
x = this,
xc = x.c,
yc = ( id = 17, y = new BigNumber( y, b ) ).c;
// Either NaN, ±Infinity or ±0?
if ( !xc || !yc || !xc[0] || !yc[0] ) {
// Return NaN if either is NaN, or one is 0 and the other is Infinity.
if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) {
y.c = y.e = y.s = null;
} else {
y.s *= x.s;
// Return ±Infinity if either is ±Infinity.
if ( !xc || !yc ) {
y.c = y.e = null;
// Return ±0 if either is ±0.
} else {
y.c = [0];
y.e = 0;
}
}
return y;
}
e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE );
y.s *= x.s;
xcL = xc.length;
ycL = yc.length;
// Ensure xc points to longer array and xcL to its length.
if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
// Initialise the result array with zeros.
for ( i = xcL + ycL, zc = []; i--; zc.push(0) );
base = BASE;
sqrtBase = SQRT_BASE;
for ( i = ycL; --i >= 0; ) {
c = 0;
ylo = yc[i] % sqrtBase;
yhi = yc[i] / sqrtBase | 0;
for ( k = xcL, j = i + k; j > i; ) {
xlo = xc[--k] % sqrtBase;
xhi = xc[k] / sqrtBase | 0;
m = yhi * xlo + xhi * ylo;
xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c;
c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi;
zc[j--] = xlo % base;
}
zc[j] = c;
}
if (c) {
++e;
} else {
zc.splice(0, 1);
}
return normalise( y, zc, e );
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
* sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted.
*
* [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toDigits() precision out of range: {sd}'
* 'toDigits() precision not an integer: {sd}'
* 'toDigits() rounding mode not an integer: {rm}'
* 'toDigits() rounding mode out of range: {rm}'
*/
P.toDigits = function ( sd, rm ) {
var n = new BigNumber(this);
sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0;
rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0;
return sd ? round( n, sd, rm ) : n;
};
/*
* Return a string representing the value of this BigNumber in exponential notation and
* rounded using ROUNDING_MODE to dp fixed decimal places.
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toExponential() decimal places not an integer: {dp}'
* 'toExponential() decimal places out of range: {dp}'
* 'toExponential() rounding mode not an integer: {rm}'
* 'toExponential() rounding mode out of range: {rm}'
*/
P.toExponential = function ( dp, rm ) {
return format( this,
dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 );
};
/*
* Return a string representing the value of this BigNumber in fixed-point notation rounding
* to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
*
* Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
* but e.g. (-0.00001).toFixed(0) is '-0'.
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toFixed() decimal places not an integer: {dp}'
* 'toFixed() decimal places out of range: {dp}'
* 'toFixed() rounding mode not an integer: {rm}'
* 'toFixed() rounding mode out of range: {rm}'
*/
P.toFixed = function ( dp, rm ) {
return format( this, dp != null && isValidInt( dp, 0, MAX, 20 )
? ~~dp + this.e + 1 : null, rm, 20 );
};
/*
* Return a string representing the value of this BigNumber in fixed-point notation rounded
* using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
* of the FORMAT object (see BigNumber.config).
*
* FORMAT = {
* decimalSeparator : '.',
* groupSeparator : ',',
* groupSize : 3,
* secondaryGroupSize : 0,
* fractionGroupSeparator : '\xA0', // non-breaking space
* fractionGroupSize : 0
* };
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toFormat() decimal places not an integer: {dp}'
* 'toFormat() decimal places out of range: {dp}'
* 'toFormat() rounding mode not an integer: {rm}'
* 'toFormat() rounding mode out of range: {rm}'
*/
P.toFormat = function ( dp, rm ) {
var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 )
? ~~dp + this.e + 1 : null, rm, 21 );
if ( this.c ) {
var i,
arr = str.split('.'),
g1 = +FORMAT.groupSize,
g2 = +FORMAT.secondaryGroupSize,
groupSeparator = FORMAT.groupSeparator,
intPart = arr[0],
fractionPart = arr[1],
isNeg = this.s < 0,
intDigits = isNeg ? intPart.slice(1) : intPart,
len = intDigits.length;
if (g2) i = g1, g1 = g2, g2 = i, len -= i;
if ( g1 > 0 && len > 0 ) {
i = len % g1 || g1;
intPart = intDigits.substr( 0, i );
for ( ; i < len; i += g1 ) {
intPart += groupSeparator + intDigits.substr( i, g1 );
}
if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i);
if (isNeg) intPart = '-' + intPart;
}
str = fractionPart
? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize )
? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ),
'$&' + FORMAT.fractionGroupSeparator )
: fractionPart )
: intPart;
}
return str;
};
/*
* Return a string array representing the value of this BigNumber as a simple fraction with
* an integer numerator and an integer denominator. The denominator will be a positive
* non-zero value less than or equal to the specified maximum denominator. If a maximum
* denominator is not specified, the denominator will be the lowest value necessary to
* represent the number exactly.
*
* [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.
*
* 'toFraction() max denominator not an integer: {md}'
* 'toFraction() max denominator out of range: {md}'
*/
P.toFraction = function (md) {
var arr, d0, d2, e, exp, n, n0, q, s,
k = ERRORS,
x = this,
xc = x.c,
d = new BigNumber(ONE),
n1 = d0 = new BigNumber(ONE),
d1 = n0 = new BigNumber(ONE);
if ( md != null ) {
ERRORS = false;
n = new BigNumber(md);
ERRORS = k;
if ( !( k = n.isInt() ) || n.lt(ONE) ) {
if (ERRORS) {
raise( 22,
'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
}
// ERRORS is false:
// If md is a finite non-integer >= 1, round it to an integer and use it.
md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null;
}
}
if ( !xc ) return x.toString();
s = coeffToString(xc);
// Determine initial denominator.
// d is a power of 10 and the minimum max denominator that specifies the value exactly.
e = d.e = s.length - x.e - 1;
d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];
md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n;
exp = MAX_EXP;
MAX_EXP = 1 / 0;
n = new BigNumber(s);
// n0 = d1 = 0
n0.c[0] = 0;
for ( ; ; ) {
q = div( n, d, 0, 1 );
d2 = d0.plus( q.times(d1) );
if ( d2.cmp(md) == 1 ) break;
d0 = d1;
d1 = d2;
n1 = n0.plus( q.times( d2 = n1 ) );
n0 = d2;
d = n.minus( q.times( d2 = d ) );
n = d2;
}
d2 = div( md.minus(d0), d1, 0, 1 );
n0 = n0.plus( d2.times(n1) );
d0 = d0.plus( d2.times(d1) );
n0.s = n1.s = x.s;
e *= 2;
// Determine which fraction is closer to x, n0/d0 or n1/d1
arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp(
div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1
? [ n1.toString(), d1.toString() ]
: [ n0.toString(), d0.toString() ];
MAX_EXP = exp;
return arr;
};
/*
* Return the value of this BigNumber converted to a number primitive.
*/
P.toNumber = function () {
return +this;
};
/*
* Return a BigNumber whose value is the value of this BigNumber raised to the power n.
* If m is present, return the result modulo m.
* If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
* If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using
* ROUNDING_MODE.
*
* The modular power operation works efficiently when x, n, and m are positive integers,
* otherwise it is equivalent to calculating x.toPower(n).modulo(m) (with POW_PRECISION 0).
*
* n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
* [m] {number|string|BigNumber} The modulus.
*
* 'pow() exponent not an integer: {n}'
* 'pow() exponent out of range: {n}'
*
* Performs 54 loop iterations for n of 9007199254740991.
*/
P.toPower = P.pow = function ( n, m ) {
var k, y, z,
i = mathfloor( n < 0 ? -n : +n ),
x = this;
if ( m != null ) {
id = 23;
m = new BigNumber(m);
}
// Pass ±Infinity to Math.pow if exponent is out of range.
if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) &&
( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) ||
parseFloat(n) != n && !( n = NaN ) ) || n == 0 ) {
k = Math.pow( +x, n );
return new BigNumber( m ? k % m : k );
}
if (m) {
if ( n > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt() ) {
x = x.mod(m);
} else {
z = m;
// Nullify m so only a single mod operation is performed at the end.
m = null;
}
} else if (POW_PRECISION) {
// Truncating each coefficient array to a length of k after each multiplication
// equates to truncating significant digits to POW_PRECISION + [28, 41],
// i.e. there will be a minimum of 28 guard digits retained.
// (Using + 1.5 would give [9, 21] guard digits.)
k = mathceil( POW_PRECISION / LOG_BASE + 2 );
}
y = new BigNumber(ONE);
for ( ; ; ) {
if ( i % 2 ) {
y = y.times(x);
if ( !y.c ) break;
if (k) {
if ( y.c.length > k ) y.c.length = k;
} else if (m) {
y = y.mod(m);
}
}
i = mathfloor( i / 2 );
if ( !i ) break;
x = x.times(x);
if (k) {
if ( x.c && x.c.length > k ) x.c.length = k;
} else if (m) {
x = x.mod(m);
}
}
if (m) return y;
if ( n < 0 ) y = ONE.div(y);
return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;
};
/*
* Return a string representing the value of this BigNumber rounded to sd significant digits
* using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
* necessary to represent the integer part of the value in fixed-point notation, then use
* exponential notation.
*
* [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toPrecision() precision not an integer: {sd}'
* 'toPrecision() precision out of range: {sd}'
* 'toPrecision() rounding mode not an integer: {rm}'
* 'toPrecision() rounding mode out of range: {rm}'
*/
P.toPrecision = function ( sd, rm ) {
return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' )
? sd | 0 : null, rm, 24 );
};
/*
* Return a string representing the value of this BigNumber in base b, or base 10 if b is
* omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
* ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
* that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
* TO_EXP_NEG, return exponential notation.
*
* [b] {number} Integer, 2 to 64 inclusive.
*
* 'toString() base not an integer: {b}'
* 'toString() base out of range: {b}'
*/
P.toString = function (b) {
var str,
n = this,
s = n.s,
e = n.e;
// Infinity or NaN?
if ( e === null ) {
if (s) {
str = 'Infinity';
if ( s < 0 ) str = '-' + str;
} else {
str = 'NaN';
}
} else {
str = coeffToString( n.c );
if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) {
str = e <= TO_EXP_NEG || e >= TO_EXP_POS
? toExponential( str, e )
: toFixedPoint( str, e );
} else {
str = convertBase( toFixedPoint( str, e ), b | 0, 10, s );
}
if ( s < 0 && n.c[0] ) str = '-' + str;
}
return str;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber truncated to a whole
* number.
*/
P.truncated = P.trunc = function () {
return round( new BigNumber(this), this.e + 1, 1 );
};
/*
* Return as toString, but do not accept a base argument, and include the minus sign for
* negative zero.
*/
P.valueOf = P.toJSON = function () {
var str,
n = this,
e = n.e;
if ( e === null ) return n.toString();
str = coeffToString( n.c );
str = e <= TO_EXP_NEG || e >= TO_EXP_POS
? toExponential( str, e )
: toFixedPoint( str, e );
return n.s < 0 ? '-' + str : str;
};
P.isBigNumber = true;
if ( config != null ) BigNumber.config(config);
return BigNumber;
}
// PRIVATE HELPER FUNCTIONS
function bitFloor(n) {
var i = n | 0;
return n > 0 || n === i ? i : i - 1;
}
// Return a coefficient array as a string of base 10 digits.
function coeffToString(a) {
var s, z,
i = 1,
j = a.length,
r = a[0] + '';
for ( ; i < j; ) {
s = a[i++] + '';
z = LOG_BASE - s.length;
for ( ; z--; s = '0' + s );
r += s;
}
// Determine trailing zeros.
for ( j = r.length; r.charCodeAt(--j) === 48; );
return r.slice( 0, j + 1 || 1 );
}
// Compare the value of BigNumbers x and y.
function compare( x, y ) {
var a, b,
xc = x.c,
yc = y.c,
i = x.s,
j = y.s,
k = x.e,
l = y.e;
// Either NaN?
if ( !i || !j ) return null;
a = xc && !xc[0];
b = yc && !yc[0];
// Either zero?
if ( a || b ) return a ? b ? 0 : -j : i;
// Signs differ?
if ( i != j ) return i;
a = i < 0;
b = k == l;
// Either Infinity?
if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1;
// Compare exponents.
if ( !b ) return k > l ^ a ? 1 : -1;
j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
// Compare digit by digit.
for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1;
// Compare lengths.
return k == l ? 0 : k > l ^ a ? 1 : -1;
}
/*
* Return true if n is a valid number in range, otherwise false.
* Use for argument validation when ERRORS is false.
* Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10.
*/
function intValidatorNoErrors( n, min, max ) {
return ( n = truncate(n) ) >= min && n <= max;
}
function isArray(obj) {
return Object.prototype.toString.call(obj) == '[object Array]';
}
/*
* Convert string of baseIn to an array of numbers of baseOut.
* Eg. convertBase('255', 10, 16) returns [15, 15].
* Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
*/
function toBaseOut( str, baseIn, baseOut ) {
var j,
arr = [0],
arrL,
i = 0,
len = str.length;
for ( ; i < len; ) {
for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );
arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) );
for ( ; j < arr.length; j++ ) {
if ( arr[j] > baseOut - 1 ) {
if ( arr[j + 1] == null ) arr[j + 1] = 0;
arr[j + 1] += arr[j] / baseOut | 0;
arr[j] %= baseOut;
}
}
}
return arr.reverse();
}
function toExponential( str, e ) {
return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) +
( e < 0 ? 'e' : 'e+' ) + e;
}
function toFixedPoint( str, e ) {
var len, z;
// Negative exponent?
if ( e < 0 ) {
// Prepend zeros.
for ( z = '0.'; ++e; z += '0' );
str = z + str;
// Positive exponent
} else {
len = str.length;
// Append zeros.
if ( ++e > len ) {
for ( z = '0', e -= len; --e; z += '0' );
str += z;
} else if ( e < len ) {
str = str.slice( 0, e ) + '.' + str.slice(e);
}
}
return str;
}
function truncate(n) {
n = parseFloat(n);
return n < 0 ? mathceil(n) : mathfloor(n);
}
// EXPORT
BigNumber = constructorFactory();
BigNumber['default'] = BigNumber.BigNumber = BigNumber;
// AMD.
if ( true ) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return BigNumber; }).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
// Node.js and other environments that support module.exports.
} else {}
})(this);
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(96),
baseKeysIn = __webpack_require__(188),
isArrayLike = __webpack_require__(25);
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}
module.exports = keysIn;
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(50),
isLength = __webpack_require__(69);
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
module.exports = isArrayLike;
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsNative = __webpack_require__(202),
getValue = __webpack_require__(205);
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
module.exports = getNative;
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Asset = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _clone = __webpack_require__(28);
var _clone2 = _interopRequireDefault(_clone);
var _padEnd = __webpack_require__(140);
var _padEnd2 = _interopRequireDefault(_padEnd);
var _trimEnd = __webpack_require__(144);
var _trimEnd2 = _interopRequireDefault(_trimEnd);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _keypair = __webpack_require__(19);
var _strkey = __webpack_require__(8);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Asset class represents an asset, either the native asset (`XLM`)
* or an asset code / issuer account ID pair.
*
* An asset code describes an asset code and issuer pair. In the case of the native
* asset XLM, the issuer will be null.
*
* @constructor
* @param {string} code - The asset code.
* @param {string} issuer - The account ID of the issuer.
*/
var Asset = exports.Asset = function () {
function Asset(code, issuer) {
_classCallCheck(this, Asset);
if (!/^[a-zA-Z0-9]{1,12}$/.test(code)) {
throw new Error('Asset code is invalid (maximum alphanumeric, 12 characters at max)');
}
if (String(code).toLowerCase() !== 'xlm' && !issuer) {
throw new Error('Issuer cannot be null');
}
if (issuer && !_strkey.StrKey.isValidEd25519PublicKey(issuer)) {
throw new Error('Issuer is invalid');
}
if (String(code).toLowerCase() === 'xlm') {
// transform all xLM, Xlm, etc. variants -> XLM
this.code = 'XLM';
} else {
this.code = code;
}
this.issuer = issuer;
}
/**
* Returns an asset object for the native asset.
* @Return {Asset}
*/
_createClass(Asset, [{
key: 'toXDRObject',
/**
* Returns the xdr.Asset object for this asset.
* @returns {xdr.Asset} XDR asset object
*/
value: function toXDRObject() {
return this._toXDRObject(_xdr2.default.Asset);
}
/**
* Returns the xdr.ChangeTrustAsset object for this asset.
* @returns {xdr.ChangeTrustAsset} XDR asset object
*/
}, {
key: 'toChangeTrustXDRObject',
value: function toChangeTrustXDRObject() {
return this._toXDRObject(_xdr2.default.ChangeTrustAsset);
}
/**
* Returns the xdr.TrustLineAsset object for this asset.
* @returns {xdr.TrustLineAsset} XDR asset object
*/
}, {
key: 'toTrustLineXDRObject',
value: function toTrustLineXDRObject() {
return this._toXDRObject(_xdr2.default.TrustLineAsset);
}
/**
* Returns the xdr object for this asset.
* @param {xdr.Asset | xdr.ChangeTrustAsset} xdrAsset - The asset xdr object.
* @returns {xdr.Asset | xdr.ChangeTrustAsset | xdr.TrustLineAsset} XDR Asset object
*/
}, {
key: '_toXDRObject',
value: function _toXDRObject() {
var xdrAsset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _xdr2.default.Asset;
if (this.isNative()) {
return xdrAsset.assetTypeNative();
}
var xdrType = void 0;
var xdrTypeString = void 0;
if (this.code.length <= 4) {
xdrType = _xdr2.default.AlphaNum4;
xdrTypeString = 'assetTypeCreditAlphanum4';
} else {
xdrType = _xdr2.default.AlphaNum12;
xdrTypeString = 'assetTypeCreditAlphanum12';
}
// pad code with null bytes if necessary
var padLength = this.code.length <= 4 ? 4 : 12;
var paddedCode = (0, _padEnd2.default)(this.code, padLength, '\0');
// eslint-disable-next-line new-cap
var assetType = new xdrType({
assetCode: paddedCode,
issuer: _keypair.Keypair.fromPublicKey(this.issuer).xdrAccountId()
});
return new xdrAsset(xdrTypeString, assetType);
}
/**
* @returns {string} Asset code
*/
}, {
key: 'getCode',
value: function getCode() {
return (0, _clone2.default)(this.code);
}
/**
* @returns {string} Asset issuer
*/
}, {
key: 'getIssuer',
value: function getIssuer() {
return (0, _clone2.default)(this.issuer);
}
/**
* @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/)
* @returns {string} Asset type. Can be one of following types:
*
* - `native`,
* - `credit_alphanum4`,
* - `credit_alphanum12`, or
* - `unknown` as the error case (which should never occur)
*/
}, {
key: 'getAssetType',
value: function getAssetType() {
switch (this.getRawAssetType()) {
case _xdr2.default.AssetType.assetTypeNative():
return 'native';
case _xdr2.default.AssetType.assetTypeCreditAlphanum4():
return 'credit_alphanum4';
case _xdr2.default.AssetType.assetTypeCreditAlphanum12():
return 'credit_alphanum12';
default:
return 'unknown';
}
}
/**
* @returns {xdr.AssetType} the raw XDR representation of the asset type
*/
}, {
key: 'getRawAssetType',
value: function getRawAssetType() {
if (this.isNative()) {
return _xdr2.default.AssetType.assetTypeNative();
}
if (this.code.length <= 4) {
return _xdr2.default.AssetType.assetTypeCreditAlphanum4();
}
return _xdr2.default.AssetType.assetTypeCreditAlphanum12();
}
/**
* @returns {boolean} true if this asset object is the native asset.
*/
}, {
key: 'isNative',
value: function isNative() {
return !this.issuer;
}
/**
* @param {Asset} asset Asset to compare
* @returns {boolean} true if this asset equals the given asset.
*/
}, {
key: 'equals',
value: function equals(asset) {
return this.code === asset.getCode() && this.issuer === asset.getIssuer();
}
}, {
key: 'toString',
value: function toString() {
if (this.isNative()) {
return 'native';
}
return this.getCode() + ':' + this.getIssuer();
}
/**
* Compares two assets according to the criteria:
*
* 1. First compare the type (native < alphanum4 < alphanum12).
* 2. If the types are equal, compare the assets codes.
* 3. If the asset codes are equal, compare the issuers.
*
* @param {Asset} assetA - the first asset
* @param {Asset} assetB - the second asset
* @returns {number} `-1` if assetA < assetB, `0` if assetA == assetB, `1` if assetA > assetB.
*
* @static
* @memberof Asset
*/
}], [{
key: 'native',
value: function native() {
return new Asset('XLM');
}
/**
* Returns an asset object from its XDR object representation.
* @param {xdr.Asset} assetXdr - The asset xdr object.
* @returns {Asset}
*/
}, {
key: 'fromOperation',
value: function fromOperation(assetXdr) {
var anum = void 0;
var code = void 0;
var issuer = void 0;
switch (assetXdr.switch()) {
case _xdr2.default.AssetType.assetTypeNative():
return this.native();
case _xdr2.default.AssetType.assetTypeCreditAlphanum4():
anum = assetXdr.alphaNum4();
/* falls through */
case _xdr2.default.AssetType.assetTypeCreditAlphanum12():
anum = anum || assetXdr.alphaNum12();
issuer = _strkey.StrKey.encodeEd25519PublicKey(anum.issuer().ed25519());
code = (0, _trimEnd2.default)(anum.assetCode(), '\0');
return new this(code, issuer);
default:
throw new Error('Invalid asset type: ' + assetXdr.switch().name);
}
}
}, {
key: 'compare',
value: function compare(assetA, assetB) {
if (!assetA || !(assetA instanceof Asset)) {
throw new Error('assetA is invalid');
}
if (!assetB || !(assetB instanceof Asset)) {
throw new Error('assetB is invalid');
}
if (assetA.equals(assetB)) {
return 0;
}
// Compare asset types.
var xdrAtype = assetA.getRawAssetType().value;
var xdrBtype = assetB.getRawAssetType().value;
if (xdrAtype !== xdrBtype) {
return xdrAtype < xdrBtype ? -1 : 1;
}
// Compare asset codes.
var result = asciiCompare(assetA.getCode(), assetB.getCode());
if (result !== 0) {
return result;
}
// Compare asset issuers.
return asciiCompare(assetA.getIssuer(), assetB.getIssuer());
}
}]);
return Asset;
}();
/**
* Compares two ASCII strings in lexographic order with uppercase precedence.
*
* @param {string} a - the first string to compare
* @param {string} b - the second
* @returns {number} like all `compare()`s:
* -1 if `a < b`, 0 if `a == b`, and 1 if `a > b`
*
* @warning No type-checks are done on the parameters
*
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare
*/
function asciiCompare(a, b) {
return a.localeCompare(b, 'en', { caseFirst: 'upper' });
}
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
var baseClone = __webpack_require__(293);
/** Used to compose bitmasks for cloning. */
var CLONE_SYMBOLS_FLAG = 4;
/**
* Creates a shallow clone of `value`.
*
* **Note:** This method is loosely based on the
* [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
* and supports cloning arrays, array buffers, booleans, date objects, maps,
* numbers, `Object` objects, regexes, sets, strings, symbols, and typed
* arrays. The own enumerable properties of `arguments` objects are cloned
* as plain objects. An empty object is returned for uncloneable values such
* as error objects, functions, DOM nodes, and WeakMaps.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to clone.
* @returns {*} Returns the cloned value.
* @see _.cloneDeep
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var shallow = _.clone(objects);
* console.log(shallow[0] === objects[0]);
* // => true
*/
function clone(value) {
return baseClone(value, CLONE_SYMBOLS_FLAG);
}
module.exports = clone;
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.encodeMuxedAccount = exports.extractBaseAddress = exports.encodeMuxedAccountToAddress = exports.decodeAddressToMuxedAccount = exports.SignerKey = exports.StrKey = exports.Networks = exports.Claimant = exports.MuxedAccount = exports.Account = exports.AuthClawbackEnabledFlag = exports.AuthImmutableFlag = exports.AuthRevocableFlag = exports.AuthRequiredFlag = exports.Operation = exports.LiquidityPoolId = exports.LiquidityPoolAsset = exports.Asset = exports.BASE_FEE = exports.TimeoutInfinite = exports.TransactionBuilder = exports.FeeBumpTransaction = exports.Transaction = exports.TransactionBase = exports.Hyper = exports.UnsignedHyper = exports.Keypair = exports.LiquidityPoolFeeV18 = exports.getLiquidityPoolId = exports.FastSigning = exports.verify = exports.sign = exports.hash = exports.xdr = undefined;
var _hashing = __webpack_require__(30);
Object.defineProperty(exports, 'hash', {
enumerable: true,
get: function get() {
return _hashing.hash;
}
});
var _signing = __webpack_require__(102);
Object.defineProperty(exports, 'sign', {
enumerable: true,
get: function get() {
return _signing.sign;
}
});
Object.defineProperty(exports, 'verify', {
enumerable: true,
get: function get() {
return _signing.verify;
}
});
Object.defineProperty(exports, 'FastSigning', {
enumerable: true,
get: function get() {
return _signing.FastSigning;
}
});
var _get_liquidity_pool_id = __webpack_require__(104);
Object.defineProperty(exports, 'getLiquidityPoolId', {
enumerable: true,
get: function get() {
return _get_liquidity_pool_id.getLiquidityPoolId;
}
});
Object.defineProperty(exports, 'LiquidityPoolFeeV18', {
enumerable: true,
get: function get() {
return _get_liquidity_pool_id.LiquidityPoolFeeV18;
}
});
var _keypair = __webpack_require__(19);
Object.defineProperty(exports, 'Keypair', {
enumerable: true,
get: function get() {
return _keypair.Keypair;
}
});
var _jsXdr = __webpack_require__(22);
Object.defineProperty(exports, 'UnsignedHyper', {
enumerable: true,
get: function get() {
return _jsXdr.UnsignedHyper;
}
});
Object.defineProperty(exports, 'Hyper', {
enumerable: true,
get: function get() {
return _jsXdr.Hyper;
}
});
var _transaction_base = __webpack_require__(86);
Object.defineProperty(exports, 'TransactionBase', {
enumerable: true,
get: function get() {
return _transaction_base.TransactionBase;
}
});
var _transaction = __webpack_require__(87);
Object.defineProperty(exports, 'Transaction', {
enumerable: true,
get: function get() {
return _transaction.Transaction;
}
});
var _fee_bump_transaction = __webpack_require__(148);
Object.defineProperty(exports, 'FeeBumpTransaction', {
enumerable: true,
get: function get() {
return _fee_bump_transaction.FeeBumpTransaction;
}
});
var _transaction_builder = __webpack_require__(361);
Object.defineProperty(exports, 'TransactionBuilder', {
enumerable: true,
get: function get() {
return _transaction_builder.TransactionBuilder;
}
});
Object.defineProperty(exports, 'TimeoutInfinite', {
enumerable: true,
get: function get() {
return _transaction_builder.TimeoutInfinite;
}
});
Object.defineProperty(exports, 'BASE_FEE', {
enumerable: true,
get: function get() {
return _transaction_builder.BASE_FEE;
}
});
var _asset = __webpack_require__(27);
Object.defineProperty(exports, 'Asset', {
enumerable: true,
get: function get() {
return _asset.Asset;
}
});
var _liquidity_pool_asset = __webpack_require__(88);
Object.defineProperty(exports, 'LiquidityPoolAsset', {
enumerable: true,
get: function get() {
return _liquidity_pool_asset.LiquidityPoolAsset;
}
});
var _liquidity_pool_id = __webpack_require__(89);
Object.defineProperty(exports, 'LiquidityPoolId', {
enumerable: true,
get: function get() {
return _liquidity_pool_id.LiquidityPoolId;
}
});
var _operation = __webpack_require__(145);
Object.defineProperty(exports, 'Operation', {
enumerable: true,
get: function get() {
return _operation.Operation;
}
});
Object.defineProperty(exports, 'AuthRequiredFlag', {
enumerable: true,
get: function get() {
return _operation.AuthRequiredFlag;
}
});
Object.defineProperty(exports, 'AuthRevocableFlag', {
enumerable: true,
get: function get() {
return _operation.AuthRevocableFlag;
}
});
Object.defineProperty(exports, 'AuthImmutableFlag', {
enumerable: true,
get: function get() {
return _operation.AuthImmutableFlag;
}
});
Object.defineProperty(exports, 'AuthClawbackEnabledFlag', {
enumerable: true,
get: function get() {
return _operation.AuthClawbackEnabledFlag;
}
});
var _memo = __webpack_require__(90);
Object.keys(_memo).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _memo[key];
}
});
});
var _account = __webpack_require__(150);
Object.defineProperty(exports, 'Account', {
enumerable: true,
get: function get() {
return _account.Account;
}
});
var _muxed_account = __webpack_require__(362);
Object.defineProperty(exports, 'MuxedAccount', {
enumerable: true,
get: function get() {
return _muxed_account.MuxedAccount;
}
});
var _claimant = __webpack_require__(146);
Object.defineProperty(exports, 'Claimant', {
enumerable: true,
get: function get() {
return _claimant.Claimant;
}
});
var _network = __webpack_require__(363);
Object.defineProperty(exports, 'Networks', {
enumerable: true,
get: function get() {
return _network.Networks;
}
});
var _strkey = __webpack_require__(8);
Object.defineProperty(exports, 'StrKey', {
enumerable: true,
get: function get() {
return _strkey.StrKey;
}
});
var _signerkey = __webpack_require__(149);
Object.defineProperty(exports, 'SignerKey', {
enumerable: true,
get: function get() {
return _signerkey.SignerKey;
}
});
var _decode_encode_muxed_account = __webpack_require__(17);
Object.defineProperty(exports, 'decodeAddressToMuxedAccount', {
enumerable: true,
get: function get() {
return _decode_encode_muxed_account.decodeAddressToMuxedAccount;
}
});
Object.defineProperty(exports, 'encodeMuxedAccountToAddress', {
enumerable: true,
get: function get() {
return _decode_encode_muxed_account.encodeMuxedAccountToAddress;
}
});
Object.defineProperty(exports, 'extractBaseAddress', {
enumerable: true,
get: function get() {
return _decode_encode_muxed_account.extractBaseAddress;
}
});
Object.defineProperty(exports, 'encodeMuxedAccount', {
enumerable: true,
get: function get() {
return _decode_encode_muxed_account.encodeMuxedAccount;
}
});
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.xdr = _xdr2.default;
exports.default = module.exports;
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.hash = hash;
var _sha = __webpack_require__(190);
function hash(data) {
var hasher = new _sha.sha256();
hasher.update(data, 'utf8');
return hasher.digest();
}
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
var Buffer = __webpack_require__(21).Buffer
// prototype class for hash functions
function Hash (blockSize, finalSize) {
this._block = Buffer.alloc(blockSize)
this._finalSize = finalSize
this._blockSize = blockSize
this._len = 0
}
Hash.prototype.update = function (data, enc) {
if (typeof data === 'string') {
enc = enc || 'utf8'
data = Buffer.from(data, enc)
}
var block = this._block
var blockSize = this._blockSize
var length = data.length
var accum = this._len
for (var offset = 0; offset < length;) {
var assigned = accum % blockSize
var remainder = Math.min(length - offset, blockSize - assigned)
for (var i = 0; i < remainder; i++) {
block[assigned + i] = data[offset + i]
}
accum += remainder
offset += remainder
if ((accum % blockSize) === 0) {
this._update(block)
}
}
this._len += length
return this
}
Hash.prototype.digest = function (enc) {
var rem = this._len % this._blockSize
this._block[rem] = 0x80
// zero (rem + 1) trailing bits, where (rem + 1) is the smallest
// non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
this._block.fill(0, rem + 1)
if (rem >= this._finalSize) {
this._update(this._block)
this._block.fill(0)
}
var bits = this._len * 8
// uint32
if (bits <= 0xffffffff) {
this._block.writeUInt32BE(bits, this._blockSize - 4)
// uint64
} else {
var lowBits = (bits & 0xffffffff) >>> 0
var highBits = (bits - lowBits) / 0x100000000
this._block.writeUInt32BE(highBits, this._blockSize - 8)
this._block.writeUInt32BE(lowBits, this._blockSize - 4)
}
this._update(this._block)
var hash = this._hash()
return enc ? hash.toString(enc) : hash
}
Hash.prototype._update = function () {
throw new Error('_update must be implemented by subclass')
}
module.exports = Hash
/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Int = undefined;
var _isNumber = __webpack_require__(42);
var _isNumber2 = _interopRequireDefault(_isNumber);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Int = exports.Int = {
read: function read(io) {
return io.readInt32BE();
},
write: function write(value, io) {
if (!(0, _isNumber2.default)(value)) {
throw new Error('XDR Write Error: not a number');
}
if (Math.floor(value) !== value) {
throw new Error('XDR Write Error: not an integer');
}
io.writeInt32BE(value);
},
isValid: function isValid(value) {
if (!(0, _isNumber2.default)(value)) {
return false;
}
if (Math.floor(value) !== value) {
return false;
}
return value >= Int.MIN_VALUE && value <= Int.MAX_VALUE;
}
};
Int.MAX_VALUE = Math.pow(2, 31) - 1;
Int.MIN_VALUE = -Math.pow(2, 31);
(0, _ioMixin2.default)(Int);
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
var assignValue = __webpack_require__(106),
baseAssignValue = __webpack_require__(72);
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
baseAssignValue(object, key, newValue);
} else {
assignValue(object, key, newValue);
}
}
return object;
}
module.exports = copyObject;
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
var arrayLikeKeys = __webpack_require__(96),
baseKeys = __webpack_require__(111),
isArrayLike = __webpack_require__(25);
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
module.exports = keys;
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(279);
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AccountRequiresMemoError = exports.InvalidSep10ChallengeError = exports.BadResponseError = exports.BadRequestError = exports.NotFoundError = exports.NetworkError = void 0;
var tslib_1 = __webpack_require__(2);
var NetworkError = (function (_super) {
tslib_1.__extends(NetworkError, _super);
function NetworkError(message, response) {
var _newTarget = this.constructor;
var _this = this;
var trueProto = _newTarget.prototype;
_this = _super.call(this, message) || this;
_this.__proto__ = trueProto;
_this.constructor = NetworkError;
_this.response = response;
return _this;
}
NetworkError.prototype.getResponse = function () {
return this.response;
};
return NetworkError;
}(Error));
exports.NetworkError = NetworkError;
var NotFoundError = (function (_super) {
tslib_1.__extends(NotFoundError, _super);
function NotFoundError(message, response) {
var _newTarget = this.constructor;
var _this = this;
var trueProto = _newTarget.prototype;
_this = _super.call(this, message, response) || this;
_this.__proto__ = trueProto;
_this.constructor = NotFoundError;
_this.name = "NotFoundError";
return _this;
}
return NotFoundError;
}(NetworkError));
exports.NotFoundError = NotFoundError;
var BadRequestError = (function (_super) {
tslib_1.__extends(BadRequestError, _super);
function BadRequestError(message, response) {
var _newTarget = this.constructor;
var _this = this;
var trueProto = _newTarget.prototype;
_this = _super.call(this, message, response) || this;
_this.__proto__ = trueProto;
_this.constructor = BadRequestError;
_this.name = "BadRequestError";
return _this;
}
return BadRequestError;
}(NetworkError));
exports.BadRequestError = BadRequestError;
var BadResponseError = (function (_super) {
tslib_1.__extends(BadResponseError, _super);
function BadResponseError(message, response) {
var _newTarget = this.constructor;
var _this = this;
var trueProto = _newTarget.prototype;
_this = _super.call(this, message, response) || this;
_this.__proto__ = trueProto;
_this.constructor = BadResponseError;
_this.name = "BadResponseError";
return _this;
}
return BadResponseError;
}(NetworkError));
exports.BadResponseError = BadResponseError;
var InvalidSep10ChallengeError = (function (_super) {
tslib_1.__extends(InvalidSep10ChallengeError, _super);
function InvalidSep10ChallengeError(message) {
var _newTarget = this.constructor;
var _this = this;
var trueProto = _newTarget.prototype;
_this = _super.call(this, message) || this;
_this.__proto__ = trueProto;
_this.constructor = InvalidSep10ChallengeError;
_this.name = "InvalidSep10ChallengeError";
return _this;
}
return InvalidSep10ChallengeError;
}(Error));
exports.InvalidSep10ChallengeError = InvalidSep10ChallengeError;
var AccountRequiresMemoError = (function (_super) {
tslib_1.__extends(AccountRequiresMemoError, _super);
function AccountRequiresMemoError(message, accountId, operationIndex) {
var _newTarget = this.constructor;
var _this = this;
var trueProto = _newTarget.prototype;
_this = _super.call(this, message) || this;
_this.__proto__ = trueProto;
_this.constructor = AccountRequiresMemoError;
_this.name = "AccountRequiresMemoError";
_this.accountId = accountId;
_this.operationIndex = operationIndex;
return _this;
}
return AccountRequiresMemoError;
}(Error));
exports.AccountRequiresMemoError = AccountRequiresMemoError;
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* URI.js - Mutating URLs
*
* Version: 1.19.11
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/
(function (root, factory) {
'use strict';
// https://github.com/umdjs/umd/blob/master/returnExports.js
if ( true && module.exports) {
// Node
module.exports = factory(__webpack_require__(153), __webpack_require__(154), __webpack_require__(155));
} else if (true) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(153), __webpack_require__(154), __webpack_require__(155)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}(this, function (punycode, IPv6, SLD, root) {
'use strict';
/*global location, escape, unescape */
// FIXME: v2.0.0 renamce non-camelCase properties to uppercase
/*jshint camelcase: false */
// save current URI variable, if any
var _URI = root && root.URI;
function URI(url, base) {
var _urlSupplied = arguments.length >= 1;
var _baseSupplied = arguments.length >= 2;
// Allow instantiation without the 'new' keyword
if (!(this instanceof URI)) {
if (_urlSupplied) {
if (_baseSupplied) {
return new URI(url, base);
}
return new URI(url);
}
return new URI();
}
if (url === undefined) {
if (_urlSupplied) {
throw new TypeError('undefined is not a valid argument for URI');
}
if (typeof location !== 'undefined') {
url = location.href + '';
} else {
url = '';
}
}
if (url === null) {
if (_urlSupplied) {
throw new TypeError('null is not a valid argument for URI');
}
}
this.href(url);
// resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor
if (base !== undefined) {
return this.absoluteTo(base);
}
return this;
}
function isInteger(value) {
return /^[0-9]+$/.test(value);
}
URI.version = '1.19.11';
var p = URI.prototype;
var hasOwn = Object.prototype.hasOwnProperty;
function escapeRegEx(string) {
// https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963
return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}
function getType(value) {
// IE8 doesn't return [Object Undefined] but [Object Object] for undefined value
if (value === undefined) {
return 'Undefined';
}
return String(Object.prototype.toString.call(value)).slice(8, -1);
}
function isArray(obj) {
return getType(obj) === 'Array';
}
function filterArrayValues(data, value) {
var lookup = {};
var i, length;
if (getType(value) === 'RegExp') {
lookup = null;
} else if (isArray(value)) {
for (i = 0, length = value.length; i < length; i++) {
lookup[value[i]] = true;
}
} else {
lookup[value] = true;
}
for (i = 0, length = data.length; i < length; i++) {
/*jshint laxbreak: true */
var _match = lookup && lookup[data[i]] !== undefined
|| !lookup && value.test(data[i]);
/*jshint laxbreak: false */
if (_match) {
data.splice(i, 1);
length--;
i--;
}
}
return data;
}
function arrayContains(list, value) {
var i, length;
// value may be string, number, array, regexp
if (isArray(value)) {
// Note: this can be optimized to O(n) (instead of current O(m * n))
for (i = 0, length = value.length; i < length; i++) {
if (!arrayContains(list, value[i])) {
return false;
}
}
return true;
}
var _type = getType(value);
for (i = 0, length = list.length; i < length; i++) {
if (_type === 'RegExp') {
if (typeof list[i] === 'string' && list[i].match(value)) {
return true;
}
} else if (list[i] === value) {
return true;
}
}
return false;
}
function arraysEqual(one, two) {
if (!isArray(one) || !isArray(two)) {
return false;
}
// arrays can't be equal if they have different amount of content
if (one.length !== two.length) {
return false;
}
one.sort();
two.sort();
for (var i = 0, l = one.length; i < l; i++) {
if (one[i] !== two[i]) {
return false;
}
}
return true;
}
function trimSlashes(text) {
var trim_expression = /^\/+|\/+$/g;
return text.replace(trim_expression, '');
}
URI._parts = function() {
return {
protocol: null,
username: null,
password: null,
hostname: null,
urn: null,
port: null,
path: null,
query: null,
fragment: null,
// state
preventInvalidHostname: URI.preventInvalidHostname,
duplicateQueryParameters: URI.duplicateQueryParameters,
escapeQuerySpace: URI.escapeQuerySpace
};
};
// state: throw on invalid hostname
// see https://github.com/medialize/URI.js/pull/345
// and https://github.com/medialize/URI.js/issues/354
URI.preventInvalidHostname = false;
// state: allow duplicate query parameters (a=1&a=1)
URI.duplicateQueryParameters = false;
// state: replaces + with %20 (space in query strings)
URI.escapeQuerySpace = true;
// static properties
URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i;
URI.idn_expression = /[^a-z0-9\._-]/i;
URI.punycode_expression = /(xn--)/i;
// well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care?
URI.ip4_expression = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
// credits to Rich Brown
// source: http://forums.intermapper.com/viewtopic.php?p=1096#1096
// specification: http://www.ietf.org/rfc/rfc4291.txt
URI.ip6_expression = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-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-Fa-f]{1,4}:){5}(((:[0-9A-Fa-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-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-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-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-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-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-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-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-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-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-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*$/;
// expression used is "gruber revised" (@gruber v2) determined to be the
// best solution in a regex-golf we did a couple of ages ago at
// * http://mathiasbynens.be/demo/url-regex
// * http://rodneyrehm.de/t/url-regex.html
URI.find_uri_expression = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/ig;
URI.findUri = {
// valid "scheme://" or "www."
start: /\b(?:([a-z][a-z0-9.+-]*:\/\/)|www\.)/gi,
// everything up to the next whitespace
end: /[\s\r\n]|$/,
// trim trailing punctuation captured by end RegExp
trim: /[`!()\[\]{};:'".,<>?«»“”„‘’]+$/,
// balanced parens inclusion (), [], {}, <>
parens: /(\([^\)]*\)|\[[^\]]*\]|\{[^}]*\}|<[^>]*>)/g,
};
URI.leading_whitespace_expression = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
URI.ascii_tab_whitespace = /[\u0009\u000A\u000D]+/g
// http://www.iana.org/assignments/uri-schemes.html
// http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports
URI.defaultPorts = {
http: '80',
https: '443',
ftp: '21',
gopher: '70',
ws: '80',
wss: '443'
};
// list of protocols which always require a hostname
URI.hostProtocols = [
'http',
'https'
];
// allowed hostname characters according to RFC 3986
// ALPHA DIGIT "-" "." "_" "~" "!" "$" "&" "'" "(" ")" "*" "+" "," ";" "=" %encoded
// I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . - _
URI.invalid_hostname_characters = /[^a-zA-Z0-9\.\-:_]/;
// map DOM Elements to their URI attribute
URI.domAttributes = {
'a': 'href',
'blockquote': 'cite',
'link': 'href',
'base': 'href',
'script': 'src',
'form': 'action',
'img': 'src',
'area': 'href',
'iframe': 'src',
'embed': 'src',
'source': 'src',
'track': 'src',
'input': 'src', // but only if type="image"
'audio': 'src',
'video': 'src'
};
URI.getDomAttribute = function(node) {
if (!node || !node.nodeName) {
return undefined;
}
var nodeName = node.nodeName.toLowerCase();
// <input> should only expose src for type="image"
if (nodeName === 'input' && node.type !== 'image') {
return undefined;
}
return URI.domAttributes[nodeName];
};
function escapeForDumbFirefox36(value) {
// https://github.com/medialize/URI.js/issues/91
return escape(value);
}
// encoding / decoding according to RFC3986
function strictEncodeURIComponent(string) {
// see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
return encodeURIComponent(string)
.replace(/[!'()*]/g, escapeForDumbFirefox36)
.replace(/\*/g, '%2A');
}
URI.encode = strictEncodeURIComponent;
URI.decode = decodeURIComponent;
URI.iso8859 = function() {
URI.encode = escape;
URI.decode = unescape;
};
URI.unicode = function() {
URI.encode = strictEncodeURIComponent;
URI.decode = decodeURIComponent;
};
URI.characters = {
pathname: {
encode: {
// RFC3986 2.1: For consistency, URI producers and normalizers should
// use uppercase hexadecimal digits for all percent-encodings.
expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig,
map: {
// -._~!'()*
'%24': '$',
'%26': '&',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '=',
'%3A': ':',
'%40': '@'
}
},
decode: {
expression: /[\/\?#]/g,
map: {
'/': '%2F',
'?': '%3F',
'#': '%23'
}
}
},
reserved: {
encode: {
// RFC3986 2.1: For consistency, URI producers and normalizers should
// use uppercase hexadecimal digits for all percent-encodings.
expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig,
map: {
// gen-delims
'%3A': ':',
'%2F': '/',
'%3F': '?',
'%23': '#',
'%5B': '[',
'%5D': ']',
'%40': '@',
// sub-delims
'%21': '!',
'%24': '$',
'%26': '&',
'%27': '\'',
'%28': '(',
'%29': ')',
'%2A': '*',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '='
}
}
},
urnpath: {
// The characters under `encode` are the characters called out by RFC 2141 as being acceptable
// for usage in a URN. RFC2141 also calls out "-", ".", and "_" as acceptable characters, but
// these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also
// note that the colon character is not featured in the encoding map; this is because URI.js
// gives the colons in URNs semantic meaning as the delimiters of path segements, and so it
// should not appear unencoded in a segment itself.
// See also the note above about RFC3986 and capitalalized hex digits.
encode: {
expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig,
map: {
'%21': '!',
'%24': '$',
'%27': '\'',
'%28': '(',
'%29': ')',
'%2A': '*',
'%2B': '+',
'%2C': ',',
'%3B': ';',
'%3D': '=',
'%40': '@'
}
},
// These characters are the characters called out by RFC2141 as "reserved" characters that
// should never appear in a URN, plus the colon character (see note above).
decode: {
expression: /[\/\?#:]/g,
map: {
'/': '%2F',
'?': '%3F',
'#': '%23',
':': '%3A'
}
}
}
};
URI.encodeQuery = function(string, escapeQuerySpace) {
var escaped = URI.encode(string + '');
if (escapeQuerySpace === undefined) {
escapeQuerySpace = URI.escapeQuerySpace;
}
return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped;
};
URI.decodeQuery = function(string, escapeQuerySpace) {
string += '';
if (escapeQuerySpace === undefined) {
escapeQuerySpace = URI.escapeQuerySpace;
}
try {
return URI.decode(escapeQuerySpace ? string.replace(/\+/g, '%20') : string);
} catch(e) {
// we're not going to mess with weird encodings,
// give up and return the undecoded original string
// see https://github.com/medialize/URI.js/issues/87
// see https://github.com/medialize/URI.js/issues/92
return string;
}
};
// generate encode/decode path functions
var _parts = {'encode':'encode', 'decode':'decode'};
var _part;
var generateAccessor = function(_group, _part) {
return function(string) {
try {
return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function(c) {
return URI.characters[_group][_part].map[c];
});
} catch (e) {
// we're not going to mess with weird encodings,
// give up and return the undecoded original string
// see https://github.com/medialize/URI.js/issues/87
// see https://github.com/medialize/URI.js/issues/92
return string;
}
};
};
for (_part in _parts) {
URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]);
URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]);
}
var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) {
return function(string) {
// Why pass in names of functions, rather than the function objects themselves? The
// definitions of some functions (but in particular, URI.decode) will occasionally change due
// to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure
// that the functions we use here are "fresh".
var actualCodingFunc;
if (!_innerCodingFuncName) {
actualCodingFunc = URI[_codingFuncName];
} else {
actualCodingFunc = function(string) {
return URI[_codingFuncName](URI[_innerCodingFuncName](string));
};
}
var segments = (string + '').split(_sep);
for (var i = 0, length = segments.length; i < length; i++) {
segments[i] = actualCodingFunc(segments[i]);
}
return segments.join(_sep);
};
};
// This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions.
URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment');
URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment');
URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode');
URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode');
URI.encodeReserved = generateAccessor('reserved', 'encode');
URI.parse = function(string, parts) {
var pos;
if (!parts) {
parts = {
preventInvalidHostname: URI.preventInvalidHostname
};
}
string = string.replace(URI.leading_whitespace_expression, '')
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
string = string.replace(URI.ascii_tab_whitespace, '')
// [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment]
// extract fragment
pos = string.indexOf('#');
if (pos > -1) {
// escaping?
parts.fragment = string.substring(pos + 1) || null;
string = string.substring(0, pos);
}
// extract query
pos = string.indexOf('?');
if (pos > -1) {
// escaping?
parts.query = string.substring(pos + 1) || null;
string = string.substring(0, pos);
}
// slashes and backslashes have lost all meaning for the web protocols (https, http, wss, ws)
string = string.replace(/^(https?|ftp|wss?)?:+[/\\]*/i, '$1://');
// slashes and backslashes have lost all meaning for scheme relative URLs
string = string.replace(/^[/\\]{2,}/i, '//');
// extract protocol
if (string.substring(0, 2) === '//') {
// relative-scheme
parts.protocol = null;
string = string.substring(2);
// extract "user:pass@host:port"
string = URI.parseAuthority(string, parts);
} else {
pos = string.indexOf(':');
if (pos > -1) {
parts.protocol = string.substring(0, pos) || null;
if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {
// : may be within the path
parts.protocol = undefined;
} else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') {
string = string.substring(pos + 3);
// extract "user:pass@host:port"
string = URI.parseAuthority(string, parts);
} else {
string = string.substring(pos + 1);
parts.urn = true;
}
}
}
// what's left must be the path
parts.path = string;
// and we're done
return parts;
};
URI.parseHost = function(string, parts) {
if (!string) {
string = '';
}
// Copy chrome, IE, opera backslash-handling behavior.
// Back slashes before the query string get converted to forward slashes
// See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124
// See: https://code.google.com/p/chromium/issues/detail?id=25916
// https://github.com/medialize/URI.js/pull/233
string = string.replace(/\\/g, '/');
// extract host:port
var pos = string.indexOf('/');
var bracketPos;
var t;
if (pos === -1) {
pos = string.length;
}
if (string.charAt(0) === '[') {
// IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6
// I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts
// IPv6+port in the format [2001:db8::1]:80 (for the time being)
bracketPos = string.indexOf(']');
parts.hostname = string.substring(1, bracketPos) || null;
parts.port = string.substring(bracketPos + 2, pos) || null;
if (parts.port === '/') {
parts.port = null;
}
} else {
var firstColon = string.indexOf(':');
var firstSlash = string.indexOf('/');
var nextColon = string.indexOf(':', firstColon + 1);
if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) {
// IPv6 host contains multiple colons - but no port
// this notation is actually not allowed by RFC 3986, but we're a liberal parser
parts.hostname = string.substring(0, pos) || null;
parts.port = null;
} else {
t = string.substring(0, pos).split(':');
parts.hostname = t[0] || null;
parts.port = t[1] || null;
}
}
if (parts.hostname && string.substring(pos).charAt(0) !== '/') {
pos++;
string = '/' + string;
}
if (parts.preventInvalidHostname) {
URI.ensureValidHostname(parts.hostname, parts.protocol);
}
if (parts.port) {
URI.ensureValidPort(parts.port);
}
return string.substring(pos) || '/';
};
URI.parseAuthority = function(string, parts) {
string = URI.parseUserinfo(string, parts);
return URI.parseHost(string, parts);
};
URI.parseUserinfo = function(string, parts) {
// extract username:password
var _string = string
var firstBackSlash = string.indexOf('\\');
if (firstBackSlash !== -1) {
string = string.replace(/\\/g, '/')
}
var firstSlash = string.indexOf('/');
var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1);
var t;
// authority@ must come before /path or \path
if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) {
t = string.substring(0, pos).split(':');
parts.username = t[0] ? URI.decode(t[0]) : null;
t.shift();
parts.password = t[0] ? URI.decode(t.join(':')) : null;
string = _string.substring(pos + 1);
} else {
parts.username = null;
parts.password = null;
}
return string;
};
URI.parseQuery = function(string, escapeQuerySpace) {
if (!string) {
return {};
}
// throw out the funky business - "?"[name"="value"&"]+
string = string.replace(/&+/g, '&').replace(/^\?*&*|&+$/g, '');
if (!string) {
return {};
}
var items = {};
var splits = string.split('&');
var length = splits.length;
var v, name, value;
for (var i = 0; i < length; i++) {
v = splits[i].split('=');
name = URI.decodeQuery(v.shift(), escapeQuerySpace);
// no "=" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters
value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null;
if (name === '__proto__') {
// ignore attempt at exploiting JavaScript internals
continue;
} else if (hasOwn.call(items, name)) {
if (typeof items[name] === 'string' || items[name] === null) {
items[name] = [items[name]];
}
items[name].push(value);
} else {
items[name] = value;
}
}
return items;
};
URI.build = function(parts) {
var t = '';
var requireAbsolutePath = false
if (parts.protocol) {
t += parts.protocol + ':';
}
if (!parts.urn && (t || parts.hostname)) {
t += '//';
requireAbsolutePath = true
}
t += (URI.buildAuthority(parts) || '');
if (typeof parts.path === 'string') {
if (parts.path.charAt(0) !== '/' && requireAbsolutePath) {
t += '/';
}
t += parts.path;
}
if (typeof parts.query === 'string' && parts.query) {
t += '?' + parts.query;
}
if (typeof parts.fragment === 'string' && parts.fragment) {
t += '#' + parts.fragment;
}
return t;
};
URI.buildHost = function(parts) {
var t = '';
if (!parts.hostname) {
return '';
} else if (URI.ip6_expression.test(parts.hostname)) {
t += '[' + parts.hostname + ']';
} else {
t += parts.hostname;
}
if (parts.port) {
t += ':' + parts.port;
}
return t;
};
URI.buildAuthority = function(parts) {
return URI.buildUserinfo(parts) + URI.buildHost(parts);
};
URI.buildUserinfo = function(parts) {
var t = '';
if (parts.username) {
t += URI.encode(parts.username);
}
if (parts.password) {
t += ':' + URI.encode(parts.password);
}
if (t) {
t += '@';
}
return t;
};
URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) {
// according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html
// being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed
// the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax!
// URI.js treats the query string as being application/x-www-form-urlencoded
// see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type
var t = '';
var unique, key, i, length;
for (key in data) {
if (key === '__proto__') {
// ignore attempt at exploiting JavaScript internals
continue;
} else if (hasOwn.call(data, key)) {
if (isArray(data[key])) {
unique = {};
for (i = 0, length = data[key].length; i < length; i++) {
if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) {
t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace);
if (duplicateQueryParameters !== true) {
unique[data[key][i] + ''] = true;
}
}
}
} else if (data[key] !== undefined) {
t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace);
}
}
}
return t.substring(1);
};
URI.buildQueryParameter = function(name, value, escapeQuerySpace) {
// http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded
// don't append "=" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization
return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : '');
};
URI.addQuery = function(data, name, value) {
if (typeof name === 'object') {
for (var key in name) {
if (hasOwn.call(name, key)) {
URI.addQuery(data, key, name[key]);
}
}
} else if (typeof name === 'string') {
if (data[name] === undefined) {
data[name] = value;
return;
} else if (typeof data[name] === 'string') {
data[name] = [data[name]];
}
if (!isArray(value)) {
value = [value];
}
data[name] = (data[name] || []).concat(value);
} else {
throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
}
};
URI.setQuery = function(data, name, value) {
if (typeof name === 'object') {
for (var key in name) {
if (hasOwn.call(name, key)) {
URI.setQuery(data, key, name[key]);
}
}
} else if (typeof name === 'string') {
data[name] = value === undefined ? null : value;
} else {
throw new TypeError('URI.setQuery() accepts an object, string as the name parameter');
}
};
URI.removeQuery = function(data, name, value) {
var i, length, key;
if (isArray(name)) {
for (i = 0, length = name.length; i < length; i++) {
data[name[i]] = undefined;
}
} else if (getType(name) === 'RegExp') {
for (key in data) {
if (name.test(key)) {
data[key] = undefined;
}
}
} else if (typeof name === 'object') {
for (key in name) {
if (hasOwn.call(name, key)) {
URI.removeQuery(data, key, name[key]);
}
}
} else if (typeof name === 'string') {
if (value !== undefined) {
if (getType(value) === 'RegExp') {
if (!isArray(data[name]) && value.test(data[name])) {
data[name] = undefined;
} else {
data[name] = filterArrayValues(data[name], value);
}
} else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) {
data[name] = undefined;
} else if (isArray(data[name])) {
data[name] = filterArrayValues(data[name], value);
}
} else {
data[name] = undefined;
}
} else {
throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter');
}
};
URI.hasQuery = function(data, name, value, withinArray) {
switch (getType(name)) {
case 'String':
// Nothing to do here
break;
case 'RegExp':
for (var key in data) {
if (hasOwn.call(data, key)) {
if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) {
return true;
}
}
}
return false;
case 'Object':
for (var _key in name) {
if (hasOwn.call(name, _key)) {
if (!URI.hasQuery(data, _key, name[_key])) {
return false;
}
}
}
return true;
default:
throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter');
}
switch (getType(value)) {
case 'Undefined':
// true if exists (but may be empty)
return name in data; // data[name] !== undefined;
case 'Boolean':
// true if exists and non-empty
var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]);
return value === _booly;
case 'Function':
// allow complex comparison
return !!value(data[name], name, data);
case 'Array':
if (!isArray(data[name])) {
return false;
}
var op = withinArray ? arrayContains : arraysEqual;
return op(data[name], value);
case 'RegExp':
if (!isArray(data[name])) {
return Boolean(data[name] && data[name].match(value));
}
if (!withinArray) {
return false;
}
return arrayContains(data[name], value);
case 'Number':
value = String(value);
/* falls through */
case 'String':
if (!isArray(data[name])) {
return data[name] === value;
}
if (!withinArray) {
return false;
}
return arrayContains(data[name], value);
default:
throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter');
}
};
URI.joinPaths = function() {
var input = [];
var segments = [];
var nonEmptySegments = 0;
for (var i = 0; i < arguments.length; i++) {
var url = new URI(arguments[i]);
input.push(url);
var _segments = url.segment();
for (var s = 0; s < _segments.length; s++) {
if (typeof _segments[s] === 'string') {
segments.push(_segments[s]);
}
if (_segments[s]) {
nonEmptySegments++;
}
}
}
if (!segments.length || !nonEmptySegments) {
return new URI('');
}
var uri = new URI('').segment(segments);
if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') {
uri.path('/' + uri.path());
}
return uri.normalize();
};
URI.commonPath = function(one, two) {
var length = Math.min(one.length, two.length);
var pos;
// find first non-matching character
for (pos = 0; pos < length; pos++) {
if (one.charAt(pos) !== two.charAt(pos)) {
pos--;
break;
}
}
if (pos < 1) {
return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : '';
}
// revert to last /
if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') {
pos = one.substring(0, pos).lastIndexOf('/');
}
return one.substring(0, pos + 1);
};
URI.withinString = function(string, callback, options) {
options || (options = {});
var _start = options.start || URI.findUri.start;
var _end = options.end || URI.findUri.end;
var _trim = options.trim || URI.findUri.trim;
var _parens = options.parens || URI.findUri.parens;
var _attributeOpen = /[a-z0-9-]=["']?$/i;
_start.lastIndex = 0;
while (true) {
var match = _start.exec(string);
if (!match) {
break;
}
var start = match.index;
if (options.ignoreHtml) {
// attribut(e=["']?$)
var attributeOpen = string.slice(Math.max(start - 3, 0), start);
if (attributeOpen && _attributeOpen.test(attributeOpen)) {
continue;
}
}
var end = start + string.slice(start).search(_end);
var slice = string.slice(start, end);
// make sure we include well balanced parens
var parensEnd = -1;
while (true) {
var parensMatch = _parens.exec(slice);
if (!parensMatch) {
break;
}
var parensMatchEnd = parensMatch.index + parensMatch[0].length;
parensEnd = Math.max(parensEnd, parensMatchEnd);
}
if (parensEnd > -1) {
slice = slice.slice(0, parensEnd) + slice.slice(parensEnd).replace(_trim, '');
} else {
slice = slice.replace(_trim, '');
}
if (slice.length <= match[0].length) {
// the extract only contains the starting marker of a URI,
// e.g. "www" or "http://"
continue;
}
if (options.ignore && options.ignore.test(slice)) {
continue;
}
end = start + slice.length;
var result = callback(slice, start, end, string);
if (result === undefined) {
_start.lastIndex = end;
continue;
}
result = String(result);
string = string.slice(0, start) + result + string.slice(end);
_start.lastIndex = start + result.length;
}
_start.lastIndex = 0;
return string;
};
URI.ensureValidHostname = function(v, protocol) {
// Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986)
// they are not part of DNS and therefore ignored by URI.js
var hasHostname = !!v; // not null and not an empty string
var hasProtocol = !!protocol;
var rejectEmptyHostname = false;
if (hasProtocol) {
rejectEmptyHostname = arrayContains(URI.hostProtocols, protocol);
}
if (rejectEmptyHostname && !hasHostname) {
throw new TypeError('Hostname cannot be empty, if protocol is ' + protocol);
} else if (v && v.match(URI.invalid_hostname_characters)) {
// test punycode
if (!punycode) {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_] and Punycode.js is not available');
}
if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-:_]');
}
}
};
URI.ensureValidPort = function (v) {
if (!v) {
return;
}
var port = Number(v);
if (isInteger(port) && (port > 0) && (port < 65536)) {
return;
}
throw new TypeError('Port "' + v + '" is not a valid port');
};
// noConflict
URI.noConflict = function(removeAll) {
if (removeAll) {
var unconflicted = {
URI: this.noConflict()
};
if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') {
unconflicted.URITemplate = root.URITemplate.noConflict();
}
if (root.IPv6 && typeof root.IPv6.noConflict === 'function') {
unconflicted.IPv6 = root.IPv6.noConflict();
}
if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') {
unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict();
}
return unconflicted;
} else if (root.URI === this) {
root.URI = _URI;
}
return this;
};
p.build = function(deferBuild) {
if (deferBuild === true) {
this._deferred_build = true;
} else if (deferBuild === undefined || this._deferred_build) {
this._string = URI.build(this._parts);
this._deferred_build = false;
}
return this;
};
p.clone = function() {
return new URI(this);
};
p.valueOf = p.toString = function() {
return this.build(false)._string;
};
function generateSimpleAccessor(_part){
return function(v, build) {
if (v === undefined) {
return this._parts[_part] || '';
} else {
this._parts[_part] = v || null;
this.build(!build);
return this;
}
};
}
function generatePrefixAccessor(_part, _key){
return function(v, build) {
if (v === undefined) {
return this._parts[_part] || '';
} else {
if (v !== null) {
v = v + '';
if (v.charAt(0) === _key) {
v = v.substring(1);
}
}
this._parts[_part] = v;
this.build(!build);
return this;
}
};
}
p.protocol = generateSimpleAccessor('protocol');
p.username = generateSimpleAccessor('username');
p.password = generateSimpleAccessor('password');
p.hostname = generateSimpleAccessor('hostname');
p.port = generateSimpleAccessor('port');
p.query = generatePrefixAccessor('query', '?');
p.fragment = generatePrefixAccessor('fragment', '#');
p.search = function(v, build) {
var t = this.query(v, build);
return typeof t === 'string' && t.length ? ('?' + t) : t;
};
p.hash = function(v, build) {
var t = this.fragment(v, build);
return typeof t === 'string' && t.length ? ('#' + t) : t;
};
p.pathname = function(v, build) {
if (v === undefined || v === true) {
var res = this._parts.path || (this._parts.hostname ? '/' : '');
return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res;
} else {
if (this._parts.urn) {
this._parts.path = v ? URI.recodeUrnPath(v) : '';
} else {
this._parts.path = v ? URI.recodePath(v) : '/';
}
this.build(!build);
return this;
}
};
p.path = p.pathname;
p.href = function(href, build) {
var key;
if (href === undefined) {
return this.toString();
}
this._string = '';
this._parts = URI._parts();
var _URI = href instanceof URI;
var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname);
if (href.nodeName) {
var attribute = URI.getDomAttribute(href);
href = href[attribute] || '';
_object = false;
}
// window.location is reported to be an object, but it's not the sort
// of object we're looking for:
// * location.protocol ends with a colon
// * location.query != object.search
// * location.hash != object.fragment
// simply serializing the unknown object should do the trick
// (for location, not for everything...)
if (!_URI && _object && href.pathname !== undefined) {
href = href.toString();
}
if (typeof href === 'string' || href instanceof String) {
this._parts = URI.parse(String(href), this._parts);
} else if (_URI || _object) {
var src = _URI ? href._parts : href;
for (key in src) {
if (key === 'query') { continue; }
if (hasOwn.call(this._parts, key)) {
this._parts[key] = src[key];
}
}
if (src.query) {
this.query(src.query, false);
}
} else {
throw new TypeError('invalid input');
}
this.build(!build);
return this;
};
// identification accessors
p.is = function(what) {
var ip = false;
var ip4 = false;
var ip6 = false;
var name = false;
var sld = false;
var idn = false;
var punycode = false;
var relative = !this._parts.urn;
if (this._parts.hostname) {
relative = false;
ip4 = URI.ip4_expression.test(this._parts.hostname);
ip6 = URI.ip6_expression.test(this._parts.hostname);
ip = ip4 || ip6;
name = !ip;
sld = name && SLD && SLD.has(this._parts.hostname);
idn = name && URI.idn_expression.test(this._parts.hostname);
punycode = name && URI.punycode_expression.test(this._parts.hostname);
}
switch (what.toLowerCase()) {
case 'relative':
return relative;
case 'absolute':
return !relative;
// hostname identification
case 'domain':
case 'name':
return name;
case 'sld':
return sld;
case 'ip':
return ip;
case 'ip4':
case 'ipv4':
case 'inet4':
return ip4;
case 'ip6':
case 'ipv6':
case 'inet6':
return ip6;
case 'idn':
return idn;
case 'url':
return !this._parts.urn;
case 'urn':
return !!this._parts.urn;
case 'punycode':
return punycode;
}
return null;
};
// component specific input validation
var _protocol = p.protocol;
var _port = p.port;
var _hostname = p.hostname;
p.protocol = function(v, build) {
if (v) {
// accept trailing ://
v = v.replace(/:(\/\/)?$/, '');
if (!v.match(URI.protocol_expression)) {
throw new TypeError('Protocol "' + v + '" contains characters other than [A-Z0-9.+-] or doesn\'t start with [A-Z]');
}
}
return _protocol.call(this, v, build);
};
p.scheme = p.protocol;
p.port = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v !== undefined) {
if (v === 0) {
v = null;
}
if (v) {
v += '';
if (v.charAt(0) === ':') {
v = v.substring(1);
}
URI.ensureValidPort(v);
}
}
return _port.call(this, v, build);
};
p.hostname = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v !== undefined) {
var x = { preventInvalidHostname: this._parts.preventInvalidHostname };
var res = URI.parseHost(v, x);
if (res !== '/') {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
}
v = x.hostname;
if (this._parts.preventInvalidHostname) {
URI.ensureValidHostname(v, this._parts.protocol);
}
}
return _hostname.call(this, v, build);
};
// compound accessors
p.origin = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
var protocol = this.protocol();
var authority = this.authority();
if (!authority) {
return '';
}
return (protocol ? protocol + '://' : '') + this.authority();
} else {
var origin = URI(v);
this
.protocol(origin.protocol())
.authority(origin.authority())
.build(!build);
return this;
}
};
p.host = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
return this._parts.hostname ? URI.buildHost(this._parts) : '';
} else {
var res = URI.parseHost(v, this._parts);
if (res !== '/') {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
}
this.build(!build);
return this;
}
};
p.authority = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
return this._parts.hostname ? URI.buildAuthority(this._parts) : '';
} else {
var res = URI.parseAuthority(v, this._parts);
if (res !== '/') {
throw new TypeError('Hostname "' + v + '" contains characters other than [A-Z0-9.-]');
}
this.build(!build);
return this;
}
};
p.userinfo = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined) {
var t = URI.buildUserinfo(this._parts);
return t ? t.substring(0, t.length -1) : t;
} else {
if (v[v.length-1] !== '@') {
v += '@';
}
URI.parseUserinfo(v, this._parts);
this.build(!build);
return this;
}
};
p.resource = function(v, build) {
var parts;
if (v === undefined) {
return this.path() + this.search() + this.hash();
}
parts = URI.parse(v);
this._parts.path = parts.path;
this._parts.query = parts.query;
this._parts.fragment = parts.fragment;
this.build(!build);
return this;
};
// fraction accessors
p.subdomain = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
// convenience, return "www" from "www.example.org"
if (v === undefined) {
if (!this._parts.hostname || this.is('IP')) {
return '';
}
// grab domain and add another segment
var end = this._parts.hostname.length - this.domain().length - 1;
return this._parts.hostname.substring(0, end) || '';
} else {
var e = this._parts.hostname.length - this.domain().length;
var sub = this._parts.hostname.substring(0, e);
var replace = new RegExp('^' + escapeRegEx(sub));
if (v && v.charAt(v.length - 1) !== '.') {
v += '.';
}
if (v.indexOf(':') !== -1) {
throw new TypeError('Domains cannot contain colons');
}
if (v) {
URI.ensureValidHostname(v, this._parts.protocol);
}
this._parts.hostname = this._parts.hostname.replace(replace, v);
this.build(!build);
return this;
}
};
p.domain = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (typeof v === 'boolean') {
build = v;
v = undefined;
}
// convenience, return "example.org" from "www.example.org"
if (v === undefined) {
if (!this._parts.hostname || this.is('IP')) {
return '';
}
// if hostname consists of 1 or 2 segments, it must be the domain
var t = this._parts.hostname.match(/\./g);
if (t && t.length < 2) {
return this._parts.hostname;
}
// grab tld and add another segment
var end = this._parts.hostname.length - this.tld(build).length - 1;
end = this._parts.hostname.lastIndexOf('.', end -1) + 1;
return this._parts.hostname.substring(end) || '';
} else {
if (!v) {
throw new TypeError('cannot set domain empty');
}
if (v.indexOf(':') !== -1) {
throw new TypeError('Domains cannot contain colons');
}
URI.ensureValidHostname(v, this._parts.protocol);
if (!this._parts.hostname || this.is('IP')) {
this._parts.hostname = v;
} else {
var replace = new RegExp(escapeRegEx(this.domain()) + '$');
this._parts.hostname = this._parts.hostname.replace(replace, v);
}
this.build(!build);
return this;
}
};
p.tld = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (typeof v === 'boolean') {
build = v;
v = undefined;
}
// return "org" from "www.example.org"
if (v === undefined) {
if (!this._parts.hostname || this.is('IP')) {
return '';
}
var pos = this._parts.hostname.lastIndexOf('.');
var tld = this._parts.hostname.substring(pos + 1);
if (build !== true && SLD && SLD.list[tld.toLowerCase()]) {
return SLD.get(this._parts.hostname) || tld;
}
return tld;
} else {
var replace;
if (!v) {
throw new TypeError('cannot set TLD empty');
} else if (v.match(/[^a-zA-Z0-9-]/)) {
if (SLD && SLD.is(v)) {
replace = new RegExp(escapeRegEx(this.tld()) + '$');
this._parts.hostname = this._parts.hostname.replace(replace, v);
} else {
throw new TypeError('TLD "' + v + '" contains characters other than [A-Z0-9]');
}
} else if (!this._parts.hostname || this.is('IP')) {
throw new ReferenceError('cannot set TLD on non-domain host');
} else {
replace = new RegExp(escapeRegEx(this.tld()) + '$');
this._parts.hostname = this._parts.hostname.replace(replace, v);
}
this.build(!build);
return this;
}
};
p.directory = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined || v === true) {
if (!this._parts.path && !this._parts.hostname) {
return '';
}
if (this._parts.path === '/') {
return '/';
}
var end = this._parts.path.length - this.filename().length - 1;
var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : '');
return v ? URI.decodePath(res) : res;
} else {
var e = this._parts.path.length - this.filename().length;
var directory = this._parts.path.substring(0, e);
var replace = new RegExp('^' + escapeRegEx(directory));
// fully qualifier directories begin with a slash
if (!this.is('relative')) {
if (!v) {
v = '/';
}
if (v.charAt(0) !== '/') {
v = '/' + v;
}
}
// directories always end with a slash
if (v && v.charAt(v.length - 1) !== '/') {
v += '/';
}
v = URI.recodePath(v);
this._parts.path = this._parts.path.replace(replace, v);
this.build(!build);
return this;
}
};
p.filename = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (typeof v !== 'string') {
if (!this._parts.path || this._parts.path === '/') {
return '';
}
var pos = this._parts.path.lastIndexOf('/');
var res = this._parts.path.substring(pos+1);
return v ? URI.decodePathSegment(res) : res;
} else {
var mutatedDirectory = false;
if (v.charAt(0) === '/') {
v = v.substring(1);
}
if (v.match(/\.?\//)) {
mutatedDirectory = true;
}
var replace = new RegExp(escapeRegEx(this.filename()) + '$');
v = URI.recodePath(v);
this._parts.path = this._parts.path.replace(replace, v);
if (mutatedDirectory) {
this.normalizePath(build);
} else {
this.build(!build);
}
return this;
}
};
p.suffix = function(v, build) {
if (this._parts.urn) {
return v === undefined ? '' : this;
}
if (v === undefined || v === true) {
if (!this._parts.path || this._parts.path === '/') {
return '';
}
var filename = this.filename();
var pos = filename.lastIndexOf('.');
var s, res;
if (pos === -1) {
return '';
}
// suffix may only contain alnum characters (yup, I made this up.)
s = filename.substring(pos+1);
res = (/^[a-z0-9%]+$/i).test(s) ? s : '';
return v ? URI.decodePathSegment(res) : res;
} else {
if (v.charAt(0) === '.') {
v = v.substring(1);
}
var suffix = this.suffix();
var replace;
if (!suffix) {
if (!v) {
return this;
}
this._parts.path += '.' + URI.recodePath(v);
} else if (!v) {
replace = new RegExp(escapeRegEx('.' + suffix) + '$');
} else {
replace = new RegExp(escapeRegEx(suffix) + '$');
}
if (replace) {
v = URI.recodePath(v);
this._parts.path = this._parts.path.replace(replace, v);
}
this.build(!build);
return this;
}
};
p.segment = function(segment, v, build) {
var separator = this._parts.urn ? ':' : '/';
var path = this.path();
var absolute = path.substring(0, 1) === '/';
var segments = path.split(separator);
if (segment !== undefined && typeof segment !== 'number') {
build = v;
v = segment;
segment = undefined;
}
if (segment !== undefined && typeof segment !== 'number') {
throw new Error('Bad segment "' + segment + '", must be 0-based integer');
}
if (absolute) {
segments.shift();
}
if (segment < 0) {
// allow negative indexes to address from the end
segment = Math.max(segments.length + segment, 0);
}
if (v === undefined) {
/*jshint laxbreak: true */
return segment === undefined
? segments
: segments[segment];
/*jshint laxbreak: false */
} else if (segment === null || segments[segment] === undefined) {
if (isArray(v)) {
segments = [];
// collapse empty elements within array
for (var i=0, l=v.length; i < l; i++) {
if (!v[i].length && (!segments.length || !segments[segments.length -1].length)) {
continue;
}
if (segments.length && !segments[segments.length -1].length) {
segments.pop();
}
segments.push(trimSlashes(v[i]));
}
} else if (v || typeof v === 'string') {
v = trimSlashes(v);
if (segments[segments.length -1] === '') {
// empty trailing elements have to be overwritten
// to prevent results such as /foo//bar
segments[segments.length -1] = v;
} else {
segments.push(v);
}
}
} else {
if (v) {
segments[segment] = trimSlashes(v);
} else {
segments.splice(segment, 1);
}
}
if (absolute) {
segments.unshift('');
}
return this.path(segments.join(separator), build);
};
p.segmentCoded = function(segment, v, build) {
var segments, i, l;
if (typeof segment !== 'number') {
build = v;
v = segment;
segment = undefined;
}
if (v === undefined) {
segments = this.segment(segment, v, build);
if (!isArray(segments)) {
segments = segments !== undefined ? URI.decode(segments) : undefined;
} else {
for (i = 0, l = segments.length; i < l; i++) {
segments[i] = URI.decode(segments[i]);
}
}
return segments;
}
if (!isArray(v)) {
v = (typeof v === 'string' || v instanceof String) ? URI.encode(v) : v;
} else {
for (i = 0, l = v.length; i < l; i++) {
v[i] = URI.encode(v[i]);
}
}
return this.segment(segment, v, build);
};
// mutating query string
var q = p.query;
p.query = function(v, build) {
if (v === true) {
return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
} else if (typeof v === 'function') {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
var result = v.call(this, data);
this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
this.build(!build);
return this;
} else if (v !== undefined && typeof v !== 'string') {
this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
this.build(!build);
return this;
} else {
return q.call(this, v, build);
}
};
p.setQuery = function(name, value, build) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
if (typeof name === 'string' || name instanceof String) {
data[name] = value !== undefined ? value : null;
} else if (typeof name === 'object') {
for (var key in name) {
if (hasOwn.call(name, key)) {
data[key] = name[key];
}
}
} else {
throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');
}
this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
if (typeof name !== 'string') {
build = value;
}
this.build(!build);
return this;
};
p.addQuery = function(name, value, build) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
URI.addQuery(data, name, value === undefined ? null : value);
this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
if (typeof name !== 'string') {
build = value;
}
this.build(!build);
return this;
};
p.removeQuery = function(name, value, build) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
URI.removeQuery(data, name, value);
this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);
if (typeof name !== 'string') {
build = value;
}
this.build(!build);
return this;
};
p.hasQuery = function(name, value, withinArray) {
var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);
return URI.hasQuery(data, name, value, withinArray);
};
p.setSearch = p.setQuery;
p.addSearch = p.addQuery;
p.removeSearch = p.removeQuery;
p.hasSearch = p.hasQuery;
// sanitizing URLs
p.normalize = function() {
if (this._parts.urn) {
return this
.normalizeProtocol(false)
.normalizePath(false)
.normalizeQuery(false)
.normalizeFragment(false)
.build();
}
return this
.normalizeProtocol(false)
.normalizeHostname(false)
.normalizePort(false)
.normalizePath(false)
.normalizeQuery(false)
.normalizeFragment(false)
.build();
};
p.normalizeProtocol = function(build) {
if (typeof this._parts.protocol === 'string') {
this._parts.protocol = this._parts.protocol.toLowerCase();
this.build(!build);
}
return this;
};
p.normalizeHostname = function(build) {
if (this._parts.hostname) {
if (this.is('IDN') && punycode) {
this._parts.hostname = punycode.toASCII(this._parts.hostname);
} else if (this.is('IPv6') && IPv6) {
this._parts.hostname = IPv6.best(this._parts.hostname);
}
this._parts.hostname = this._parts.hostname.toLowerCase();
this.build(!build);
}
return this;
};
p.normalizePort = function(build) {
// remove port of it's the protocol's default
if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) {
this._parts.port = null;
this.build(!build);
}
return this;
};
p.normalizePath = function(build) {
var _path = this._parts.path;
if (!_path) {
return this;
}
if (this._parts.urn) {
this._parts.path = URI.recodeUrnPath(this._parts.path);
this.build(!build);
return this;
}
if (this._parts.path === '/') {
return this;
}
_path = URI.recodePath(_path);
var _was_relative;
var _leadingParents = '';
var _parent, _pos;
// handle relative paths
if (_path.charAt(0) !== '/') {
_was_relative = true;
_path = '/' + _path;
}
// handle relative files (as opposed to directories)
if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') {
_path += '/';
}
// resolve simples
_path = _path
.replace(/(\/(\.\/)+)|(\/\.$)/g, '/')
.replace(/\/{2,}/g, '/');
// remember leading parents
if (_was_relative) {
_leadingParents = _path.substring(1).match(/^(\.\.\/)+/) || '';
if (_leadingParents) {
_leadingParents = _leadingParents[0];
}
}
// resolve parents
while (true) {
_parent = _path.search(/\/\.\.(\/|$)/);
if (_parent === -1) {
// no more ../ to resolve
break;
} else if (_parent === 0) {
// top level cannot be relative, skip it
_path = _path.substring(3);
continue;
}
_pos = _path.substring(0, _parent).lastIndexOf('/');
if (_pos === -1) {
_pos = _parent;
}
_path = _path.substring(0, _pos) + _path.substring(_parent + 3);
}
// revert to relative
if (_was_relative && this.is('relative')) {
_path = _leadingParents + _path.substring(1);
}
this._parts.path = _path;
this.build(!build);
return this;
};
p.normalizePathname = p.normalizePath;
p.normalizeQuery = function(build) {
if (typeof this._parts.query === 'string') {
if (!this._parts.query.length) {
this._parts.query = null;
} else {
this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace));
}
this.build(!build);
}
return this;
};
p.normalizeFragment = function(build) {
if (!this._parts.fragment) {
this._parts.fragment = null;
this.build(!build);
}
return this;
};
p.normalizeSearch = p.normalizeQuery;
p.normalizeHash = p.normalizeFragment;
p.iso8859 = function() {
// expect unicode input, iso8859 output
var e = URI.encode;
var d = URI.decode;
URI.encode = escape;
URI.decode = decodeURIComponent;
try {
this.normalize();
} finally {
URI.encode = e;
URI.decode = d;
}
return this;
};
p.unicode = function() {
// expect iso8859 input, unicode output
var e = URI.encode;
var d = URI.decode;
URI.encode = strictEncodeURIComponent;
URI.decode = unescape;
try {
this.normalize();
} finally {
URI.encode = e;
URI.decode = d;
}
return this;
};
p.readable = function() {
var uri = this.clone();
// removing username, password, because they shouldn't be displayed according to RFC 3986
uri.username('').password('').normalize();
var t = '';
if (uri._parts.protocol) {
t += uri._parts.protocol + '://';
}
if (uri._parts.hostname) {
if (uri.is('punycode') && punycode) {
t += punycode.toUnicode(uri._parts.hostname);
if (uri._parts.port) {
t += ':' + uri._parts.port;
}
} else {
t += uri.host();
}
}
if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') {
t += '/';
}
t += uri.path(true);
if (uri._parts.query) {
var q = '';
for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) {
var kv = (qp[i] || '').split('=');
q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace)
.replace(/&/g, '%26');
if (kv[1] !== undefined) {
q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace)
.replace(/&/g, '%26');
}
}
t += '?' + q.substring(1);
}
t += URI.decodeQuery(uri.hash(), true);
return t;
};
// resolving relative and absolute URLs
p.absoluteTo = function(base) {
var resolved = this.clone();
var properties = ['protocol', 'username', 'password', 'hostname', 'port'];
var basedir, i, p;
if (this._parts.urn) {
throw new Error('URNs do not have any generally defined hierarchical components');
}
if (!(base instanceof URI)) {
base = new URI(base);
}
if (resolved._parts.protocol) {
// Directly returns even if this._parts.hostname is empty.
return resolved;
} else {
resolved._parts.protocol = base._parts.protocol;
}
if (this._parts.hostname) {
return resolved;
}
for (i = 0; (p = properties[i]); i++) {
resolved._parts[p] = base._parts[p];
}
if (!resolved._parts.path) {
resolved._parts.path = base._parts.path;
if (!resolved._parts.query) {
resolved._parts.query = base._parts.query;
}
} else {
if (resolved._parts.path.substring(-2) === '..') {
resolved._parts.path += '/';
}
if (resolved.path().charAt(0) !== '/') {
basedir = base.directory();
basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : '';
resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path;
resolved.normalizePath();
}
}
resolved.build();
return resolved;
};
p.relativeTo = function(base) {
var relative = this.clone().normalize();
var relativeParts, baseParts, common, relativePath, basePath;
if (relative._parts.urn) {
throw new Error('URNs do not have any generally defined hierarchical components');
}
base = new URI(base).normalize();
relativeParts = relative._parts;
baseParts = base._parts;
relativePath = relative.path();
basePath = base.path();
if (relativePath.charAt(0) !== '/') {
throw new Error('URI is already relative');
}
if (basePath.charAt(0) !== '/') {
throw new Error('Cannot calculate a URI relative to another relative URI');
}
if (relativeParts.protocol === baseParts.protocol) {
relativeParts.protocol = null;
}
if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) {
return relative.build();
}
if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) {
return relative.build();
}
if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) {
relativeParts.hostname = null;
relativeParts.port = null;
} else {
return relative.build();
}
if (relativePath === basePath) {
relativeParts.path = '';
return relative.build();
}
// determine common sub path
common = URI.commonPath(relativePath, basePath);
// If the paths have nothing in common, return a relative URL with the absolute path.
if (!common) {
return relative.build();
}
var parents = baseParts.path
.substring(common.length)
.replace(/[^\/]*$/, '')
.replace(/.*?\//g, '../');
relativeParts.path = (parents + relativeParts.path.substring(common.length)) || './';
return relative.build();
};
// comparing URIs
p.equals = function(uri) {
var one = this.clone();
var two = new URI(uri);
var one_map = {};
var two_map = {};
var checked = {};
var one_query, two_query, key;
one.normalize();
two.normalize();
// exact match
if (one.toString() === two.toString()) {
return true;
}
// extract query string
one_query = one.query();
two_query = two.query();
one.query('');
two.query('');
// definitely not equal if not even non-query parts match
if (one.toString() !== two.toString()) {
return false;
}
// query parameters have the same length, even if they're permuted
if (one_query.length !== two_query.length) {
return false;
}
one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace);
two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace);
for (key in one_map) {
if (hasOwn.call(one_map, key)) {
if (!isArray(one_map[key])) {
if (one_map[key] !== two_map[key]) {
return false;
}
} else if (!arraysEqual(one_map[key], two_map[key])) {
return false;
}
checked[key] = true;
}
}
for (key in two_map) {
if (hasOwn.call(two_map, key)) {
if (!checked[key]) {
// two contains a parameter not present in one
return false;
}
}
}
return true;
};
// state
p.preventInvalidHostname = function(v) {
this._parts.preventInvalidHostname = !!v;
return this;
};
p.duplicateQueryParameters = function(v) {
this._parts.duplicateQueryParameters = !!v;
return this;
};
p.escapeQuerySpace = function(v) {
this._parts.escapeQuerySpace = !!v;
return this;
};
return URI;
}));
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 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.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
/*<replacement>*/
var pna = __webpack_require__(64);
/*</replacement>*/
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}return keys;
};
/*</replacement>*/
module.exports = Duplex;
/*<replacement>*/
var util = Object.create(__webpack_require__(45));
util.inherits = __webpack_require__(11);
/*</replacement>*/
var Readable = __webpack_require__(169);
var Writable = __webpack_require__(172);
util.inherits(Duplex, Readable);
{
// avoid scope creep, the keys array can then be collected
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
}
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false) this.readable = false;
if (options && options.writable === false) this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
this.once('end', onend);
}
Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function () {
return this._writableState.highWaterMark;
}
});
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
pna.nextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
Object.defineProperty(Duplex.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined || this._writableState === undefined) {
return false;
}
return this._readableState.destroyed && this._writableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (this._readableState === undefined || this._writableState === undefined) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
this._writableState.destroyed = value;
}
});
Duplex.prototype._destroy = function (err, cb) {
this.push(null);
this.end();
pna.nextTick(cb, err);
};
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
var root = __webpack_require__(14);
/** Built-in value references. */
var Symbol = root.Symbol;
module.exports = Symbol;
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(14),
stubFalse = __webpack_require__(186);
/** Detect free variable `exports`. */
var freeExports = true && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
module.exports = isBuffer;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(41)(module)))
/***/ }),
/* 41 */
/***/ (function(module, exports) {
module.exports = function(module) {
if (!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
if (!module.children) module.children = [];
Object.defineProperty(module, "loaded", {
enumerable: true,
get: function() {
return module.l;
}
});
Object.defineProperty(module, "id", {
enumerable: true,
get: function() {
return module.i;
}
});
module.webpackPolyfill = 1;
}
return module;
};
/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(20),
isObjectLike = __webpack_require__(12);
/** `Object#toString` result references. */
var numberTag = '[object Number]';
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike(value) && baseGetTag(value) == numberTag);
}
module.exports = isNumber;
/***/ }),
/* 43 */
/***/ (function(module, exports) {
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
module.exports = eq;
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
var DataView = __webpack_require__(254),
Map = __webpack_require__(75),
Promise = __webpack_require__(255),
Set = __webpack_require__(256),
WeakMap = __webpack_require__(257),
baseGetTag = __webpack_require__(20),
toSource = __webpack_require__(108);
/** `Object#toString` result references. */
var mapTag = '[object Map]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
setTag = '[object Set]',
weakMapTag = '[object WeakMap]';
var dataViewTag = '[object DataView]';
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
module.exports = getTag;
/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(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);
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 46 */
/***/ (function(module, exports) {
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
module.exports = identity;
/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsArguments = __webpack_require__(183),
isObjectLike = __webpack_require__(12);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
module.exports = isArguments;
/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsTypedArray = __webpack_require__(187),
baseUnary = __webpack_require__(70),
nodeUtil = __webpack_require__(71);
/* Node.js helper references. */
var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
module.exports = isTypedArray;
/***/ }),
/* 49 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
return value === proto;
}
module.exports = isPrototype;
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(20),
isObject = __webpack_require__(18);
/** `Object#toString` result references. */
var asyncTag = '[object AsyncFunction]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
proxyTag = '[object Proxy]';
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
module.exports = isFunction;
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.calculatePadding = calculatePadding;
exports.slicePadding = slicePadding;
var _every = __webpack_require__(73);
var _every2 = _interopRequireDefault(_every);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function calculatePadding(length) {
switch (length % 4) {
case 0:
return 0;
case 1:
return 3;
case 2:
return 2;
case 3:
return 1;
default:
return null;
}
}
function slicePadding(io, length) {
var padding = io.slice(length);
var allZero = (0, _every2.default)(padding.buffer(), function (byte) {
return byte === 0;
});
if (allZero !== true) {
throw new Error('XDR Read Error: invalid padding');
}
}
/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(53),
stackClear = __webpack_require__(226),
stackDelete = __webpack_require__(227),
stackGet = __webpack_require__(228),
stackHas = __webpack_require__(229),
stackSet = __webpack_require__(230);
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
module.exports = Stack;
/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {
var listCacheClear = __webpack_require__(221),
listCacheDelete = __webpack_require__(222),
listCacheGet = __webpack_require__(223),
listCacheHas = __webpack_require__(224),
listCacheSet = __webpack_require__(225);
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
module.exports = ListCache;
/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {
var eq = __webpack_require__(43);
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
module.exports = assocIndexOf;
/***/ }),
/* 55 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(26);
/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');
module.exports = nativeCreate;
/***/ }),
/* 56 */
/***/ (function(module, exports, __webpack_require__) {
var isKeyable = __webpack_require__(239);
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
module.exports = getMapData;
/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(20),
isObjectLike = __webpack_require__(12);
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && baseGetTag(value) == symbolTag);
}
module.exports = isSymbol;
/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {
var isSymbol = __webpack_require__(57);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || isSymbol(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = toKey;
/***/ }),
/* 59 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.UnsignedInt = undefined;
var _isNumber = __webpack_require__(42);
var _isNumber2 = _interopRequireDefault(_isNumber);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var UnsignedInt = exports.UnsignedInt = {
read: function read(io) {
return io.readUInt32BE();
},
write: function write(value, io) {
if (!(0, _isNumber2.default)(value)) {
throw new Error('XDR Write Error: not a number');
}
if (Math.floor(value) !== value) {
throw new Error('XDR Write Error: not an integer');
}
if (value < 0) {
throw new Error('XDR Write Error: negative number ' + value);
}
io.writeUInt32BE(value);
},
isValid: function isValid(value) {
if (!(0, _isNumber2.default)(value)) {
return false;
}
if (Math.floor(value) !== value) {
return false;
}
return value >= UnsignedInt.MIN_VALUE && value <= UnsignedInt.MAX_VALUE;
}
};
UnsignedInt.MAX_VALUE = Math.pow(2, 32) - 1;
UnsignedInt.MIN_VALUE = 0;
(0, _ioMixin2.default)(UnsignedInt);
/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Config = void 0;
var tslib_1 = __webpack_require__(2);
var clone_1 = tslib_1.__importDefault(__webpack_require__(28));
var defaultConfig = {
allowHttp: false,
timeout: 0,
};
var config = clone_1.default(defaultConfig);
var Config = (function () {
function Config() {
}
Config.setAllowHttp = function (value) {
config.allowHttp = value;
};
Config.setTimeout = function (value) {
config.timeout = value;
};
Config.isAllowHttp = function () {
return config.allowHttp;
};
Config.getTimeout = function () {
return config.timeout;
};
Config.setDefault = function () {
config = Object.assign({}, defaultConfig);
};
return Config;
}());
exports.Config = Config;
/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(374);
/***/ }),
/* 62 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {
var utils = __webpack_require__(10);
var normalizeHeaderName = __webpack_require__(379);
var enhanceError = __webpack_require__(158);
var DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
function getDefaultAdapter() {
var adapter;
if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = __webpack_require__(159);
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
// For node use HTTP adapter
adapter = __webpack_require__(159);
}
return adapter;
}
function stringifySafely(rawValue, parser, encoder) {
if (utils.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
return utils.trim(rawValue);
} catch (e) {
if (e.name !== 'SyntaxError') {
throw e;
}
}
}
return (encoder || JSON.stringify)(rawValue);
}
var defaults = {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: getDefaultAdapter(),
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName(headers, 'Accept');
normalizeHeaderName(headers, 'Content-Type');
if (utils.isFormData(data) ||
utils.isArrayBuffer(data) ||
utils.isBuffer(data) ||
utils.isStream(data) ||
utils.isFile(data) ||
utils.isBlob(data)
) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
return data.toString();
}
if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) {
setContentTypeIfUnset(headers, 'application/json');
return stringifySafely(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
var transitional = this.transitional || defaults.transitional;
var silentJSONParsing = transitional && transitional.silentJSONParsing;
var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';
if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {
try {
return JSON.parse(data);
} catch (e) {
if (strictJSONParsing) {
if (e.name === 'SyntaxError') {
throw enhanceError(e, this, 'E_JSON_PARSE');
}
throw e;
}
}
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
},
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
}
}
};
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
defaults.headers[method] = {};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});
module.exports = defaults;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(13)))
/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* A `Cancel` is an object that is thrown when an operation is canceled.
*
* @class
* @param {string=} message The message.
*/
function Cancel(message) {
this.message = message;
}
Cancel.prototype.toString = function toString() {
return 'Cancel' + (this.message ? ': ' + this.message : '');
};
Cancel.prototype.__CANCEL__ = true;
module.exports = Cancel;
/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {
if (typeof process === 'undefined' ||
!process.version ||
process.version.indexOf('v0.') === 0 ||
process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
module.exports = { nextTick: nextTick };
} else {
module.exports = process
}
function nextTick(fn, arg1, arg2, arg3) {
if (typeof fn !== 'function') {
throw new TypeError('"callback" argument must be a function');
}
var len = arguments.length;
var args, i;
switch (len) {
case 0:
case 1:
return process.nextTick(fn);
case 2:
return process.nextTick(function afterTickOne() {
fn.call(null, arg1);
});
case 3:
return process.nextTick(function afterTickTwo() {
fn.call(null, arg1, arg2);
});
case 4:
return process.nextTick(function afterTickThree() {
fn.call(null, arg1, arg2, arg3);
});
default:
args = new Array(len - 1);
i = 0;
while (i < args.length) {
args[i++] = arguments[i];
}
return process.nextTick(function afterTick() {
fn.apply(null, args);
});
}
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(13)))
/***/ }),
/* 65 */
/***/ (function(module) {
module.exports = JSON.parse("{\"name\":\"stellar-sdk\",\"version\":\"10.4.1\",\"description\":\"stellar-sdk is a library for working with the Stellar Horizon server.\",\"main\":\"./lib/index.js\",\"types\":\"./lib/index.d.ts\",\"files\":[\"/types\",\"/lib\",\"/dist\"],\"scripts\":{\"prepare\":\"gulp build\",\"test\":\"babel-node ./node_modules/.bin/gulp test\",\"test:watch\":\"babel-node ./node_modules/.bin/gulp test:watch\",\"build:docs\":\"gulp build:docs\",\"docs\":\"yarn build:docs && jsdoc -c .jsdoc.json\",\"preversion\":\"gulp test\",\"version\":\"gulp build\",\"postversion\":\"git push && git push --tags\",\"prettier-all\":\"prettier --write **/*.{js,ts}\"},\"husky\":{\"hooks\":{\"pre-commit\":\"lint-staged\"}},\"prettier\":\"@stellar/prettier-config\",\"lint-staged\":{\"lib/*.{js,json}\":[\"prettier --write\",\"git add\"],\"lib/*.js\":[\"eslint --fix --max-warnings 0\",\"git add\"],\"**/*.ts\":[\"prettier --write\",\"tslint --fix\",\"git add\"]},\"keywords\":[\"stellar\"],\"repository\":{\"type\":\"git\",\"url\":\"https://github.com/stellar/js-stellar-sdk.git\"},\"author\":\"Stellar Development Foundation <hello@stellar.org>\",\"license\":\"Apache-2.0\",\"bugs\":{\"url\":\"https://github.com/stellar/js-stellar-sdk/issues\"},\"homepage\":\"https://github.com/stellar/js-stellar-sdk\",\"devDependencies\":{\"@kollavarsham/gulp-coveralls\":\"0.2.8\",\"@stellar/prettier-config\":\"^1.0.1\",\"@stellar/tsconfig\":\"^1.0.1\",\"@stellar/tslint-config\":\"^1.0.3\",\"@types/detect-node\":\"^2.0.0\",\"@types/lodash\":\"^4.14.130\",\"axios-mock-adapter\":\"^1.16.0\",\"babel-cli\":\"^6.26.0\",\"babel-core\":\"~6.26.3\",\"babel-eslint\":\"^10.0.1\",\"babel-istanbul\":\"^0.12.2\",\"babel-loader\":\"^7.0.0\",\"babel-plugin-transform-builtin-extend\":\"^1.1.2\",\"babel-preset-es2015\":\"^6.24.1\",\"babel-register\":\"^6.26.0\",\"body-parser\":\"^1.12.2\",\"chai\":\"^2.2.0\",\"chai-as-promised\":\"^5.2.0\",\"chai-http\":\"^4.3.0\",\"clear\":\"^0.1.0\",\"coveralls\":\"3.0.2\",\"del\":\"^5.1.0\",\"eslint\":\"^5.12.1\",\"eslint-config-airbnb-base\":\"^13.1.0\",\"eslint-config-prettier\":\"^3.6.0\",\"eslint-plugin-import\":\"^2.15.0\",\"eslint-plugin-node\":\"^8.0.1\",\"eslint-plugin-prefer-import\":\"^0.0.1\",\"eslint-plugin-prettier\":\"^3.0.1\",\"ghooks\":\"^0.3.0\",\"gulp\":\"^4.0.0\",\"gulp-babel\":\"^6.1.3\",\"gulp-eslint\":\"^5.0.0\",\"gulp-insert\":\"^0.5.0\",\"gulp-istanbul\":\"^1.1.3\",\"gulp-load-plugins\":\"1.5.0\",\"gulp-mocha\":\"^7.0.2\",\"gulp-plumber\":\"^1.0.0\",\"gulp-rename\":\"~1.2.0\",\"gulp-tslint\":\"^8.1.4\",\"husky\":\"^1.3.1\",\"isparta\":\"^4.1.1\",\"istanbul\":\"^0.4.5\",\"jsdoc\":\"3.5.5\",\"json-loader\":\"^0.5.1\",\"karma\":\"^6.3.0\",\"karma-chai\":\"^0.1.0\",\"karma-chai-as-promised\":\"^0.1.2\",\"karma-chrome-launcher\":\"^3.1.0\",\"karma-commonjs\":\"^1.0.0\",\"karma-firefox-launcher\":\"^2.1.2\",\"karma-mocha\":\"^2.0.1\",\"karma-phantomjs-launcher\":\"^1.0.4\",\"karma-sauce-launcher\":\"2.0.2\",\"karma-sinon\":\"^1.0.5\",\"karma-sinon-chai\":\"2.0.2\",\"karma-webpack\":\"5.0.0\",\"lint-staged\":\"7.3.0\",\"minami\":\"^1.1.1\",\"mocha\":\"^9.1.4\",\"prettier\":\"^1.17.1\",\"sinon\":\"^1.14.1\",\"sinon-chai\":\"^2.7.0\",\"terser-webpack-plugin\":\"^1.3.0\",\"ts-loader\":\"^5.0.0\",\"tslint\":\"^5.16.0\",\"typescript\":\"^3.4.5\",\"webpack\":\"^4.33.0\",\"webpack-cli\":\"^3.3.3\",\"webpack-stream\":\"^5.2.1\"},\"dependencies\":{\"@types/eventsource\":\"^1.1.2\",\"@types/node\":\">= 8\",\"@types/randombytes\":\"^2.0.0\",\"@types/urijs\":\"^1.19.6\",\"axios\":\"0.25.0\",\"bignumber.js\":\"^4.0.0\",\"detect-node\":\"^2.0.4\",\"es6-promise\":\"^4.2.4\",\"eventsource\":\"^1.1.1\",\"lodash\":\"^4.17.21\",\"randombytes\":\"^2.1.0\",\"stellar-base\":\"^8.2.2\",\"toml\":\"^2.3.0\",\"tslib\":\"^1.10.0\",\"urijs\":\"^1.19.1\",\"utility-types\":\"^3.7.0\"}}");
/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {
var createBaseFor = __webpack_require__(182);
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
module.exports = baseFor;
/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {
var identity = __webpack_require__(46);
/**
* Casts `value` to `identity` if it's not a function.
*
* @private
* @param {*} value The value to inspect.
* @returns {Function} Returns cast function.
*/
function castFunction(value) {
return typeof value == 'function' ? value : identity;
}
module.exports = castFunction;
/***/ }),
/* 68 */
/***/ (function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
var type = typeof value;
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(type == 'number' ||
(type != 'symbol' && reIsUint.test(value))) &&
(value > -1 && value % 1 == 0 && value < length);
}
module.exports = isIndex;
/***/ }),
/* 69 */
/***/ (function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
/***/ }),
/* 70 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
module.exports = baseUnary;
/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(98);
/** Detect free variable `exports`. */
var freeExports = true && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
// Use `util.types` for Node.js 10+.
var types = freeModule && freeModule.require && freeModule.require('util').types;
if (types) {
return types;
}
// Legacy `process.binding('util')` for Node.js < 10.
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
module.exports = nodeUtil;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(41)(module)))
/***/ }),
/* 72 */
/***/ (function(module, exports, __webpack_require__) {
var defineProperty = __webpack_require__(107);
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue(object, key, value) {
if (key == '__proto__' && defineProperty) {
defineProperty(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
module.exports = baseAssignValue;
/***/ }),
/* 73 */
/***/ (function(module, exports, __webpack_require__) {
var arrayEvery = __webpack_require__(214),
baseEvery = __webpack_require__(215),
baseIteratee = __webpack_require__(113),
isArray = __webpack_require__(3),
isIterateeCall = __webpack_require__(110);
/**
* Checks if `predicate` returns truthy for **all** elements of `collection`.
* Iteration is stopped once `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* **Note:** This method returns `true` for
* [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
* [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
* elements of empty collections.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* // => false
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.every(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.every(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.every(users, 'active');
* // => false
*/
function every(collection, predicate, guard) {
var func = isArray(collection) ? arrayEvery : baseEvery;
if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, baseIteratee(predicate, 3));
}
module.exports = every;
/***/ }),
/* 74 */
/***/ (function(module, exports, __webpack_require__) {
var baseForOwn = __webpack_require__(216),
createBaseEach = __webpack_require__(218);
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
module.exports = baseEach;
/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(26),
root = __webpack_require__(14);
/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map');
module.exports = Map;
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
var mapCacheClear = __webpack_require__(231),
mapCacheDelete = __webpack_require__(238),
mapCacheGet = __webpack_require__(240),
mapCacheHas = __webpack_require__(241),
mapCacheSet = __webpack_require__(242);
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
module.exports = MapCache;
/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {
var arrayFilter = __webpack_require__(253),
stubArray = __webpack_require__(120);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
module.exports = getSymbols;
/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {
var isArray = __webpack_require__(3),
isSymbol = __webpack_require__(57);
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/;
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
if (isArray(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
module.exports = isKey;
/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {
var baseToString = __webpack_require__(80);
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
return value == null ? '' : baseToString(value);
}
module.exports = toString;
/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(39),
arrayMap = __webpack_require__(81),
isArray = __webpack_require__(3),
isSymbol = __webpack_require__(57);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString) + '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
module.exports = baseToString;
/***/ }),
/* 81 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
module.exports = arrayMap;
/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Reference = exports.Reference = function () {
function Reference() {
_classCallCheck(this, Reference);
}
_createClass(Reference, [{
key: 'resolve',
/* jshint unused: false */
value: function resolve() {
throw new Error('implement resolve in child class');
}
}]);
return Reference;
}();
/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(112);
/** Built-in value references. */
var getPrototype = overArg(Object.getPrototypeOf, Object);
module.exports = getPrototype;
/***/ }),
/* 84 */
/***/ (function(module, exports, __webpack_require__) {
var Uint8Array = __webpack_require__(116);
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array(result).set(new Uint8Array(arrayBuffer));
return result;
}
module.exports = cloneArrayBuffer;
/***/ }),
/* 85 */
/***/ (function(module, exports) {
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsZWJ = '\\u200d';
/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
/**
* Checks if `string` contains Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a symbol is found, else `false`.
*/
function hasUnicode(string) {
return reHasUnicode.test(string);
}
module.exports = hasUnicode;
/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TransactionBase = undefined;
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; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _hashing = __webpack_require__(30);
var _keypair = __webpack_require__(19);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* @ignore
*/
var TransactionBase = exports.TransactionBase = function () {
function TransactionBase(tx, signatures, fee, networkPassphrase) {
_classCallCheck(this, TransactionBase);
if (typeof networkPassphrase !== 'string') {
throw new Error('Invalid passphrase provided to Transaction: expected a string but got a ' + (typeof networkPassphrase === 'undefined' ? 'undefined' : _typeof(networkPassphrase)));
}
this._networkPassphrase = networkPassphrase;
this._tx = tx;
this._signatures = signatures;
this._fee = fee;
}
/**
* @type {Array.<xdr.DecoratedSignature>}
* @readonly
*/
_createClass(TransactionBase, [{
key: 'sign',
/**
* Signs the transaction with the given {@link Keypair}.
* @param {...Keypair} keypairs Keypairs of signers
* @returns {void}
*/
value: function sign() {
var _this = this;
var txHash = this.hash();
for (var _len = arguments.length, keypairs = Array(_len), _key = 0; _key < _len; _key++) {
keypairs[_key] = arguments[_key];
}
keypairs.forEach(function (kp) {
var sig = kp.signDecorated(txHash);
_this.signatures.push(sig);
});
}
/**
* Signs a transaction with the given {@link Keypair}. Useful if someone sends
* you a transaction XDR for you to sign and return (see
* [addSignature](#addSignature) for more information).
*
* When you get a transaction XDR to sign....
* - Instantiate a `Transaction` object with the XDR
* - Use {@link Keypair} to generate a keypair object for your Stellar seed.
* - Run `getKeypairSignature` with that keypair
* - Send back the signature along with your publicKey (not your secret seed!)
*
* Example:
* ```javascript
* // `transactionXDR` is a string from the person generating the transaction
* const transaction = new Transaction(transactionXDR, networkPassphrase);
* const keypair = Keypair.fromSecret(myStellarSeed);
* return transaction.getKeypairSignature(keypair);
* ```
*
* @param {Keypair} keypair Keypair of signer
* @returns {string} Signature string
*/
}, {
key: 'getKeypairSignature',
value: function getKeypairSignature(keypair) {
return keypair.sign(this.hash()).toString('base64');
}
/**
* Add a signature to the transaction. Useful when a party wants to pre-sign
* a transaction but doesn't want to give access to their secret keys.
* This will also verify whether the signature is valid.
*
* Here's how you would use this feature to solicit multiple signatures.
* - Use `TransactionBuilder` to build a new transaction.
* - Make sure to set a long enough timeout on that transaction to give your
* signers enough time to sign!
* - Once you build the transaction, use `transaction.toXDR()` to get the
* base64-encoded XDR string.
* - _Warning!_ Once you've built this transaction, don't submit any other
* transactions onto your account! Doing so will invalidate this pre-compiled
* transaction!
* - Send this XDR string to your other parties. They can use the instructions
* for [getKeypairSignature](#getKeypairSignature) to sign the transaction.
* - They should send you back their `publicKey` and the `signature` string
* from [getKeypairSignature](#getKeypairSignature), both of which you pass to
* this function.
*
* @param {string} publicKey The public key of the signer
* @param {string} signature The base64 value of the signature XDR
* @returns {void}
*/
}, {
key: 'addSignature',
value: function addSignature() {
var publicKey = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var signature = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
if (!signature || typeof signature !== 'string') {
throw new Error('Invalid signature');
}
if (!publicKey || typeof publicKey !== 'string') {
throw new Error('Invalid publicKey');
}
var keypair = void 0;
var hint = void 0;
var signatureBuffer = Buffer.from(signature, 'base64');
try {
keypair = _keypair.Keypair.fromPublicKey(publicKey);
hint = keypair.signatureHint();
} catch (e) {
throw new Error('Invalid publicKey');
}
if (!keypair.verify(this.hash(), signatureBuffer)) {
throw new Error('Invalid signature');
}
this.signatures.push(new _xdr2.default.DecoratedSignature({
hint: hint,
signature: signatureBuffer
}));
}
/**
* Add a decorated signature directly to the transaction envelope.
*
* @param {xdr.DecoratedSignature} signature raw signature to add
* @returns {void}
*
* @see Keypair.signDecorated
* @see Keypair.signPayloadDecorated
*/
}, {
key: 'addDecoratedSignature',
value: function addDecoratedSignature(signature) {
this.signatures.push(signature);
}
/**
* Add `hashX` signer preimage as signature.
* @param {Buffer|String} preimage Preimage of hash used as signer
* @returns {void}
*/
}, {
key: 'signHashX',
value: function signHashX(preimage) {
if (typeof preimage === 'string') {
preimage = Buffer.from(preimage, 'hex');
}
if (preimage.length > 64) {
throw new Error('preimage cannnot be longer than 64 bytes');
}
var signature = preimage;
var hashX = (0, _hashing.hash)(preimage);
var hint = hashX.slice(hashX.length - 4);
this.signatures.push(new _xdr2.default.DecoratedSignature({ hint: hint, signature: signature }));
}
/**
* Returns a hash for this transaction, suitable for signing.
* @returns {Buffer}
*/
}, {
key: 'hash',
value: function hash() {
return (0, _hashing.hash)(this.signatureBase());
}
}, {
key: 'signatureBase',
value: function signatureBase() {
throw new Error('Implement in subclass');
}
}, {
key: 'toEnvelope',
value: function toEnvelope() {
throw new Error('Implement in subclass');
}
/**
* Get the transaction envelope as a base64-encoded string
* @returns {string} XDR string
*/
}, {
key: 'toXDR',
value: function toXDR() {
return this.toEnvelope().toXDR().toString('base64');
}
}, {
key: 'signatures',
get: function get() {
return this._signatures;
},
set: function set(value) {
throw new Error('Transaction is immutable');
}
}, {
key: 'tx',
get: function get() {
return this._tx;
},
set: function set(value) {
throw new Error('Transaction is immutable');
}
/**
* @type {string}
* @readonly
*/
}, {
key: 'fee',
get: function get() {
return this._fee;
},
set: function set(value) {
throw new Error('Transaction is immutable');
}
/**
* @type {string}
* @readonly
*/
}, {
key: 'networkPassphrase',
get: function get() {
return this._networkPassphrase;
},
set: function set(networkPassphrase) {
this._networkPassphrase = networkPassphrase;
}
}]);
return TransactionBase;
}();
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 87 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Transaction = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _map = __webpack_require__(134);
var _map2 = _interopRequireDefault(_map);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _hashing = __webpack_require__(30);
var _strkey = __webpack_require__(8);
var _operation = __webpack_require__(145);
var _memo = __webpack_require__(90);
var _transaction_base = __webpack_require__(86);
var _decode_encode_muxed_account = __webpack_require__(17);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Use {@link TransactionBuilder} to build a transaction object. If you have an
* object or base64-encoded string of the transaction envelope XDR, use {@link
* TransactionBuilder.fromXDR}.
*
* Once a Transaction has been created, its attributes and operations should not
* be changed. You should only add signatures (using {@link Transaction#sign})
* to a Transaction object before submitting to the network or forwarding on to
* additional signers.
*
* @constructor
*
* @param {string|xdr.TransactionEnvelope} envelope - transaction envelope
* object or base64 encoded string
* @param {string} [networkPassphrase] - passphrase of the target stellar
* network (e.g. "Public Global Stellar Network ; September 2015")
*
* @extends TransactionBase
*/
var Transaction = exports.Transaction = function (_TransactionBase) {
_inherits(Transaction, _TransactionBase);
function Transaction(envelope, networkPassphrase) {
_classCallCheck(this, Transaction);
if (typeof envelope === 'string') {
var buffer = Buffer.from(envelope, 'base64');
envelope = _xdr2.default.TransactionEnvelope.fromXDR(buffer);
}
var envelopeType = envelope.switch();
if (!(envelopeType === _xdr2.default.EnvelopeType.envelopeTypeTxV0() || envelopeType === _xdr2.default.EnvelopeType.envelopeTypeTx())) {
throw new Error('Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ' + envelopeType.name + '.');
}
var txEnvelope = envelope.value();
var tx = txEnvelope.tx();
var fee = tx.fee().toString();
var signatures = (txEnvelope.signatures() || []).slice();
var _this = _possibleConstructorReturn(this, (Transaction.__proto__ || Object.getPrototypeOf(Transaction)).call(this, tx, signatures, fee, networkPassphrase));
_this._envelopeType = envelopeType;
_this._memo = tx.memo();
_this._sequence = tx.seqNum().toString();
switch (_this._envelopeType) {
case _xdr2.default.EnvelopeType.envelopeTypeTxV0():
_this._source = _strkey.StrKey.encodeEd25519PublicKey(_this.tx.sourceAccountEd25519());
break;
default:
_this._source = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(_this.tx.sourceAccount());
break;
}
var cond = null;
var timeBounds = null;
switch (_this._envelopeType) {
case _xdr2.default.EnvelopeType.envelopeTypeTxV0():
timeBounds = tx.timeBounds();
break;
case _xdr2.default.EnvelopeType.envelopeTypeTx():
switch (tx.cond().switch()) {
case _xdr2.default.PreconditionType.precondTime():
timeBounds = tx.cond().timeBounds();
break;
case _xdr2.default.PreconditionType.precondV2():
cond = tx.cond().v2();
timeBounds = cond.timeBounds();
break;
default:
break;
}
break;
default:
break;
}
if (timeBounds) {
_this._timeBounds = {
minTime: timeBounds.minTime().toString(),
maxTime: timeBounds.maxTime().toString()
};
}
if (cond) {
var ledgerBounds = cond.ledgerBounds();
if (ledgerBounds) {
_this._ledgerBounds = {
minLedger: ledgerBounds.minLedger(),
maxLedger: ledgerBounds.maxLedger()
};
}
var minSeq = cond.minSeqNum();
if (minSeq) {
_this._minAccountSequence = minSeq.toString();
}
_this._minAccountSequenceAge = cond.minSeqAge();
_this._minAccountSequenceLedgerGap = cond.minSeqLedgerGap();
_this._extraSigners = cond.extraSigners();
}
var operations = tx.operations() || [];
_this._operations = (0, _map2.default)(operations, function (op) {
return _operation.Operation.fromXDRObject(op);
});
return _this;
}
/**
* @type {object}
* @property {string} 64 bit unix timestamp
* @property {string} 64 bit unix timestamp
* @readonly
*/
_createClass(Transaction, [{
key: 'signatureBase',
/**
* Returns the "signature base" of this transaction, which is the value
* that, when hashed, should be signed to create a signature that
* validators on the Stellar Network will accept.
*
* It is composed of a 4 prefix bytes followed by the xdr-encoded form
* of this transaction.
* @returns {Buffer}
*/
value: function signatureBase() {
var tx = this.tx;
// Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0
// we need a Transaction to generate the signature base
if (this._envelopeType === _xdr2.default.EnvelopeType.envelopeTypeTxV0()) {
tx = _xdr2.default.Transaction.fromXDR(Buffer.concat([
// TransactionV0 is a transaction with the AccountID discriminant
// stripped off, we need to put it back to build a valid transaction
// which we can use to build a TransactionSignaturePayloadTaggedTransaction
_xdr2.default.PublicKeyType.publicKeyTypeEd25519().toXDR(), tx.toXDR()]));
}
var taggedTransaction = new _xdr2.default.TransactionSignaturePayloadTaggedTransaction.envelopeTypeTx(tx);
var txSignature = new _xdr2.default.TransactionSignaturePayload({
networkId: _xdr2.default.Hash.fromXDR((0, _hashing.hash)(this.networkPassphrase)),
taggedTransaction: taggedTransaction
});
return txSignature.toXDR();
}
/**
* To envelope returns a xdr.TransactionEnvelope which can be submitted to the network.
* @returns {xdr.TransactionEnvelope}
*/
}, {
key: 'toEnvelope',
value: function toEnvelope() {
var rawTx = this.tx.toXDR();
var signatures = this.signatures.slice(); // make a copy of the signatures
var envelope = void 0;
switch (this._envelopeType) {
case _xdr2.default.EnvelopeType.envelopeTypeTxV0():
envelope = new _xdr2.default.TransactionEnvelope.envelopeTypeTxV0(new _xdr2.default.TransactionV0Envelope({
tx: _xdr2.default.TransactionV0.fromXDR(rawTx), // make a copy of tx
signatures: signatures
}));
break;
case _xdr2.default.EnvelopeType.envelopeTypeTx():
envelope = new _xdr2.default.TransactionEnvelope.envelopeTypeTx(new _xdr2.default.TransactionV1Envelope({
tx: _xdr2.default.Transaction.fromXDR(rawTx), // make a copy of tx
signatures: signatures
}));
break;
default:
throw new Error('Invalid TransactionEnvelope: expected an envelopeTypeTxV0 or envelopeTypeTx but received an ' + this._envelopeType.name + '.');
}
return envelope;
}
/**
* Calculate the claimable balance ID for an operation within the transaction.
*
* @param {integer} opIndex the index of the CreateClaimableBalance op
* @returns {string} a hex string representing the claimable balance ID
*
* @throws {RangeError} for invalid `opIndex` value
* @throws {TypeError} if op at `opIndex` is not `CreateClaimableBalance`
* @throws for general XDR un/marshalling failures
*
* @see https://github.com/stellar/go/blob/d712346e61e288d450b0c08038c158f8848cc3e4/txnbuild/transaction.go#L392-L435
*
*/
}, {
key: 'getClaimableBalanceId',
value: function getClaimableBalanceId(opIndex) {
// Validate and then extract the operation from the transaction.
if (!Number.isInteger(opIndex) || opIndex < 0 || opIndex >= this.operations.length) {
throw new RangeError('invalid operation index');
}
var op = this.operations[opIndex];
try {
op = _operation.Operation.createClaimableBalance(op);
} catch (err) {
throw new TypeError('expected createClaimableBalance, got ' + op.type + ': ' + err);
}
// Always use the transaction's *unmuxed* source.
var account = _strkey.StrKey.decodeEd25519PublicKey((0, _decode_encode_muxed_account.extractBaseAddress)(this.source));
var operationId = _xdr2.default.HashIdPreimage.envelopeTypeOpId(new _xdr2.default.HashIdPreimageOperationId({
sourceAccount: _xdr2.default.AccountId.publicKeyTypeEd25519(account),
seqNum: _xdr2.default.SequenceNumber.fromString(this.sequence),
opNum: opIndex
}));
var opIdHash = (0, _hashing.hash)(operationId.toXDR('raw'));
var balanceId = _xdr2.default.ClaimableBalanceId.claimableBalanceIdTypeV0(opIdHash);
return balanceId.toXDR('hex');
}
}, {
key: 'timeBounds',
get: function get() {
return this._timeBounds;
},
set: function set(value) {
throw new Error('Transaction is immutable');
}
/**
* @type {object}
* @property {number} minLedger - smallest ledger bound (uint32)
* @property {number} maxLedger - largest ledger bound (or 0 for inf)
* @readonly
*/
}, {
key: 'ledgerBounds',
get: function get() {
return this._ledgerBounds;
},
set: function set(value) {
throw new Error('Transaction is immutable');
}
/**
* @type {string} 64 bit account sequence
* @readonly
*/
}, {
key: 'minAccountSequence',
get: function get() {
return this._minAccountSequence;
},
set: function set(value) {
throw new Error('Transaction is immutable');
}
/**
* @type {number} 64 bit number of seconds
* @readonly
*/
}, {
key: 'minAccountSequenceAge',
get: function get() {
return this._minAccountSequenceAge;
},
set: function set(value) {
throw new Error('Transaction is immutable');
}
/**
* @type {number} 32 bit number of ledgers
* @readonly
*/
}, {
key: 'minAccountSequenceLedgerGap',
get: function get() {
return this._minAccountSequenceLedgerGap;
},
set: function set(value) {
throw new Error('Transaction is immutable');
}
/**
* @type {string[]} array of extra signers (@{link StrKey}s)
* @readonly
*/
}, {
key: 'extraSigners',
get: function get() {
return this._extraSigners;
},
set: function set(value) {
throw new Error('Transaction is immutable');
}
/**
* @type {string}
* @readonly
*/
}, {
key: 'sequence',
get: function get() {
return this._sequence;
},
set: function set(value) {
throw new Error('Transaction is immutable');
}
/**
* @type {string}
* @readonly
*/
}, {
key: 'source',
get: function get() {
return this._source;
},
set: function set(value) {
throw new Error('Transaction is immutable');
}
/**
* @type {Array.<xdr.Operation>}
* @readonly
*/
}, {
key: 'operations',
get: function get() {
return this._operations;
},
set: function set(value) {
throw new Error('Transaction is immutable');
}
/**
* @type {string}
* @readonly
*/
}, {
key: 'memo',
get: function get() {
return _memo.Memo.fromXDRObject(this._memo);
},
set: function set(value) {
throw new Error('Transaction is immutable');
}
}]);
return Transaction;
}(_transaction_base.TransactionBase);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 88 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.LiquidityPoolAsset = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _clone = __webpack_require__(28);
var _clone2 = _interopRequireDefault(_clone);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _asset = __webpack_require__(27);
var _get_liquidity_pool_id = __webpack_require__(104);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* LiquidityPoolAsset class represents a liquidity pool trustline change.
*
* @constructor
* @param {Asset} assetA – The first asset in the Pool, it must respect the rule assetA < assetB. See {@link Asset.compare} for more details on how assets are sorted.
* @param {Asset} assetB – The second asset in the Pool, it must respect the rule assetA < assetB. See {@link Asset.compare} for more details on how assets are sorted.
* @param {number} fee – The liquidity pool fee. For now the only fee supported is `30`.
*/
var LiquidityPoolAsset = exports.LiquidityPoolAsset = function () {
function LiquidityPoolAsset(assetA, assetB, fee) {
_classCallCheck(this, LiquidityPoolAsset);
if (!assetA || !(assetA instanceof _asset.Asset)) {
throw new Error('assetA is invalid');
}
if (!assetB || !(assetB instanceof _asset.Asset)) {
throw new Error('assetB is invalid');
}
if (_asset.Asset.compare(assetA, assetB) !== -1) {
throw new Error('Assets are not in lexicographic order');
}
if (!fee || fee !== _get_liquidity_pool_id.LiquidityPoolFeeV18) {
throw new Error('fee is invalid');
}
this.assetA = assetA;
this.assetB = assetB;
this.fee = fee;
}
/**
* Returns a liquidity pool asset object from its XDR ChangeTrustAsset object
* representation.
* @param {xdr.ChangeTrustAsset} ctAssetXdr - The asset XDR object.
* @returns {LiquidityPoolAsset}
*/
_createClass(LiquidityPoolAsset, [{
key: 'toXDRObject',
/**
* Returns the `xdr.ChangeTrustAsset` object for this liquidity pool asset.
*
* Note: To convert from an {@link Asset `Asset`} to `xdr.ChangeTrustAsset`
* please refer to the
* {@link Asset.toChangeTrustXDRObject `Asset.toChangeTrustXDRObject`} method.
*
* @returns {xdr.ChangeTrustAsset} XDR ChangeTrustAsset object.
*/
value: function toXDRObject() {
var lpConstantProductParamsXdr = new _xdr2.default.LiquidityPoolConstantProductParameters({
assetA: this.assetA.toXDRObject(),
assetB: this.assetB.toXDRObject(),
fee: this.fee
});
var lpParamsXdr = new _xdr2.default.LiquidityPoolParameters('liquidityPoolConstantProduct', lpConstantProductParamsXdr);
return new _xdr2.default.ChangeTrustAsset('assetTypePoolShare', lpParamsXdr);
}
/**
* @returns {LiquidityPoolParameters} Liquidity pool parameters.
*/
}, {
key: 'getLiquidityPoolParameters',
value: function getLiquidityPoolParameters() {
return (0, _clone2.default)({
assetA: this.assetA,
assetB: this.assetB,
fee: this.fee
});
}
/**
* @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/)
* @returns {AssetType.liquidityPoolShares} asset type. Can only be `liquidity_pool_shares`.
*/
}, {
key: 'getAssetType',
value: function getAssetType() {
return 'liquidity_pool_shares';
}
/**
* @param {LiquidityPoolAsset} other the LiquidityPoolAsset to compare
* @returns {boolean} `true` if this asset equals the given asset.
*/
}, {
key: 'equals',
value: function equals(other) {
return this.assetA.equals(other.assetA) && this.assetB.equals(other.assetB) && this.fee === other.fee;
}
}, {
key: 'toString',
value: function toString() {
var poolId = (0, _get_liquidity_pool_id.getLiquidityPoolId)('constant_product', this.getLiquidityPoolParameters()).toString('hex');
return 'liquidity_pool:' + poolId;
}
}], [{
key: 'fromOperation',
value: function fromOperation(ctAssetXdr) {
var assetType = ctAssetXdr.switch();
if (assetType === _xdr2.default.AssetType.assetTypePoolShare()) {
var liquidityPoolParameters = ctAssetXdr.liquidityPool().constantProduct();
return new this(_asset.Asset.fromOperation(liquidityPoolParameters.assetA()), _asset.Asset.fromOperation(liquidityPoolParameters.assetB()), liquidityPoolParameters.fee());
}
throw new Error('Invalid asset type: ' + assetType.name);
}
}]);
return LiquidityPoolAsset;
}();
/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.LiquidityPoolId = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _clone = __webpack_require__(28);
var _clone2 = _interopRequireDefault(_clone);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* LiquidityPoolId class represents the asset referenced by a trustline to a
* liquidity pool.
*
* @constructor
* @param {string} liquidityPoolId - The ID of the liquidity pool in string 'hex'.
*/
var LiquidityPoolId = exports.LiquidityPoolId = function () {
function LiquidityPoolId(liquidityPoolId) {
_classCallCheck(this, LiquidityPoolId);
if (!liquidityPoolId) {
throw new Error('liquidityPoolId cannot be empty');
}
if (!/^[a-f0-9]{64}$/.test(liquidityPoolId)) {
throw new Error('Liquidity pool ID is not a valid hash');
}
this.liquidityPoolId = liquidityPoolId;
}
/**
* Returns a liquidity pool ID object from its xdr.TrustLineAsset representation.
* @param {xdr.TrustLineAsset} tlAssetXdr - The asset XDR object.
* @returns {LiquidityPoolId}
*/
_createClass(LiquidityPoolId, [{
key: 'toXDRObject',
/**
* Returns the `xdr.TrustLineAsset` object for this liquidity pool ID.
*
* Note: To convert from {@link Asset `Asset`} to `xdr.TrustLineAsset` please
* refer to the
* {@link Asset.toTrustLineXDRObject `Asset.toTrustLineXDRObject`} method.
*
* @returns {xdr.TrustLineAsset} XDR LiquidityPoolId object
*/
value: function toXDRObject() {
var xdrPoolId = _xdr2.default.PoolId.fromXDR(this.liquidityPoolId, 'hex');
return new _xdr2.default.TrustLineAsset('assetTypePoolShare', xdrPoolId);
}
/**
* @returns {string} Liquidity pool ID.
*/
}, {
key: 'getLiquidityPoolId',
value: function getLiquidityPoolId() {
return (0, _clone2.default)(this.liquidityPoolId);
}
/**
* @see [Assets concept](https://developers.stellar.org/docs/glossary/assets/)
* @returns {AssetType.liquidityPoolShares} asset type. Can only be `liquidity_pool_shares`.
*/
}, {
key: 'getAssetType',
value: function getAssetType() {
return 'liquidity_pool_shares';
}
/**
* @param {LiquidityPoolId} asset LiquidityPoolId to compare.
* @returns {boolean} `true` if this asset equals the given asset.
*/
}, {
key: 'equals',
value: function equals(asset) {
return this.liquidityPoolId === asset.getLiquidityPoolId();
}
}, {
key: 'toString',
value: function toString() {
return 'liquidity_pool:' + this.liquidityPoolId;
}
}], [{
key: 'fromOperation',
value: function fromOperation(tlAssetXdr) {
var assetType = tlAssetXdr.switch();
if (assetType === _xdr2.default.AssetType.assetTypePoolShare()) {
var liquidityPoolId = tlAssetXdr.liquidityPoolId().toString('hex');
return new this(liquidityPoolId);
}
throw new Error('Invalid asset type: ' + assetType.name);
}
}]);
return LiquidityPoolId;
}();
/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Memo = exports.MemoReturn = exports.MemoHash = exports.MemoText = exports.MemoID = exports.MemoNone = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _isUndefined = __webpack_require__(7);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _isString = __webpack_require__(9);
var _isString2 = _interopRequireDefault(_isString);
var _clone = __webpack_require__(28);
var _clone2 = _interopRequireDefault(_clone);
var _jsXdr = __webpack_require__(22);
var _bignumber = __webpack_require__(23);
var _bignumber2 = _interopRequireDefault(_bignumber);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Type of {@link Memo}.
*/
var MemoNone = exports.MemoNone = 'none';
/**
* Type of {@link Memo}.
*/
var MemoID = exports.MemoID = 'id';
/**
* Type of {@link Memo}.
*/
var MemoText = exports.MemoText = 'text';
/**
* Type of {@link Memo}.
*/
var MemoHash = exports.MemoHash = 'hash';
/**
* Type of {@link Memo}.
*/
var MemoReturn = exports.MemoReturn = 'return';
/**
* `Memo` represents memos attached to transactions.
*
* @param {string} type - `MemoNone`, `MemoID`, `MemoText`, `MemoHash` or `MemoReturn`
* @param {*} value - `string` for `MemoID`, `MemoText`, buffer of hex string for `MemoHash` or `MemoReturn`
* @see [Transactions concept](https://developers.stellar.org/docs/glossary/transactions/)
* @class Memo
*/
var Memo = function () {
function Memo(type) {
var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
_classCallCheck(this, Memo);
this._type = type;
this._value = value;
switch (this._type) {
case MemoNone:
break;
case MemoID:
Memo._validateIdValue(value);
break;
case MemoText:
Memo._validateTextValue(value);
break;
case MemoHash:
case MemoReturn:
Memo._validateHashValue(value);
// We want MemoHash and MemoReturn to have Buffer as a value
if ((0, _isString2.default)(value)) {
this._value = Buffer.from(value, 'hex');
}
break;
default:
throw new Error('Invalid memo type');
}
}
/**
* Contains memo type: `MemoNone`, `MemoID`, `MemoText`, `MemoHash` or `MemoReturn`
*/
_createClass(Memo, [{
key: 'toXDRObject',
/**
* Returns XDR memo object.
* @returns {xdr.Memo}
*/
value: function toXDRObject() {
switch (this._type) {
case MemoNone:
return _xdr2.default.Memo.memoNone();
case MemoID:
return _xdr2.default.Memo.memoId(_jsXdr.UnsignedHyper.fromString(this._value));
case MemoText:
return _xdr2.default.Memo.memoText(this._value);
case MemoHash:
return _xdr2.default.Memo.memoHash(this._value);
case MemoReturn:
return _xdr2.default.Memo.memoReturn(this._value);
default:
return null;
}
}
/**
* Returns {@link Memo} from XDR memo object.
* @param {xdr.Memo} object XDR memo object
* @returns {Memo}
*/
}, {
key: 'type',
get: function get() {
return (0, _clone2.default)(this._type);
},
set: function set(type) {
throw new Error('Memo is immutable');
}
/**
* Contains memo value:
* * `null` for `MemoNone`,
* * `string` for `MemoID`,
* * `Buffer` for `MemoText` after decoding using `fromXDRObject`, original value otherwise,
* * `Buffer` for `MemoHash`, `MemoReturn`.
*/
}, {
key: 'value',
get: function get() {
switch (this._type) {
case MemoNone:
return null;
case MemoID:
case MemoText:
return (0, _clone2.default)(this._value);
case MemoHash:
case MemoReturn:
return Buffer.from(this._value);
default:
throw new Error('Invalid memo type');
}
},
set: function set(value) {
throw new Error('Memo is immutable');
}
}], [{
key: '_validateIdValue',
value: function _validateIdValue(value) {
var error = new Error('Expects a int64 as a string. Got ' + value);
if (!(0, _isString2.default)(value)) {
throw error;
}
var number = void 0;
try {
number = new _bignumber2.default(value);
} catch (e) {
throw error;
}
// Infinity
if (!number.isFinite()) {
throw error;
}
// NaN
if (number.isNaN()) {
throw error;
}
}
}, {
key: '_validateTextValue',
value: function _validateTextValue(value) {
if (!_xdr2.default.Memo.armTypeForArm('text').isValid(value)) {
throw new Error('Expects string, array or buffer, max 28 bytes');
}
}
}, {
key: '_validateHashValue',
value: function _validateHashValue(value) {
var error = new Error('Expects a 32 byte hash value or hex encoded string. Got ' + value);
if (value === null || (0, _isUndefined2.default)(value)) {
throw error;
}
var valueBuffer = void 0;
if ((0, _isString2.default)(value)) {
if (!/^[0-9A-Fa-f]{64}$/g.test(value)) {
throw error;
}
valueBuffer = Buffer.from(value, 'hex');
} else if (Buffer.isBuffer(value)) {
valueBuffer = Buffer.from(value);
} else {
throw error;
}
if (!valueBuffer.length || valueBuffer.length !== 32) {
throw error;
}
}
/**
* Returns an empty memo (`MemoNone`).
* @returns {Memo}
*/
}, {
key: 'none',
value: function none() {
return new Memo(MemoNone);
}
/**
* Creates and returns a `MemoText` memo.
* @param {string} text - memo text
* @returns {Memo}
*/
}, {
key: 'text',
value: function text(_text) {
return new Memo(MemoText, _text);
}
/**
* Creates and returns a `MemoID` memo.
* @param {string} id - 64-bit number represented as a string
* @returns {Memo}
*/
}, {
key: 'id',
value: function id(_id) {
return new Memo(MemoID, _id);
}
/**
* Creates and returns a `MemoHash` memo.
* @param {array|string} hash - 32 byte hash or hex encoded string
* @returns {Memo}
*/
}, {
key: 'hash',
value: function hash(_hash) {
return new Memo(MemoHash, _hash);
}
/**
* Creates and returns a `MemoReturn` memo.
* @param {array|string} hash - 32 byte hash or hex encoded string
* @returns {Memo}
*/
}, {
key: 'return',
value: function _return(hash) {
return new Memo(MemoReturn, hash);
}
}, {
key: 'fromXDRObject',
value: function fromXDRObject(object) {
switch (object.arm()) {
case 'id':
return Memo.id(object.value().toString());
case 'text':
return Memo.text(object.value());
case 'hash':
return Memo.hash(object.value());
case 'retHash':
return Memo.return(object.value());
default:
break;
}
if (typeof object.value() === 'undefined') {
return Memo.none();
}
throw new Error('Unknown type');
}
}]);
return Memo;
}();
exports.Memo = Memo;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 91 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCurrentServerTime = exports.SERVER_TIME_MAP = void 0;
var tslib_1 = __webpack_require__(2);
var axios_1 = tslib_1.__importDefault(__webpack_require__(61));
var urijs_1 = tslib_1.__importDefault(__webpack_require__(37));
var version = __webpack_require__(65).version;
exports.SERVER_TIME_MAP = {};
var HorizonAxiosClient = axios_1.default.create({
headers: {
"X-Client-Name": "js-stellar-sdk",
"X-Client-Version": version,
},
});
function _toSeconds(ms) {
return Math.floor(ms / 1000);
}
HorizonAxiosClient.interceptors.response.use(function interceptorHorizonResponse(response) {
var hostname = urijs_1.default(response.config.url).hostname();
var serverTime = _toSeconds(Date.parse(response.headers.date));
var localTimeRecorded = _toSeconds(new Date().getTime());
if (!isNaN(serverTime)) {
exports.SERVER_TIME_MAP[hostname] = {
serverTime: serverTime,
localTimeRecorded: localTimeRecorded,
};
}
return response;
});
exports.default = HorizonAxiosClient;
function getCurrentServerTime(hostname) {
var entry = exports.SERVER_TIME_MAP[hostname];
if (!entry || !entry.localTimeRecorded || !entry.serverTime) {
return null;
}
var serverTime = entry.serverTime, localTimeRecorded = entry.localTimeRecorded;
var currentTime = _toSeconds(new Date().getTime());
if (currentTime - localTimeRecorded > 60 * 5) {
return null;
}
return currentTime - localTimeRecorded + serverTime;
}
exports.getCurrentServerTime = getCurrentServerTime;
/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 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 punycode = __webpack_require__(395);
var util = __webpack_require__(396);
exports.parse = urlParse;
exports.resolve = urlResolve;
exports.resolveObject = urlResolveObject;
exports.format = urlFormat;
exports.Url = Url;
function Url() {
this.protocol = null;
this.slashes = null;
this.auth = null;
this.host = null;
this.port = null;
this.hostname = null;
this.hash = null;
this.search = null;
this.query = null;
this.pathname = null;
this.path = null;
this.href = null;
}
// Reference: RFC 3986, RFC 1808, RFC 2396
// define these here so at least they only have to be
// compiled once on the first module load.
var protocolPattern = /^([a-z0-9.+-]+:)/i,
portPattern = /:[0-9]*$/,
// Special case for a simple path URL
simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
// RFC 2396: characters reserved for delimiting URLs.
// We actually just auto-escape these.
delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
// RFC 2396: characters not allowed for various reasons.
unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
// Allowed by RFCs, but cause of XSS attacks. Always escape these.
autoEscape = ['\''].concat(unwise),
// Characters that are never ever allowed in a hostname.
// Note that any invalid chars are also handled, but these
// are the ones that are *expected* to be seen, so we fast-path
// them.
nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
hostEndingChars = ['/', '?', '#'],
hostnameMaxLen = 255,
hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
// protocols that can allow "unsafe" and "unwise" chars.
unsafeProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that never have a hostname.
hostlessProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that always contain a // bit.
slashedProtocol = {
'http': true,
'https': true,
'ftp': true,
'gopher': true,
'file': true,
'http:': true,
'https:': true,
'ftp:': true,
'gopher:': true,
'file:': true
},
querystring = __webpack_require__(397);
function urlParse(url, parseQueryString, slashesDenoteHost) {
if (url && util.isObject(url) && url instanceof Url) return url;
var u = new Url;
u.parse(url, parseQueryString, slashesDenoteHost);
return u;
}
Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
if (!util.isString(url)) {
throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
}
// Copy chrome, IE, opera backslash-handling behavior.
// Back slashes before the query string get converted to forward slashes
// See: https://code.google.com/p/chromium/issues/detail?id=25916
var queryIndex = url.indexOf('?'),
splitter =
(queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
uSplit = url.split(splitter),
slashRegex = /\\/g;
uSplit[0] = uSplit[0].replace(slashRegex, '/');
url = uSplit.join(splitter);
var rest = url;
// trim before proceeding.
// This is to support parse stuff like " http://foo.com \n"
rest = rest.trim();
if (!slashesDenoteHost && url.split('#').length === 1) {
// Try fast path regexp
var simplePath = simplePathPattern.exec(rest);
if (simplePath) {
this.path = rest;
this.href = rest;
this.pathname = simplePath[1];
if (simplePath[2]) {
this.search = simplePath[2];
if (parseQueryString) {
this.query = querystring.parse(this.search.substr(1));
} else {
this.query = this.search.substr(1);
}
} else if (parseQueryString) {
this.search = '';
this.query = {};
}
return this;
}
}
var proto = protocolPattern.exec(rest);
if (proto) {
proto = proto[0];
var lowerProto = proto.toLowerCase();
this.protocol = lowerProto;
rest = rest.substr(proto.length);
}
// figure out if it's got a host
// user@server is *always* interpreted as a hostname, and url
// resolution will treat //foo/bar as host=foo,path=bar because that's
// how the browser resolves relative URLs.
if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
var slashes = rest.substr(0, 2) === '//';
if (slashes && !(proto && hostlessProtocol[proto])) {
rest = rest.substr(2);
this.slashes = true;
}
}
if (!hostlessProtocol[proto] &&
(slashes || (proto && !slashedProtocol[proto]))) {
// there's a hostname.
// the first instance of /, ?, ;, or # ends the host.
//
// If there is an @ in the hostname, then non-host chars *are* allowed
// to the left of the last @ sign, unless some host-ending character
// comes *before* the @-sign.
// URLs are obnoxious.
//
// ex:
// http://a@b@c/ => user:a@b host:c
// http://a@b?@c => user:a host:c path:/?@c
// v0.12 TODO(isaacs): This is not quite how Chrome does things.
// Review our test case against browsers more comprehensively.
// find the first instance of any hostEndingChars
var hostEnd = -1;
for (var i = 0; i < hostEndingChars.length; i++) {
var hec = rest.indexOf(hostEndingChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
hostEnd = hec;
}
// at this point, either we have an explicit point where the
// auth portion cannot go past, or the last @ char is the decider.
var auth, atSign;
if (hostEnd === -1) {
// atSign can be anywhere.
atSign = rest.lastIndexOf('@');
} else {
// atSign must be in auth portion.
// http://a@b/c@d => host:b auth:a path:/c@d
atSign = rest.lastIndexOf('@', hostEnd);
}
// Now we have a portion which is definitely the auth.
// Pull that off.
if (atSign !== -1) {
auth = rest.slice(0, atSign);
rest = rest.slice(atSign + 1);
this.auth = decodeURIComponent(auth);
}
// the host is the remaining to the left of the first non-host char
hostEnd = -1;
for (var i = 0; i < nonHostChars.length; i++) {
var hec = rest.indexOf(nonHostChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
hostEnd = hec;
}
// if we still have not hit it, then the entire thing is a host.
if (hostEnd === -1)
hostEnd = rest.length;
this.host = rest.slice(0, hostEnd);
rest = rest.slice(hostEnd);
// pull out port.
this.parseHost();
// we've indicated that there is a hostname,
// so even if it's empty, it has to be present.
this.hostname = this.hostname || '';
// if hostname begins with [ and ends with ]
// assume that it's an IPv6 address.
var ipv6Hostname = this.hostname[0] === '[' &&
this.hostname[this.hostname.length - 1] === ']';
// validate a little.
if (!ipv6Hostname) {
var hostparts = this.hostname.split(/\./);
for (var i = 0, l = hostparts.length; i < l; i++) {
var part = hostparts[i];
if (!part) continue;
if (!part.match(hostnamePartPattern)) {
var newpart = '';
for (var j = 0, k = part.length; j < k; j++) {
if (part.charCodeAt(j) > 127) {
// we replace non-ASCII char with a temporary placeholder
// we need this to make sure size of hostname is not
// broken by replacing non-ASCII by nothing
newpart += 'x';
} else {
newpart += part[j];
}
}
// we test again with ASCII char only
if (!newpart.match(hostnamePartPattern)) {
var validParts = hostparts.slice(0, i);
var notHost = hostparts.slice(i + 1);
var bit = part.match(hostnamePartStart);
if (bit) {
validParts.push(bit[1]);
notHost.unshift(bit[2]);
}
if (notHost.length) {
rest = '/' + notHost.join('.') + rest;
}
this.hostname = validParts.join('.');
break;
}
}
}
}
if (this.hostname.length > hostnameMaxLen) {
this.hostname = '';
} else {
// hostnames are always lower case.
this.hostname = this.hostname.toLowerCase();
}
if (!ipv6Hostname) {
// IDNA Support: Returns a punycoded representation of "domain".
// It only converts parts of the domain name that
// have non-ASCII characters, i.e. it doesn't matter if
// you call it with a domain that already is ASCII-only.
this.hostname = punycode.toASCII(this.hostname);
}
var p = this.port ? ':' + this.port : '';
var h = this.hostname || '';
this.host = h + p;
this.href += this.host;
// strip [ and ] from the hostname
// the host field still retains them, though
if (ipv6Hostname) {
this.hostname = this.hostname.substr(1, this.hostname.length - 2);
if (rest[0] !== '/') {
rest = '/' + rest;
}
}
}
// now rest is set to the post-host stuff.
// chop off any delim chars.
if (!unsafeProtocol[lowerProto]) {
// First, make 100% sure that any "autoEscape" chars get
// escaped, even if encodeURIComponent doesn't think they
// need to be.
for (var i = 0, l = autoEscape.length; i < l; i++) {
var ae = autoEscape[i];
if (rest.indexOf(ae) === -1)
continue;
var esc = encodeURIComponent(ae);
if (esc === ae) {
esc = escape(ae);
}
rest = rest.split(ae).join(esc);
}
}
// chop off from the tail first.
var hash = rest.indexOf('#');
if (hash !== -1) {
// got a fragment string.
this.hash = rest.substr(hash);
rest = rest.slice(0, hash);
}
var qm = rest.indexOf('?');
if (qm !== -1) {
this.search = rest.substr(qm);
this.query = rest.substr(qm + 1);
if (parseQueryString) {
this.query = querystring.parse(this.query);
}
rest = rest.slice(0, qm);
} else if (parseQueryString) {
// no query string, but parseQueryString still requested
this.search = '';
this.query = {};
}
if (rest) this.pathname = rest;
if (slashedProtocol[lowerProto] &&
this.hostname && !this.pathname) {
this.pathname = '/';
}
//to support http.request
if (this.pathname || this.search) {
var p = this.pathname || '';
var s = this.search || '';
this.path = p + s;
}
// finally, reconstruct the href based on what has been validated.
this.href = this.format();
return this;
};
// format a parsed object into a url string
function urlFormat(obj) {
// ensure it's an object, and not a string url.
// If it's an obj, this is a no-op.
// this way, you can call url_format() on strings
// to clean up potentially wonky urls.
if (util.isString(obj)) obj = urlParse(obj);
if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
return obj.format();
}
Url.prototype.format = function() {
var auth = this.auth || '';
if (auth) {
auth = encodeURIComponent(auth);
auth = auth.replace(/%3A/i, ':');
auth += '@';
}
var protocol = this.protocol || '',
pathname = this.pathname || '',
hash = this.hash || '',
host = false,
query = '';
if (this.host) {
host = auth + this.host;
} else if (this.hostname) {
host = auth + (this.hostname.indexOf(':') === -1 ?
this.hostname :
'[' + this.hostname + ']');
if (this.port) {
host += ':' + this.port;
}
}
if (this.query &&
util.isObject(this.query) &&
Object.keys(this.query).length) {
query = querystring.stringify(this.query);
}
var search = this.search || (query && ('?' + query)) || '';
if (protocol && protocol.substr(-1) !== ':') protocol += ':';
// only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
// unless they had them to begin with.
if (this.slashes ||
(!protocol || slashedProtocol[protocol]) && host !== false) {
host = '//' + (host || '');
if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
} else if (!host) {
host = '';
}
if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
if (search && search.charAt(0) !== '?') search = '?' + search;
pathname = pathname.replace(/[?#]/g, function(match) {
return encodeURIComponent(match);
});
search = search.replace('#', '%23');
return protocol + host + pathname + search + hash;
};
function urlResolve(source, relative) {
return urlParse(source, false, true).resolve(relative);
}
Url.prototype.resolve = function(relative) {
return this.resolveObject(urlParse(relative, false, true)).format();
};
function urlResolveObject(source, relative) {
if (!source) return relative;
return urlParse(source, false, true).resolveObject(relative);
}
Url.prototype.resolveObject = function(relative) {
if (util.isString(relative)) {
var rel = new Url();
rel.parse(relative, false, true);
relative = rel;
}
var result = new Url();
var tkeys = Object.keys(this);
for (var tk = 0; tk < tkeys.length; tk++) {
var tkey = tkeys[tk];
result[tkey] = this[tkey];
}
// hash is always overridden, no matter what.
// even href="" will remove it.
result.hash = relative.hash;
// if the relative url is empty, then there's nothing left to do here.
if (relative.href === '') {
result.href = result.format();
return result;
}
// hrefs like //foo/bar always cut to the protocol.
if (relative.slashes && !relative.protocol) {
// take everything except the protocol from relative
var rkeys = Object.keys(relative);
for (var rk = 0; rk < rkeys.length; rk++) {
var rkey = rkeys[rk];
if (rkey !== 'protocol')
result[rkey] = relative[rkey];
}
//urlParse appends trailing / to urls like http://www.example.com
if (slashedProtocol[result.protocol] &&
result.hostname && !result.pathname) {
result.path = result.pathname = '/';
}
result.href = result.format();
return result;
}
if (relative.protocol && relative.protocol !== result.protocol) {
// if it's a known url protocol, then changing
// the protocol does weird things
// first, if it's not file:, then we MUST have a host,
// and if there was a path
// to begin with, then we MUST have a path.
// if it is file:, then the host is dropped,
// because that's known to be hostless.
// anything else is assumed to be absolute.
if (!slashedProtocol[relative.protocol]) {
var keys = Object.keys(relative);
for (var v = 0; v < keys.length; v++) {
var k = keys[v];
result[k] = relative[k];
}
result.href = result.format();
return result;
}
result.protocol = relative.protocol;
if (!relative.host && !hostlessProtocol[relative.protocol]) {
var relPath = (relative.pathname || '').split('/');
while (relPath.length && !(relative.host = relPath.shift()));
if (!relative.host) relative.host = '';
if (!relative.hostname) relative.hostname = '';
if (relPath[0] !== '') relPath.unshift('');
if (relPath.length < 2) relPath.unshift('');
result.pathname = relPath.join('/');
} else {
result.pathname = relative.pathname;
}
result.search = relative.search;
result.query = relative.query;
result.host = relative.host || '';
result.auth = relative.auth;
result.hostname = relative.hostname || relative.host;
result.port = relative.port;
// to support http.request
if (result.pathname || result.search) {
var p = result.pathname || '';
var s = result.search || '';
result.path = p + s;
}
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
}
var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
isRelAbs = (
relative.host ||
relative.pathname && relative.pathname.charAt(0) === '/'
),
mustEndAbs = (isRelAbs || isSourceAbs ||
(result.host && relative.pathname)),
removeAllDots = mustEndAbs,
srcPath = result.pathname && result.pathname.split('/') || [],
relPath = relative.pathname && relative.pathname.split('/') || [],
psychotic = result.protocol && !slashedProtocol[result.protocol];
// if the url is a non-slashed url, then relative
// links like ../.. should be able
// to crawl up to the hostname, as well. This is strange.
// result.protocol has already been set by now.
// Later on, put the first path part into the host field.
if (psychotic) {
result.hostname = '';
result.port = null;
if (result.host) {
if (srcPath[0] === '') srcPath[0] = result.host;
else srcPath.unshift(result.host);
}
result.host = '';
if (relative.protocol) {
relative.hostname = null;
relative.port = null;
if (relative.host) {
if (relPath[0] === '') relPath[0] = relative.host;
else relPath.unshift(relative.host);
}
relative.host = null;
}
mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
}
if (isRelAbs) {
// it's absolute.
result.host = (relative.host || relative.host === '') ?
relative.host : result.host;
result.hostname = (relative.hostname || relative.hostname === '') ?
relative.hostname : result.hostname;
result.search = relative.search;
result.query = relative.query;
srcPath = relPath;
// fall through to the dot-handling below.
} else if (relPath.length) {
// it's relative
// throw away the existing file, and take the new path instead.
if (!srcPath) srcPath = [];
srcPath.pop();
srcPath = srcPath.concat(relPath);
result.search = relative.search;
result.query = relative.query;
} else if (!util.isNullOrUndefined(relative.search)) {
// just pull out the search.
// like href='?foo'.
// Put this after the other two cases because it simplifies the booleans
if (psychotic) {
result.hostname = result.host = srcPath.shift();
//occationaly the auth can get stuck only in host
//this especially happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ?
result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
result.search = relative.search;
result.query = relative.query;
//to support http.request
if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.href = result.format();
return result;
}
if (!srcPath.length) {
// no path at all. easy.
// we've already handled the other stuff above.
result.pathname = null;
//to support http.request
if (result.search) {
result.path = '/' + result.search;
} else {
result.path = null;
}
result.href = result.format();
return result;
}
// if a url ENDs in . or .., then it must get a trailing slash.
// however, if it ends in anything else non-slashy,
// then it must NOT get a trailing slash.
var last = srcPath.slice(-1)[0];
var hasTrailingSlash = (
(result.host || relative.host || srcPath.length > 1) &&
(last === '.' || last === '..') || last === '');
// strip single dots, resolve double dots to parent dir
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = srcPath.length; i >= 0; i--) {
last = srcPath[i];
if (last === '.') {
srcPath.splice(i, 1);
} else if (last === '..') {
srcPath.splice(i, 1);
up++;
} else if (up) {
srcPath.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (!mustEndAbs && !removeAllDots) {
for (; up--; up) {
srcPath.unshift('..');
}
}
if (mustEndAbs && srcPath[0] !== '' &&
(!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
srcPath.unshift('');
}
if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
srcPath.push('');
}
var isAbsolute = srcPath[0] === '' ||
(srcPath[0] && srcPath[0].charAt(0) === '/');
// put the host back
if (psychotic) {
result.hostname = result.host = isAbsolute ? '' :
srcPath.length ? srcPath.shift() : '';
//occationaly the auth can get stuck only in host
//this especially happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ?
result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
mustEndAbs = mustEndAbs || (result.host && srcPath.length);
if (mustEndAbs && !isAbsolute) {
srcPath.unshift('');
}
if (!srcPath.length) {
result.pathname = null;
result.path = null;
} else {
result.pathname = srcPath.join('/');
}
//to support request.http
if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.auth = relative.auth || result.auth;
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
};
Url.prototype.parseHost = function() {
var host = this.host;
var port = portPattern.exec(host);
if (port) {
port = port[0];
if (port !== ':') {
this.port = port.substr(1);
}
host = host.substr(0, host.length - port.length);
}
if (host) this.hostname = host;
};
/***/ }),
/* 93 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 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 R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
module.exports = EventEmitter;
module.exports.once = once;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err; // Unhandled 'error' event
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
// not listening for removeListener, no need to emit
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function (resolve, reject) {
function eventListener() {
if (errorListener !== undefined) {
emitter.removeListener('error', errorListener);
}
resolve([].slice.call(arguments));
};
var errorListener;
// Adding an error listener is not optional because
// if an error is thrown on an event emitter we cannot
// guarantee that the actual event we are waiting will
// be fired. The result could be a silent way to create
// memory or file descriptor leaks, which is something
// we should avoid.
if (name !== 'error') {
errorListener = function errorListener(err) {
emitter.removeListener(name, eventListener);
reject(err);
};
emitter.once('error', errorListener);
}
emitter.once(name, eventListener);
});
}
/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {
/* eslint-disable node/no-deprecated-api */
var buffer = __webpack_require__(1)
var Buffer = buffer.Buffer
// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
for (var key in src) {
dst[key] = src[key]
}
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
module.exports = buffer
} else {
// Copy properties from require('buffer')
copyProps(buffer, exports)
exports.Buffer = SafeBuffer
}
function SafeBuffer (arg, encodingOrOffset, length) {
return Buffer(arg, encodingOrOffset, length)
}
// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)
SafeBuffer.from = function (arg, encodingOrOffset, length) {
if (typeof arg === 'number') {
throw new TypeError('Argument must not be a number')
}
return Buffer(arg, encodingOrOffset, length)
}
SafeBuffer.alloc = function (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
var buf = Buffer(size)
if (fill !== undefined) {
if (typeof encoding === 'string') {
buf.fill(fill, encoding)
} else {
buf.fill(fill)
}
} else {
buf.fill(0)
}
return buf
}
SafeBuffer.allocUnsafe = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return Buffer(size)
}
SafeBuffer.allocUnsafeSlow = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return buffer.SlowBuffer(size)
}
/***/ }),
/* 95 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AccountResponse = void 0;
var tslib_1 = __webpack_require__(2);
var forIn_1 = tslib_1.__importDefault(__webpack_require__(181));
var stellar_base_1 = __webpack_require__(29);
var AccountResponse = (function () {
function AccountResponse(response) {
var _this = this;
this._baseAccount = new stellar_base_1.Account(response.account_id, response.sequence);
forIn_1.default(response, function (value, key) {
_this[key] = value;
});
}
AccountResponse.prototype.accountId = function () {
return this._baseAccount.accountId();
};
AccountResponse.prototype.sequenceNumber = function () {
return this._baseAccount.sequenceNumber();
};
AccountResponse.prototype.incrementSequenceNumber = function () {
this._baseAccount.incrementSequenceNumber();
this.sequence = this._baseAccount.sequenceNumber();
};
return AccountResponse;
}());
exports.AccountResponse = AccountResponse;
/***/ }),
/* 96 */
/***/ (function(module, exports, __webpack_require__) {
var baseTimes = __webpack_require__(97),
isArguments = __webpack_require__(47),
isArray = __webpack_require__(3),
isBuffer = __webpack_require__(40),
isIndex = __webpack_require__(68),
isTypedArray = __webpack_require__(48);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
module.exports = arrayLikeKeys;
/***/ }),
/* 97 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
module.exports = baseTimes;
/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
module.exports = freeGlobal;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5)))
/***/ }),
/* 99 */
/***/ (function(module, exports) {
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
/***/ }),
/* 100 */
/***/ (function(module, exports, __webpack_require__) {
/**
* A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
* in FIPS 180-2
* Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
*
*/
var inherits = __webpack_require__(11)
var Hash = __webpack_require__(31)
var Buffer = __webpack_require__(21).Buffer
var K = [
0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
]
var W = new Array(64)
function Sha256 () {
this.init()
this._w = W // new Array(64)
Hash.call(this, 64, 56)
}
inherits(Sha256, Hash)
Sha256.prototype.init = function () {
this._a = 0x6a09e667
this._b = 0xbb67ae85
this._c = 0x3c6ef372
this._d = 0xa54ff53a
this._e = 0x510e527f
this._f = 0x9b05688c
this._g = 0x1f83d9ab
this._h = 0x5be0cd19
return this
}
function ch (x, y, z) {
return z ^ (x & (y ^ z))
}
function maj (x, y, z) {
return (x & y) | (z & (x | y))
}
function sigma0 (x) {
return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
}
function sigma1 (x) {
return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
}
function gamma0 (x) {
return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
}
function gamma1 (x) {
return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
}
Sha256.prototype._update = function (M) {
var W = this._w
var a = this._a | 0
var b = this._b | 0
var c = this._c | 0
var d = this._d | 0
var e = this._e | 0
var f = this._f | 0
var g = this._g | 0
var h = this._h | 0
for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
for (var j = 0; j < 64; ++j) {
var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
var T2 = (sigma0(a) + maj(a, b, c)) | 0
h = g
g = f
f = e
e = (d + T1) | 0
d = c
c = b
b = a
a = (T1 + T2) | 0
}
this._a = (a + this._a) | 0
this._b = (b + this._b) | 0
this._c = (c + this._c) | 0
this._d = (d + this._d) | 0
this._e = (e + this._e) | 0
this._f = (f + this._f) | 0
this._g = (g + this._g) | 0
this._h = (h + this._h) | 0
}
Sha256.prototype._hash = function () {
var H = Buffer.allocUnsafe(32)
H.writeInt32BE(this._a, 0)
H.writeInt32BE(this._b, 4)
H.writeInt32BE(this._c, 8)
H.writeInt32BE(this._d, 12)
H.writeInt32BE(this._e, 16)
H.writeInt32BE(this._f, 20)
H.writeInt32BE(this._g, 24)
H.writeInt32BE(this._h, 28)
return H
}
module.exports = Sha256
/***/ }),
/* 101 */
/***/ (function(module, exports, __webpack_require__) {
var inherits = __webpack_require__(11)
var Hash = __webpack_require__(31)
var Buffer = __webpack_require__(21).Buffer
var K = [
0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
]
var W = new Array(160)
function Sha512 () {
this.init()
this._w = W
Hash.call(this, 128, 112)
}
inherits(Sha512, Hash)
Sha512.prototype.init = function () {
this._ah = 0x6a09e667
this._bh = 0xbb67ae85
this._ch = 0x3c6ef372
this._dh = 0xa54ff53a
this._eh = 0x510e527f
this._fh = 0x9b05688c
this._gh = 0x1f83d9ab
this._hh = 0x5be0cd19
this._al = 0xf3bcc908
this._bl = 0x84caa73b
this._cl = 0xfe94f82b
this._dl = 0x5f1d36f1
this._el = 0xade682d1
this._fl = 0x2b3e6c1f
this._gl = 0xfb41bd6b
this._hl = 0x137e2179
return this
}
function Ch (x, y, z) {
return z ^ (x & (y ^ z))
}
function maj (x, y, z) {
return (x & y) | (z & (x | y))
}
function sigma0 (x, xl) {
return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
}
function sigma1 (x, xl) {
return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
}
function Gamma0 (x, xl) {
return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
}
function Gamma0l (x, xl) {
return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
}
function Gamma1 (x, xl) {
return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
}
function Gamma1l (x, xl) {
return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
}
function getCarry (a, b) {
return (a >>> 0) < (b >>> 0) ? 1 : 0
}
Sha512.prototype._update = function (M) {
var W = this._w
var ah = this._ah | 0
var bh = this._bh | 0
var ch = this._ch | 0
var dh = this._dh | 0
var eh = this._eh | 0
var fh = this._fh | 0
var gh = this._gh | 0
var hh = this._hh | 0
var al = this._al | 0
var bl = this._bl | 0
var cl = this._cl | 0
var dl = this._dl | 0
var el = this._el | 0
var fl = this._fl | 0
var gl = this._gl | 0
var hl = this._hl | 0
for (var i = 0; i < 32; i += 2) {
W[i] = M.readInt32BE(i * 4)
W[i + 1] = M.readInt32BE(i * 4 + 4)
}
for (; i < 160; i += 2) {
var xh = W[i - 15 * 2]
var xl = W[i - 15 * 2 + 1]
var gamma0 = Gamma0(xh, xl)
var gamma0l = Gamma0l(xl, xh)
xh = W[i - 2 * 2]
xl = W[i - 2 * 2 + 1]
var gamma1 = Gamma1(xh, xl)
var gamma1l = Gamma1l(xl, xh)
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7h = W[i - 7 * 2]
var Wi7l = W[i - 7 * 2 + 1]
var Wi16h = W[i - 16 * 2]
var Wi16l = W[i - 16 * 2 + 1]
var Wil = (gamma0l + Wi7l) | 0
var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
Wil = (Wil + gamma1l) | 0
Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
Wil = (Wil + Wi16l) | 0
Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
W[i] = Wih
W[i + 1] = Wil
}
for (var j = 0; j < 160; j += 2) {
Wih = W[j]
Wil = W[j + 1]
var majh = maj(ah, bh, ch)
var majl = maj(al, bl, cl)
var sigma0h = sigma0(ah, al)
var sigma0l = sigma0(al, ah)
var sigma1h = sigma1(eh, el)
var sigma1l = sigma1(el, eh)
// t1 = h + sigma1 + ch + K[j] + W[j]
var Kih = K[j]
var Kil = K[j + 1]
var chh = Ch(eh, fh, gh)
var chl = Ch(el, fl, gl)
var t1l = (hl + sigma1l) | 0
var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
t1l = (t1l + chl) | 0
t1h = (t1h + chh + getCarry(t1l, chl)) | 0
t1l = (t1l + Kil) | 0
t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
t1l = (t1l + Wil) | 0
t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
// t2 = sigma0 + maj
var t2l = (sigma0l + majl) | 0
var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
hh = gh
hl = gl
gh = fh
gl = fl
fh = eh
fl = el
el = (dl + t1l) | 0
eh = (dh + t1h + getCarry(el, dl)) | 0
dh = ch
dl = cl
ch = bh
cl = bl
bh = ah
bl = al
al = (t1l + t2l) | 0
ah = (t1h + t2h + getCarry(al, t1l)) | 0
}
this._al = (this._al + al) | 0
this._bl = (this._bl + bl) | 0
this._cl = (this._cl + cl) | 0
this._dl = (this._dl + dl) | 0
this._el = (this._el + el) | 0
this._fl = (this._fl + fl) | 0
this._gl = (this._gl + gl) | 0
this._hl = (this._hl + hl) | 0
this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
}
Sha512.prototype._hash = function () {
var H = Buffer.allocUnsafe(64)
function writeInt64BE (h, l, offset) {
H.writeInt32BE(h, offset)
H.writeInt32BE(l, offset + 4)
}
writeInt64BE(this._ah, this._al, 0)
writeInt64BE(this._bh, this._bl, 8)
writeInt64BE(this._ch, this._cl, 16)
writeInt64BE(this._dh, this._dl, 24)
writeInt64BE(this._eh, this._el, 32)
writeInt64BE(this._fh, this._fl, 40)
writeInt64BE(this._gh, this._gl, 48)
writeInt64BE(this._hh, this._hl, 56)
return H
}
module.exports = Sha512
/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.sign = sign;
exports.verify = verify;
exports.generate = generate;
// This module provides the signing functionality used by the stellar network
// The code below may look a little strange... this is because we try to provide
// the most efficient signing method possible. First, we try to load the
// native `sodium-native` package for node.js environments, and if that fails we
// fallback to `tweetnacl`
var actualMethods = {};
/**
* Use this flag to check if fast signing (provided by `sodium-native` package) is available.
* If your app is signing a large number of transaction or verifying a large number
* of signatures make sure `sodium-native` package is installed.
*/
var FastSigning = exports.FastSigning = checkFastSigning();
function sign(data, secretKey) {
return actualMethods.sign(data, secretKey);
}
function verify(data, signature, publicKey) {
return actualMethods.verify(data, signature, publicKey);
}
function generate(secretKey) {
return actualMethods.generate(secretKey);
}
function checkFastSigning() {
return typeof window === 'undefined' ? checkFastSigningNode() : checkFastSigningBrowser();
}
function checkFastSigningNode() {
// NOTE: we use commonjs style require here because es6 imports
// can only occur at the top level. thanks, obama.
var sodium = void 0;
try {
// eslint-disable-next-line
sodium = __webpack_require__(197);
} catch (err) {
return checkFastSigningBrowser();
}
if (!Object.keys(sodium).length) {
return checkFastSigningBrowser();
}
actualMethods.generate = function (secretKey) {
var pk = Buffer.alloc(sodium.crypto_sign_PUBLICKEYBYTES);
var sk = Buffer.alloc(sodium.crypto_sign_SECRETKEYBYTES);
sodium.crypto_sign_seed_keypair(pk, sk, secretKey);
return pk;
};
actualMethods.sign = function (data, secretKey) {
data = Buffer.from(data);
var signature = Buffer.alloc(sodium.crypto_sign_BYTES);
sodium.crypto_sign_detached(signature, data, secretKey);
return signature;
};
actualMethods.verify = function (data, signature, publicKey) {
data = Buffer.from(data);
try {
return sodium.crypto_sign_verify_detached(signature, data, publicKey);
} catch (e) {
return false;
}
};
return true;
}
function checkFastSigningBrowser() {
// fallback to `tweetnacl` if we're in the browser or
// if there was a failure installing `sodium-native`
// eslint-disable-next-line
var nacl = __webpack_require__(103);
actualMethods.generate = function (secretKey) {
var secretKeyUint8 = new Uint8Array(secretKey);
var naclKeys = nacl.sign.keyPair.fromSeed(secretKeyUint8);
return Buffer.from(naclKeys.publicKey);
};
actualMethods.sign = function (data, secretKey) {
data = Buffer.from(data);
data = new Uint8Array(data.toJSON().data);
secretKey = new Uint8Array(secretKey.toJSON().data);
var signature = nacl.sign.detached(data, secretKey);
return Buffer.from(signature);
};
actualMethods.verify = function (data, signature, publicKey) {
data = Buffer.from(data);
data = new Uint8Array(data.toJSON().data);
signature = new Uint8Array(signature.toJSON().data);
publicKey = new Uint8Array(publicKey.toJSON().data);
return nacl.sign.detached.verify(data, signature, publicKey);
};
return false;
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 103 */
/***/ (function(module, exports, __webpack_require__) {
(function(nacl) {
'use strict';
// 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(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(/* 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 ts64(x, i, h, l) {
x[i] = (h >> 24) & 0xff;
x[i+1] = (h >> 16) & 0xff;
x[i+2] = (h >> 8) & 0xff;
x[i+3] = h & 0xff;
x[i+4] = (l >> 24) & 0xff;
x[i+5] = (l >> 16) & 0xff;
x[i+6] = (l >> 8) & 0xff;
x[i+7] = l & 0xff;
}
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_16(x, xi, y, yi) {
return vn(x,xi,y,yi,16);
}
function crypto_verify_32(x, xi, y, yi) {
return vn(x,xi,y,yi,32);
}
function core_salsa20(o, p, k, c) {
var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,
j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,
j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,
j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,
j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,
j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,
j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,
j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,
j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,
j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,
j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,
j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,
j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,
j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,
j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,
j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;
var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
x15 = j15, u;
for (var i = 0; i < 20; i += 2) {
u = x0 + x12 | 0;
x4 ^= u<<7 | u>>>(32-7);
u = x4 + x0 | 0;
x8 ^= u<<9 | u>>>(32-9);
u = x8 + x4 | 0;
x12 ^= u<<13 | u>>>(32-13);
u = x12 + x8 | 0;
x0 ^= u<<18 | u>>>(32-18);
u = x5 + x1 | 0;
x9 ^= u<<7 | u>>>(32-7);
u = x9 + x5 | 0;
x13 ^= u<<9 | u>>>(32-9);
u = x13 + x9 | 0;
x1 ^= u<<13 | u>>>(32-13);
u = x1 + x13 | 0;
x5 ^= u<<18 | u>>>(32-18);
u = x10 + x6 | 0;
x14 ^= u<<7 | u>>>(32-7);
u = x14 + x10 | 0;
x2 ^= u<<9 | u>>>(32-9);
u = x2 + x14 | 0;
x6 ^= u<<13 | u>>>(32-13);
u = x6 + x2 | 0;
x10 ^= u<<18 | u>>>(32-18);
u = x15 + x11 | 0;
x3 ^= u<<7 | u>>>(32-7);
u = x3 + x15 | 0;
x7 ^= u<<9 | u>>>(32-9);
u = x7 + x3 | 0;
x11 ^= u<<13 | u>>>(32-13);
u = x11 + x7 | 0;
x15 ^= u<<18 | u>>>(32-18);
u = x0 + x3 | 0;
x1 ^= u<<7 | u>>>(32-7);
u = x1 + x0 | 0;
x2 ^= u<<9 | u>>>(32-9);
u = x2 + x1 | 0;
x3 ^= u<<13 | u>>>(32-13);
u = x3 + x2 | 0;
x0 ^= u<<18 | u>>>(32-18);
u = x5 + x4 | 0;
x6 ^= u<<7 | u>>>(32-7);
u = x6 + x5 | 0;
x7 ^= u<<9 | u>>>(32-9);
u = x7 + x6 | 0;
x4 ^= u<<13 | u>>>(32-13);
u = x4 + x7 | 0;
x5 ^= u<<18 | u>>>(32-18);
u = x10 + x9 | 0;
x11 ^= u<<7 | u>>>(32-7);
u = x11 + x10 | 0;
x8 ^= u<<9 | u>>>(32-9);
u = x8 + x11 | 0;
x9 ^= u<<13 | u>>>(32-13);
u = x9 + x8 | 0;
x10 ^= u<<18 | u>>>(32-18);
u = x15 + x14 | 0;
x12 ^= u<<7 | u>>>(32-7);
u = x12 + x15 | 0;
x13 ^= u<<9 | u>>>(32-9);
u = x13 + x12 | 0;
x14 ^= u<<13 | u>>>(32-13);
u = x14 + x13 | 0;
x15 ^= u<<18 | u>>>(32-18);
}
x0 = x0 + j0 | 0;
x1 = x1 + j1 | 0;
x2 = x2 + j2 | 0;
x3 = x3 + j3 | 0;
x4 = x4 + j4 | 0;
x5 = x5 + j5 | 0;
x6 = x6 + j6 | 0;
x7 = x7 + j7 | 0;
x8 = x8 + j8 | 0;
x9 = x9 + j9 | 0;
x10 = x10 + j10 | 0;
x11 = x11 + j11 | 0;
x12 = x12 + j12 | 0;
x13 = x13 + j13 | 0;
x14 = x14 + j14 | 0;
x15 = x15 + j15 | 0;
o[ 0] = x0 >>> 0 & 0xff;
o[ 1] = x0 >>> 8 & 0xff;
o[ 2] = x0 >>> 16 & 0xff;
o[ 3] = x0 >>> 24 & 0xff;
o[ 4] = x1 >>> 0 & 0xff;
o[ 5] = x1 >>> 8 & 0xff;
o[ 6] = x1 >>> 16 & 0xff;
o[ 7] = x1 >>> 24 & 0xff;
o[ 8] = x2 >>> 0 & 0xff;
o[ 9] = x2 >>> 8 & 0xff;
o[10] = x2 >>> 16 & 0xff;
o[11] = x2 >>> 24 & 0xff;
o[12] = x3 >>> 0 & 0xff;
o[13] = x3 >>> 8 & 0xff;
o[14] = x3 >>> 16 & 0xff;
o[15] = x3 >>> 24 & 0xff;
o[16] = x4 >>> 0 & 0xff;
o[17] = x4 >>> 8 & 0xff;
o[18] = x4 >>> 16 & 0xff;
o[19] = x4 >>> 24 & 0xff;
o[20] = x5 >>> 0 & 0xff;
o[21] = x5 >>> 8 & 0xff;
o[22] = x5 >>> 16 & 0xff;
o[23] = x5 >>> 24 & 0xff;
o[24] = x6 >>> 0 & 0xff;
o[25] = x6 >>> 8 & 0xff;
o[26] = x6 >>> 16 & 0xff;
o[27] = x6 >>> 24 & 0xff;
o[28] = x7 >>> 0 & 0xff;
o[29] = x7 >>> 8 & 0xff;
o[30] = x7 >>> 16 & 0xff;
o[31] = x7 >>> 24 & 0xff;
o[32] = x8 >>> 0 & 0xff;
o[33] = x8 >>> 8 & 0xff;
o[34] = x8 >>> 16 & 0xff;
o[35] = x8 >>> 24 & 0xff;
o[36] = x9 >>> 0 & 0xff;
o[37] = x9 >>> 8 & 0xff;
o[38] = x9 >>> 16 & 0xff;
o[39] = x9 >>> 24 & 0xff;
o[40] = x10 >>> 0 & 0xff;
o[41] = x10 >>> 8 & 0xff;
o[42] = x10 >>> 16 & 0xff;
o[43] = x10 >>> 24 & 0xff;
o[44] = x11 >>> 0 & 0xff;
o[45] = x11 >>> 8 & 0xff;
o[46] = x11 >>> 16 & 0xff;
o[47] = x11 >>> 24 & 0xff;
o[48] = x12 >>> 0 & 0xff;
o[49] = x12 >>> 8 & 0xff;
o[50] = x12 >>> 16 & 0xff;
o[51] = x12 >>> 24 & 0xff;
o[52] = x13 >>> 0 & 0xff;
o[53] = x13 >>> 8 & 0xff;
o[54] = x13 >>> 16 & 0xff;
o[55] = x13 >>> 24 & 0xff;
o[56] = x14 >>> 0 & 0xff;
o[57] = x14 >>> 8 & 0xff;
o[58] = x14 >>> 16 & 0xff;
o[59] = x14 >>> 24 & 0xff;
o[60] = x15 >>> 0 & 0xff;
o[61] = x15 >>> 8 & 0xff;
o[62] = x15 >>> 16 & 0xff;
o[63] = x15 >>> 24 & 0xff;
}
function core_hsalsa20(o,p,k,c) {
var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,
j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,
j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,
j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,
j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,
j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,
j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,
j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,
j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,
j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,
j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,
j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,
j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,
j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,
j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,
j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;
var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
x15 = j15, u;
for (var i = 0; i < 20; i += 2) {
u = x0 + x12 | 0;
x4 ^= u<<7 | u>>>(32-7);
u = x4 + x0 | 0;
x8 ^= u<<9 | u>>>(32-9);
u = x8 + x4 | 0;
x12 ^= u<<13 | u>>>(32-13);
u = x12 + x8 | 0;
x0 ^= u<<18 | u>>>(32-18);
u = x5 + x1 | 0;
x9 ^= u<<7 | u>>>(32-7);
u = x9 + x5 | 0;
x13 ^= u<<9 | u>>>(32-9);
u = x13 + x9 | 0;
x1 ^= u<<13 | u>>>(32-13);
u = x1 + x13 | 0;
x5 ^= u<<18 | u>>>(32-18);
u = x10 + x6 | 0;
x14 ^= u<<7 | u>>>(32-7);
u = x14 + x10 | 0;
x2 ^= u<<9 | u>>>(32-9);
u = x2 + x14 | 0;
x6 ^= u<<13 | u>>>(32-13);
u = x6 + x2 | 0;
x10 ^= u<<18 | u>>>(32-18);
u = x15 + x11 | 0;
x3 ^= u<<7 | u>>>(32-7);
u = x3 + x15 | 0;
x7 ^= u<<9 | u>>>(32-9);
u = x7 + x3 | 0;
x11 ^= u<<13 | u>>>(32-13);
u = x11 + x7 | 0;
x15 ^= u<<18 | u>>>(32-18);
u = x0 + x3 | 0;
x1 ^= u<<7 | u>>>(32-7);
u = x1 + x0 | 0;
x2 ^= u<<9 | u>>>(32-9);
u = x2 + x1 | 0;
x3 ^= u<<13 | u>>>(32-13);
u = x3 + x2 | 0;
x0 ^= u<<18 | u>>>(32-18);
u = x5 + x4 | 0;
x6 ^= u<<7 | u>>>(32-7);
u = x6 + x5 | 0;
x7 ^= u<<9 | u>>>(32-9);
u = x7 + x6 | 0;
x4 ^= u<<13 | u>>>(32-13);
u = x4 + x7 | 0;
x5 ^= u<<18 | u>>>(32-18);
u = x10 + x9 | 0;
x11 ^= u<<7 | u>>>(32-7);
u = x11 + x10 | 0;
x8 ^= u<<9 | u>>>(32-9);
u = x8 + x11 | 0;
x9 ^= u<<13 | u>>>(32-13);
u = x9 + x8 | 0;
x10 ^= u<<18 | u>>>(32-18);
u = x15 + x14 | 0;
x12 ^= u<<7 | u>>>(32-7);
u = x12 + x15 | 0;
x13 ^= u<<9 | u>>>(32-9);
u = x13 + x12 | 0;
x14 ^= u<<13 | u>>>(32-13);
u = x14 + x13 | 0;
x15 ^= u<<18 | u>>>(32-18);
}
o[ 0] = x0 >>> 0 & 0xff;
o[ 1] = x0 >>> 8 & 0xff;
o[ 2] = x0 >>> 16 & 0xff;
o[ 3] = x0 >>> 24 & 0xff;
o[ 4] = x5 >>> 0 & 0xff;
o[ 5] = x5 >>> 8 & 0xff;
o[ 6] = x5 >>> 16 & 0xff;
o[ 7] = x5 >>> 24 & 0xff;
o[ 8] = x10 >>> 0 & 0xff;
o[ 9] = x10 >>> 8 & 0xff;
o[10] = x10 >>> 16 & 0xff;
o[11] = x10 >>> 24 & 0xff;
o[12] = x15 >>> 0 & 0xff;
o[13] = x15 >>> 8 & 0xff;
o[14] = x15 >>> 16 & 0xff;
o[15] = x15 >>> 24 & 0xff;
o[16] = x6 >>> 0 & 0xff;
o[17] = x6 >>> 8 & 0xff;
o[18] = x6 >>> 16 & 0xff;
o[19] = x6 >>> 24 & 0xff;
o[20] = x7 >>> 0 & 0xff;
o[21] = x7 >>> 8 & 0xff;
o[22] = x7 >>> 16 & 0xff;
o[23] = x7 >>> 24 & 0xff;
o[24] = x8 >>> 0 & 0xff;
o[25] = x8 >>> 8 & 0xff;
o[26] = x8 >>> 16 & 0xff;
o[27] = x8 >>> 24 & 0xff;
o[28] = x9 >>> 0 & 0xff;
o[29] = x9 >>> 8 & 0xff;
o[30] = x9 >>> 16 & 0xff;
o[31] = x9 >>> 24 & 0xff;
}
function crypto_core_salsa20(out,inp,k,c) {
core_salsa20(out,inp,k,c);
}
function crypto_core_hsalsa20(out,inp,k,c) {
core_hsalsa20(out,inp,k,c);
}
var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]);
// "expand 32-byte k"
function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) {
var z = new Uint8Array(16), x = new Uint8Array(64);
var u, i;
for (i = 0; i < 16; i++) z[i] = 0;
for (i = 0; i < 8; i++) z[i] = n[i];
while (b >= 64) {
crypto_core_salsa20(x,z,k,sigma);
for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i];
u = 1;
for (i = 8; i < 16; i++) {
u = u + (z[i] & 0xff) | 0;
z[i] = u & 0xff;
u >>>= 8;
}
b -= 64;
cpos += 64;
mpos += 64;
}
if (b > 0) {
crypto_core_salsa20(x,z,k,sigma);
for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i];
}
return 0;
}
function crypto_stream_salsa20(c,cpos,b,n,k) {
var z = new Uint8Array(16), x = new Uint8Array(64);
var u, i;
for (i = 0; i < 16; i++) z[i] = 0;
for (i = 0; i < 8; i++) z[i] = n[i];
while (b >= 64) {
crypto_core_salsa20(x,z,k,sigma);
for (i = 0; i < 64; i++) c[cpos+i] = x[i];
u = 1;
for (i = 8; i < 16; i++) {
u = u + (z[i] & 0xff) | 0;
z[i] = u & 0xff;
u >>>= 8;
}
b -= 64;
cpos += 64;
}
if (b > 0) {
crypto_core_salsa20(x,z,k,sigma);
for (i = 0; i < b; i++) c[cpos+i] = x[i];
}
return 0;
}
function crypto_stream(c,cpos,d,n,k) {
var s = new Uint8Array(32);
crypto_core_hsalsa20(s,n,k,sigma);
var sn = new Uint8Array(8);
for (var i = 0; i < 8; i++) sn[i] = n[i+16];
return crypto_stream_salsa20(c,cpos,d,sn,s);
}
function crypto_stream_xor(c,cpos,m,mpos,d,n,k) {
var s = new Uint8Array(32);
crypto_core_hsalsa20(s,n,k,sigma);
var sn = new Uint8Array(8);
for (var i = 0; i < 8; i++) sn[i] = n[i+16];
return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s);
}
/*
* Port of Andrew Moon's Poly1305-donna-16. Public domain.
* https://github.com/floodyberry/poly1305-donna
*/
var poly1305 = function(key) {
this.buffer = new Uint8Array(16);
this.r = new Uint16Array(10);
this.h = new Uint16Array(10);
this.pad = new Uint16Array(8);
this.leftover = 0;
this.fin = 0;
var t0, t1, t2, t3, t4, t5, t6, t7;
t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff;
t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
this.r[5] = ((t4 >>> 1)) & 0x1ffe;
t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
this.r[9] = ((t7 >>> 5)) & 0x007f;
this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8;
this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8;
this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8;
this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8;
this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8;
this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8;
this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8;
this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8;
};
poly1305.prototype.blocks = function(m, mpos, bytes) {
var hibit = this.fin ? 0 : (1 << 11);
var t0, t1, t2, t3, t4, t5, t6, t7, c;
var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;
var h0 = this.h[0],
h1 = this.h[1],
h2 = this.h[2],
h3 = this.h[3],
h4 = this.h[4],
h5 = this.h[5],
h6 = this.h[6],
h7 = this.h[7],
h8 = this.h[8],
h9 = this.h[9];
var r0 = this.r[0],
r1 = this.r[1],
r2 = this.r[2],
r3 = this.r[3],
r4 = this.r[4],
r5 = this.r[5],
r6 = this.r[6],
r7 = this.r[7],
r8 = this.r[8],
r9 = this.r[9];
while (bytes >= 16) {
t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff;
t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;
t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;
h5 += ((t4 >>> 1)) & 0x1fff;
t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;
t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
h9 += ((t7 >>> 5)) | hibit;
c = 0;
d0 = c;
d0 += h0 * r0;
d0 += h1 * (5 * r9);
d0 += h2 * (5 * r8);
d0 += h3 * (5 * r7);
d0 += h4 * (5 * r6);
c = (d0 >>> 13); d0 &= 0x1fff;
d0 += h5 * (5 * r5);
d0 += h6 * (5 * r4);
d0 += h7 * (5 * r3);
d0 += h8 * (5 * r2);
d0 += h9 * (5 * r1);
c += (d0 >>> 13); d0 &= 0x1fff;
d1 = c;
d1 += h0 * r1;
d1 += h1 * r0;
d1 += h2 * (5 * r9);
d1 += h3 * (5 * r8);
d1 += h4 * (5 * r7);
c = (d1 >>> 13); d1 &= 0x1fff;
d1 += h5 * (5 * r6);
d1 += h6 * (5 * r5);
d1 += h7 * (5 * r4);
d1 += h8 * (5 * r3);
d1 += h9 * (5 * r2);
c += (d1 >>> 13); d1 &= 0x1fff;
d2 = c;
d2 += h0 * r2;
d2 += h1 * r1;
d2 += h2 * r0;
d2 += h3 * (5 * r9);
d2 += h4 * (5 * r8);
c = (d2 >>> 13); d2 &= 0x1fff;
d2 += h5 * (5 * r7);
d2 += h6 * (5 * r6);
d2 += h7 * (5 * r5);
d2 += h8 * (5 * r4);
d2 += h9 * (5 * r3);
c += (d2 >>> 13); d2 &= 0x1fff;
d3 = c;
d3 += h0 * r3;
d3 += h1 * r2;
d3 += h2 * r1;
d3 += h3 * r0;
d3 += h4 * (5 * r9);
c = (d3 >>> 13); d3 &= 0x1fff;
d3 += h5 * (5 * r8);
d3 += h6 * (5 * r7);
d3 += h7 * (5 * r6);
d3 += h8 * (5 * r5);
d3 += h9 * (5 * r4);
c += (d3 >>> 13); d3 &= 0x1fff;
d4 = c;
d4 += h0 * r4;
d4 += h1 * r3;
d4 += h2 * r2;
d4 += h3 * r1;
d4 += h4 * r0;
c = (d4 >>> 13); d4 &= 0x1fff;
d4 += h5 * (5 * r9);
d4 += h6 * (5 * r8);
d4 += h7 * (5 * r7);
d4 += h8 * (5 * r6);
d4 += h9 * (5 * r5);
c += (d4 >>> 13); d4 &= 0x1fff;
d5 = c;
d5 += h0 * r5;
d5 += h1 * r4;
d5 += h2 * r3;
d5 += h3 * r2;
d5 += h4 * r1;
c = (d5 >>> 13); d5 &= 0x1fff;
d5 += h5 * r0;
d5 += h6 * (5 * r9);
d5 += h7 * (5 * r8);
d5 += h8 * (5 * r7);
d5 += h9 * (5 * r6);
c += (d5 >>> 13); d5 &= 0x1fff;
d6 = c;
d6 += h0 * r6;
d6 += h1 * r5;
d6 += h2 * r4;
d6 += h3 * r3;
d6 += h4 * r2;
c = (d6 >>> 13); d6 &= 0x1fff;
d6 += h5 * r1;
d6 += h6 * r0;
d6 += h7 * (5 * r9);
d6 += h8 * (5 * r8);
d6 += h9 * (5 * r7);
c += (d6 >>> 13); d6 &= 0x1fff;
d7 = c;
d7 += h0 * r7;
d7 += h1 * r6;
d7 += h2 * r5;
d7 += h3 * r4;
d7 += h4 * r3;
c = (d7 >>> 13); d7 &= 0x1fff;
d7 += h5 * r2;
d7 += h6 * r1;
d7 += h7 * r0;
d7 += h8 * (5 * r9);
d7 += h9 * (5 * r8);
c += (d7 >>> 13); d7 &= 0x1fff;
d8 = c;
d8 += h0 * r8;
d8 += h1 * r7;
d8 += h2 * r6;
d8 += h3 * r5;
d8 += h4 * r4;
c = (d8 >>> 13); d8 &= 0x1fff;
d8 += h5 * r3;
d8 += h6 * r2;
d8 += h7 * r1;
d8 += h8 * r0;
d8 += h9 * (5 * r9);
c += (d8 >>> 13); d8 &= 0x1fff;
d9 = c;
d9 += h0 * r9;
d9 += h1 * r8;
d9 += h2 * r7;
d9 += h3 * r6;
d9 += h4 * r5;
c = (d9 >>> 13); d9 &= 0x1fff;
d9 += h5 * r4;
d9 += h6 * r3;
d9 += h7 * r2;
d9 += h8 * r1;
d9 += h9 * r0;
c += (d9 >>> 13); d9 &= 0x1fff;
c = (((c << 2) + c)) | 0;
c = (c + d0) | 0;
d0 = c & 0x1fff;
c = (c >>> 13);
d1 += c;
h0 = d0;
h1 = d1;
h2 = d2;
h3 = d3;
h4 = d4;
h5 = d5;
h6 = d6;
h7 = d7;
h8 = d8;
h9 = d9;
mpos += 16;
bytes -= 16;
}
this.h[0] = h0;
this.h[1] = h1;
this.h[2] = h2;
this.h[3] = h3;
this.h[4] = h4;
this.h[5] = h5;
this.h[6] = h6;
this.h[7] = h7;
this.h[8] = h8;
this.h[9] = h9;
};
poly1305.prototype.finish = function(mac, macpos) {
var g = new Uint16Array(10);
var c, mask, f, i;
if (this.leftover) {
i = this.leftover;
this.buffer[i++] = 1;
for (; i < 16; i++) this.buffer[i] = 0;
this.fin = 1;
this.blocks(this.buffer, 0, 16);
}
c = this.h[1] >>> 13;
this.h[1] &= 0x1fff;
for (i = 2; i < 10; i++) {
this.h[i] += c;
c = this.h[i] >>> 13;
this.h[i] &= 0x1fff;
}
this.h[0] += (c * 5);
c = this.h[0] >>> 13;
this.h[0] &= 0x1fff;
this.h[1] += c;
c = this.h[1] >>> 13;
this.h[1] &= 0x1fff;
this.h[2] += c;
g[0] = this.h[0] + 5;
c = g[0] >>> 13;
g[0] &= 0x1fff;
for (i = 1; i < 10; i++) {
g[i] = this.h[i] + c;
c = g[i] >>> 13;
g[i] &= 0x1fff;
}
g[9] -= (1 << 13);
mask = (c ^ 1) - 1;
for (i = 0; i < 10; i++) g[i] &= mask;
mask = ~mask;
for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i];
this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff;
this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff;
this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff;
this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff;
this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff;
this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff;
this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff;
this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff;
f = this.h[0] + this.pad[0];
this.h[0] = f & 0xffff;
for (i = 1; i < 8; i++) {
f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0;
this.h[i] = f & 0xffff;
}
mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff;
mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff;
mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff;
mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff;
mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff;
mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff;
mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff;
mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff;
mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff;
mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff;
mac[macpos+10] = (this.h[5] >>> 0) & 0xff;
mac[macpos+11] = (this.h[5] >>> 8) & 0xff;
mac[macpos+12] = (this.h[6] >>> 0) & 0xff;
mac[macpos+13] = (this.h[6] >>> 8) & 0xff;
mac[macpos+14] = (this.h[7] >>> 0) & 0xff;
mac[macpos+15] = (this.h[7] >>> 8) & 0xff;
};
poly1305.prototype.update = function(m, mpos, bytes) {
var i, want;
if (this.leftover) {
want = (16 - this.leftover);
if (want > bytes)
want = bytes;
for (i = 0; i < want; i++)
this.buffer[this.leftover + i] = m[mpos+i];
bytes -= want;
mpos += want;
this.leftover += want;
if (this.leftover < 16)
return;
this.blocks(this.buffer, 0, 16);
this.leftover = 0;
}
if (bytes >= 16) {
want = bytes - (bytes % 16);
this.blocks(m, mpos, want);
mpos += want;
bytes -= want;
}
if (bytes) {
for (i = 0; i < bytes; i++)
this.buffer[this.leftover + i] = m[mpos+i];
this.leftover += bytes;
}
};
function crypto_onetimeauth(out, outpos, m, mpos, n, k) {
var s = new poly1305(k);
s.update(m, mpos, n);
s.finish(out, outpos);
return 0;
}
function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {
var x = new Uint8Array(16);
crypto_onetimeauth(x,0,m,mpos,n,k);
return crypto_verify_16(h,hpos,x,0);
}
function crypto_secretbox(c,m,d,n,k) {
var i;
if (d < 32) return -1;
crypto_stream_xor(c,0,m,0,d,n,k);
crypto_onetimeauth(c, 16, c, 32, d - 32, c);
for (i = 0; i < 16; i++) c[i] = 0;
return 0;
}
function crypto_secretbox_open(m,c,d,n,k) {
var i;
var x = new Uint8Array(32);
if (d < 32) return -1;
crypto_stream(x,0,32,n,k);
if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1;
crypto_stream_xor(m,0,c,0,d,n,k);
for (i = 0; i < 32; i++) m[i] = 0;
return 0;
}
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 crypto_box_keypair(y, x) {
randombytes(x, 32);
return crypto_scalarmult_base(y, x);
}
function crypto_box_beforenm(k, y, x) {
var s = new Uint8Array(32);
crypto_scalarmult(s, x, y);
return crypto_core_hsalsa20(k, _0, s, sigma);
}
var crypto_box_afternm = crypto_secretbox;
var crypto_box_open_afternm = crypto_secretbox_open;
function crypto_box(c, m, d, n, y, x) {
var k = new Uint8Array(32);
crypto_box_beforenm(k, y, x);
return crypto_box_afternm(c, m, d, n, k);
}
function crypto_box_open(m, c, d, n, y, x) {
var k = new Uint8Array(32);
crypto_box_beforenm(k, y, x);
return crypto_box_open_afternm(m, c, d, n, k);
}
var K = [
0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
];
function crypto_hashblocks_hl(hh, hl, m, n) {
var wh = new Int32Array(16), wl = new Int32Array(16),
bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,
bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,
th, tl, i, j, h, l, a, b, c, d;
var ah0 = hh[0],
ah1 = hh[1],
ah2 = hh[2],
ah3 = hh[3],
ah4 = hh[4],
ah5 = hh[5],
ah6 = hh[6],
ah7 = hh[7],
al0 = hl[0],
al1 = hl[1],
al2 = hl[2],
al3 = hl[3],
al4 = hl[4],
al5 = hl[5],
al6 = hl[6],
al7 = hl[7];
var pos = 0;
while (n >= 128) {
for (i = 0; i < 16; i++) {
j = 8 * i + pos;
wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];
wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];
}
for (i = 0; i < 80; i++) {
bh0 = ah0;
bh1 = ah1;
bh2 = ah2;
bh3 = ah3;
bh4 = ah4;
bh5 = ah5;
bh6 = ah6;
bh7 = ah7;
bl0 = al0;
bl1 = al1;
bl2 = al2;
bl3 = al3;
bl4 = al4;
bl5 = al5;
bl6 = al6;
bl7 = al7;
// add
h = ah7;
l = al7;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
// Sigma1
h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));
l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
// Ch
h = (ah4 & ah5) ^ (~ah4 & ah6);
l = (al4 & al5) ^ (~al4 & al6);
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
// K
h = K[i*2];
l = K[i*2+1];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
// w
h = wh[i%16];
l = wl[i%16];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
th = c & 0xffff | d << 16;
tl = a & 0xffff | b << 16;
// add
h = th;
l = tl;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
// Sigma0
h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));
l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
// Maj
h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);
l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
bh7 = (c & 0xffff) | (d << 16);
bl7 = (a & 0xffff) | (b << 16);
// add
h = bh3;
l = bl3;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = th;
l = tl;
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
bh3 = (c & 0xffff) | (d << 16);
bl3 = (a & 0xffff) | (b << 16);
ah1 = bh0;
ah2 = bh1;
ah3 = bh2;
ah4 = bh3;
ah5 = bh4;
ah6 = bh5;
ah7 = bh6;
ah0 = bh7;
al1 = bl0;
al2 = bl1;
al3 = bl2;
al4 = bl3;
al5 = bl4;
al6 = bl5;
al7 = bl6;
al0 = bl7;
if (i%16 === 15) {
for (j = 0; j < 16; j++) {
// add
h = wh[j];
l = wl[j];
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = wh[(j+9)%16];
l = wl[(j+9)%16];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
// sigma0
th = wh[(j+1)%16];
tl = wl[(j+1)%16];
h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);
l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
// sigma1
th = wh[(j+14)%16];
tl = wl[(j+14)%16];
h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);
l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
wh[j] = (c & 0xffff) | (d << 16);
wl[j] = (a & 0xffff) | (b << 16);
}
}
}
// add
h = ah0;
l = al0;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = hh[0];
l = hl[0];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[0] = ah0 = (c & 0xffff) | (d << 16);
hl[0] = al0 = (a & 0xffff) | (b << 16);
h = ah1;
l = al1;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = hh[1];
l = hl[1];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[1] = ah1 = (c & 0xffff) | (d << 16);
hl[1] = al1 = (a & 0xffff) | (b << 16);
h = ah2;
l = al2;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = hh[2];
l = hl[2];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[2] = ah2 = (c & 0xffff) | (d << 16);
hl[2] = al2 = (a & 0xffff) | (b << 16);
h = ah3;
l = al3;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = hh[3];
l = hl[3];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[3] = ah3 = (c & 0xffff) | (d << 16);
hl[3] = al3 = (a & 0xffff) | (b << 16);
h = ah4;
l = al4;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = hh[4];
l = hl[4];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[4] = ah4 = (c & 0xffff) | (d << 16);
hl[4] = al4 = (a & 0xffff) | (b << 16);
h = ah5;
l = al5;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = hh[5];
l = hl[5];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[5] = ah5 = (c & 0xffff) | (d << 16);
hl[5] = al5 = (a & 0xffff) | (b << 16);
h = ah6;
l = al6;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = hh[6];
l = hl[6];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[6] = ah6 = (c & 0xffff) | (d << 16);
hl[6] = al6 = (a & 0xffff) | (b << 16);
h = ah7;
l = al7;
a = l & 0xffff; b = l >>> 16;
c = h & 0xffff; d = h >>> 16;
h = hh[7];
l = hl[7];
a += l & 0xffff; b += l >>> 16;
c += h & 0xffff; d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[7] = ah7 = (c & 0xffff) | (d << 16);
hl[7] = al7 = (a & 0xffff) | (b << 16);
pos += 128;
n -= 128;
}
return n;
}
function crypto_hash(out, m, n) {
var hh = new Int32Array(8),
hl = new Int32Array(8),
x = new Uint8Array(256),
i, b = n;
hh[0] = 0x6a09e667;
hh[1] = 0xbb67ae85;
hh[2] = 0x3c6ef372;
hh[3] = 0xa54ff53a;
hh[4] = 0x510e527f;
hh[5] = 0x9b05688c;
hh[6] = 0x1f83d9ab;
hh[7] = 0x5be0cd19;
hl[0] = 0xf3bcc908;
hl[1] = 0x84caa73b;
hl[2] = 0xfe94f82b;
hl[3] = 0x5f1d36f1;
hl[4] = 0xade682d1;
hl[5] = 0x2b3e6c1f;
hl[6] = 0xfb41bd6b;
hl[7] = 0x137e2179;
crypto_hashblocks_hl(hh, hl, m, n);
n %= 128;
for (i = 0; i < n; i++) x[i] = m[b-n+i];
x[n] = 128;
n = 256-128*(n<112?1:0);
x[n-9] = 0;
ts64(x, n-8, (b / 0x20000000) | 0, b << 3);
crypto_hashblocks_hl(hh, hl, x, n);
for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);
return 0;
}
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(pk, sk, seeded) {
var d = new Uint8Array(64);
var p = [gf(), gf(), gf(), gf()];
var i;
if (!seeded) randombytes(sk, 32);
crypto_hash(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;
}
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 = Math.floor((x[j] + 128) / 256);
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);
}
// Note: difference from C - smlen returned, not passed as argument.
function crypto_sign(sm, m, n, sk) {
var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);
var i, j, x = new Float64Array(64);
var p = [gf(), gf(), gf(), gf()];
crypto_hash(d, sk, 32);
d[0] &= 248;
d[31] &= 127;
d[31] |= 64;
var smlen = n + 64;
for (i = 0; i < n; i++) sm[64 + i] = m[i];
for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
crypto_hash(r, sm.subarray(32), n+32);
reduce(r);
scalarbase(p, r);
pack(sm, p);
for (i = 32; i < 64; i++) sm[i] = sk[i];
crypto_hash(h, sm, n + 64);
reduce(h);
for (i = 0; i < 64; i++) x[i] = 0;
for (i = 0; i < 32; i++) x[i] = r[i];
for (i = 0; i < 32; i++) {
for (j = 0; j < 32; j++) {
x[i+j] += h[i] * d[j];
}
}
modL(sm.subarray(32), x);
return smlen;
}
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);
S(num, r[1]);
M(den, num, D);
Z(num, num, r[2]);
A(den, r[2], den);
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 crypto_sign_open(m, sm, n, pk) {
var i;
var t = new Uint8Array(32), h = new Uint8Array(64);
var p = [gf(), gf(), gf(), gf()],
q = [gf(), gf(), gf(), gf()];
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];
return n;
}
var crypto_secretbox_KEYBYTES = 32,
crypto_secretbox_NONCEBYTES = 24,
crypto_secretbox_ZEROBYTES = 32,
crypto_secretbox_BOXZEROBYTES = 16,
crypto_scalarmult_BYTES = 32,
crypto_scalarmult_SCALARBYTES = 32,
crypto_box_PUBLICKEYBYTES = 32,
crypto_box_SECRETKEYBYTES = 32,
crypto_box_BEFORENMBYTES = 32,
crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES,
crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES,
crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES,
crypto_sign_BYTES = 64,
crypto_sign_PUBLICKEYBYTES = 32,
crypto_sign_SECRETKEYBYTES = 64,
crypto_sign_SEEDBYTES = 32,
crypto_hash_BYTES = 64;
nacl.lowlevel = {
crypto_core_hsalsa20: crypto_core_hsalsa20,
crypto_stream_xor: crypto_stream_xor,
crypto_stream: crypto_stream,
crypto_stream_salsa20_xor: crypto_stream_salsa20_xor,
crypto_stream_salsa20: crypto_stream_salsa20,
crypto_onetimeauth: crypto_onetimeauth,
crypto_onetimeauth_verify: crypto_onetimeauth_verify,
crypto_verify_16: crypto_verify_16,
crypto_verify_32: crypto_verify_32,
crypto_secretbox: crypto_secretbox,
crypto_secretbox_open: crypto_secretbox_open,
crypto_scalarmult: crypto_scalarmult,
crypto_scalarmult_base: crypto_scalarmult_base,
crypto_box_beforenm: crypto_box_beforenm,
crypto_box_afternm: crypto_box_afternm,
crypto_box: crypto_box,
crypto_box_open: crypto_box_open,
crypto_box_keypair: crypto_box_keypair,
crypto_hash: crypto_hash,
crypto_sign: crypto_sign,
crypto_sign_keypair: crypto_sign_keypair,
crypto_sign_open: crypto_sign_open,
crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES,
crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES,
crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES,
crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES,
crypto_scalarmult_BYTES: crypto_scalarmult_BYTES,
crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES,
crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES,
crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES,
crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES,
crypto_box_NONCEBYTES: crypto_box_NONCEBYTES,
crypto_box_ZEROBYTES: crypto_box_ZEROBYTES,
crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES,
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,
gf: gf,
D: D,
L: L,
pack25519: pack25519,
unpack25519: unpack25519,
M: M,
A: A,
S: S,
Z: Z,
pow2523: pow2523,
add: add,
set25519: set25519,
modL: modL,
scalarmult: scalarmult,
scalarbase: scalarbase,
};
/* High-level API */
function checkLengths(k, n) {
if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size');
if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size');
}
function checkBoxLengths(pk, sk) {
if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size');
if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size');
}
function checkArrayTypes() {
for (var i = 0; i < arguments.length; i++) {
if (!(arguments[i] instanceof Uint8Array))
throw new TypeError('unexpected type, 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.secretbox = function(msg, nonce, key) {
checkArrayTypes(msg, nonce, key);
checkLengths(key, nonce);
var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);
var c = new Uint8Array(m.length);
for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i];
crypto_secretbox(c, m, m.length, nonce, key);
return c.subarray(crypto_secretbox_BOXZEROBYTES);
};
nacl.secretbox.open = function(box, nonce, key) {
checkArrayTypes(box, nonce, key);
checkLengths(key, nonce);
var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);
var m = new Uint8Array(c.length);
for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i];
if (c.length < 32) return null;
if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null;
return m.subarray(crypto_secretbox_ZEROBYTES);
};
nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;
nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;
nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;
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.box = function(msg, nonce, publicKey, secretKey) {
var k = nacl.box.before(publicKey, secretKey);
return nacl.secretbox(msg, nonce, k);
};
nacl.box.before = function(publicKey, secretKey) {
checkArrayTypes(publicKey, secretKey);
checkBoxLengths(publicKey, secretKey);
var k = new Uint8Array(crypto_box_BEFORENMBYTES);
crypto_box_beforenm(k, publicKey, secretKey);
return k;
};
nacl.box.after = nacl.secretbox;
nacl.box.open = function(msg, nonce, publicKey, secretKey) {
var k = nacl.box.before(publicKey, secretKey);
return nacl.secretbox.open(msg, nonce, k);
};
nacl.box.open.after = nacl.secretbox.open;
nacl.box.keyPair = function() {
var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
crypto_box_keypair(pk, sk);
return {publicKey: pk, secretKey: sk};
};
nacl.box.keyPair.fromSecretKey = function(secretKey) {
checkArrayTypes(secretKey);
if (secretKey.length !== crypto_box_SECRETKEYBYTES)
throw new Error('bad secret key size');
var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
crypto_scalarmult_base(pk, secretKey);
return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
};
nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;
nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;
nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;
nacl.box.nonceLength = crypto_box_NONCEBYTES;
nacl.box.overheadLength = nacl.secretbox.overheadLength;
nacl.sign = function(msg, secretKey) {
checkArrayTypes(msg, secretKey);
if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
throw new Error('bad secret key size');
var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);
crypto_sign(signedMsg, msg, msg.length, secretKey);
return signedMsg;
};
nacl.sign.open = function(signedMsg, publicKey) {
checkArrayTypes(signedMsg, publicKey);
if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
throw new Error('bad public key size');
var tmp = new Uint8Array(signedMsg.length);
var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);
if (mlen < 0) return null;
var m = new Uint8Array(mlen);
for (var i = 0; i < m.length; i++) m[i] = tmp[i];
return m;
};
nacl.sign.detached = function(msg, secretKey) {
var signedMsg = nacl.sign(msg, secretKey);
var sig = new Uint8Array(crypto_sign_BYTES);
for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
return sig;
};
nacl.sign.detached.verify = function(msg, sig, publicKey) {
checkArrayTypes(msg, sig, publicKey);
if (sig.length !== crypto_sign_BYTES)
throw new Error('bad signature size');
if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
throw new Error('bad public key size');
var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
var m = new Uint8Array(crypto_sign_BYTES + msg.length);
var i;
for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
};
nacl.sign.keyPair = function() {
var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
crypto_sign_keypair(pk, sk);
return {publicKey: pk, secretKey: sk};
};
nacl.sign.keyPair.fromSecretKey = function(secretKey) {
checkArrayTypes(secretKey);
if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
throw new Error('bad secret key size');
var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];
return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
};
nacl.sign.keyPair.fromSeed = function(seed) {
checkArrayTypes(seed);
if (seed.length !== crypto_sign_SEEDBYTES)
throw new Error('bad seed size');
var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
for (var i = 0; i < 32; i++) sk[i] = seed[i];
crypto_sign_keypair(pk, sk, true);
return {publicKey: pk, secretKey: sk};
};
nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;
nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;
nacl.sign.seedLength = crypto_sign_SEEDBYTES;
nacl.sign.signatureLength = crypto_sign_BYTES;
nacl.hash = function(msg) {
checkArrayTypes(msg);
var h = new Uint8Array(crypto_hash_BYTES);
crypto_hash(h, msg, msg.length);
return h;
};
nacl.hash.hashLength = crypto_hash_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;
};
(function() {
// Initialize PRNG if environment provides CSPRNG.
// If not, methods calling randombytes will throw.
var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;
if (crypto && crypto.getRandomValues) {
// Browsers.
var QUOTA = 65536;
nacl.setPRNG(function(x, n) {
var i, v = new Uint8Array(n);
for (i = 0; i < n; i += QUOTA) {
crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
}
for (i = 0; i < n; i++) x[i] = v[i];
cleanup(v);
});
} else if (true) {
// Node.js.
crypto = __webpack_require__(198);
if (crypto && crypto.randomBytes) {
nacl.setPRNG(function(x, n) {
var i, v = crypto.randomBytes(n);
for (i = 0; i < n; i++) x[i] = v[i];
cleanup(v);
});
}
}
})();
})( true && module.exports ? module.exports : (self.nacl = self.nacl || {}));
/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.LiquidityPoolFeeV18 = undefined;
exports.getLiquidityPoolId = getLiquidityPoolId;
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _asset = __webpack_require__(27);
var _hashing = __webpack_require__(30);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// LiquidityPoolFeeV18 is the default liquidity pool fee in protocol v18. It defaults to 30 base points (0.3%).
var LiquidityPoolFeeV18 = exports.LiquidityPoolFeeV18 = 30;
/**
* getLiquidityPoolId computes the Pool ID for the given assets, fee and pool type.
*
* @see [stellar-core getPoolID](https://github.com/stellar/stellar-core/blob/9f3a48c6a8f1aa77b6043a055d0638661f718080/src/ledger/test/LedgerTxnTests.cpp#L3746-L3751)
*
* @export
* @param {string} liquidityPoolType – A string representing the liquidity pool type.
* @param {object} liquidityPoolParameters – The liquidity pool parameters.
* @param {Asset} liquidityPoolParameters.assetA – The first asset in the Pool, it must respect the rule assetA < assetB.
* @param {Asset} liquidityPoolParameters.assetB – The second asset in the Pool, it must respect the rule assetA < assetB.
* @param {number} liquidityPoolParameters.fee – The liquidity pool fee. For now the only fee supported is `30`.
*
* @return {Buffer} the raw Pool ID buffer, which can be stringfied with `toString('hex')`
*/
function getLiquidityPoolId(liquidityPoolType) {
var liquidityPoolParameters = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (liquidityPoolType !== 'constant_product') {
throw new Error('liquidityPoolType is invalid');
}
var assetA = liquidityPoolParameters.assetA,
assetB = liquidityPoolParameters.assetB,
fee = liquidityPoolParameters.fee;
if (!assetA || !(assetA instanceof _asset.Asset)) {
throw new Error('assetA is invalid');
}
if (!assetB || !(assetB instanceof _asset.Asset)) {
throw new Error('assetB is invalid');
}
if (!fee || fee !== LiquidityPoolFeeV18) {
throw new Error('fee is invalid');
}
if (_asset.Asset.compare(assetA, assetB) !== -1) {
throw new Error('Assets are not in lexicographic order');
}
var lpTypeData = _xdr2.default.LiquidityPoolType.liquidityPoolConstantProduct().toXDR();
var lpParamsData = new _xdr2.default.LiquidityPoolConstantProductParameters({
assetA: assetA.toXDRObject(),
assetB: assetB.toXDRObject(),
fee: fee
}).toXDR();
var payload = Buffer.concat([lpTypeData, lpParamsData]);
return (0, _hashing.hash)(payload);
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _int = __webpack_require__(32);
Object.keys(_int).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _int[key];
}
});
});
var _hyper = __webpack_require__(269);
Object.keys(_hyper).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _hyper[key];
}
});
});
var _unsignedInt = __webpack_require__(59);
Object.keys(_unsignedInt).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _unsignedInt[key];
}
});
});
var _unsignedHyper = __webpack_require__(270);
Object.keys(_unsignedHyper).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _unsignedHyper[key];
}
});
});
var _float = __webpack_require__(271);
Object.keys(_float).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _float[key];
}
});
});
var _double = __webpack_require__(272);
Object.keys(_double).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _double[key];
}
});
});
var _quadruple = __webpack_require__(273);
Object.keys(_quadruple).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _quadruple[key];
}
});
});
var _bool = __webpack_require__(127);
Object.keys(_bool).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _bool[key];
}
});
});
var _string = __webpack_require__(275);
Object.keys(_string).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _string[key];
}
});
});
var _opaque = __webpack_require__(276);
Object.keys(_opaque).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _opaque[key];
}
});
});
var _varOpaque = __webpack_require__(277);
Object.keys(_varOpaque).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _varOpaque[key];
}
});
});
var _array = __webpack_require__(278);
Object.keys(_array).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _array[key];
}
});
});
var _varArray = __webpack_require__(283);
Object.keys(_varArray).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _varArray[key];
}
});
});
var _option = __webpack_require__(284);
Object.keys(_option).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _option[key];
}
});
});
var _void = __webpack_require__(133);
Object.keys(_void).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _void[key];
}
});
});
var _enum = __webpack_require__(285);
Object.keys(_enum).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _enum[key];
}
});
});
var _struct = __webpack_require__(288);
Object.keys(_struct).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _struct[key];
}
});
});
var _union = __webpack_require__(291);
Object.keys(_union).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _union[key];
}
});
});
/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(72),
eq = __webpack_require__(43);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
module.exports = assignValue;
/***/ }),
/* 107 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(26);
var defineProperty = (function() {
try {
var func = getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
module.exports = defineProperty;
/***/ }),
/* 108 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var funcProto = Function.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
module.exports = toSource;
/***/ }),
/* 109 */
/***/ (function(module, exports, __webpack_require__) {
var baseRest = __webpack_require__(206),
isIterateeCall = __webpack_require__(110);
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return baseRest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = (assigner.length > 3 && typeof customizer == 'function')
? (length--, customizer)
: undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
module.exports = createAssigner;
/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {
var eq = __webpack_require__(43),
isArrayLike = __webpack_require__(25),
isIndex = __webpack_require__(68),
isObject = __webpack_require__(18);
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq(object[index], value);
}
return false;
}
module.exports = isIterateeCall;
/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {
var isPrototype = __webpack_require__(49),
nativeKeys = __webpack_require__(217);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
module.exports = baseKeys;
/***/ }),
/* 112 */
/***/ (function(module, exports) {
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
module.exports = overArg;
/***/ }),
/* 113 */
/***/ (function(module, exports, __webpack_require__) {
var baseMatches = __webpack_require__(219),
baseMatchesProperty = __webpack_require__(259),
identity = __webpack_require__(46),
isArray = __webpack_require__(3),
property = __webpack_require__(267);
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity;
}
if (typeof value == 'object') {
return isArray(value)
? baseMatchesProperty(value[0], value[1])
: baseMatches(value);
}
return property(value);
}
module.exports = baseIteratee;
/***/ }),
/* 114 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsEqualDeep = __webpack_require__(243),
isObjectLike = __webpack_require__(12);
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
module.exports = baseIsEqual;
/***/ }),
/* 115 */
/***/ (function(module, exports, __webpack_require__) {
var SetCache = __webpack_require__(244),
arraySome = __webpack_require__(247),
cacheHas = __webpack_require__(248);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Check that cyclic values are equal.
var arrStacked = stack.get(array);
var othStacked = stack.get(other);
if (arrStacked && othStacked) {
return arrStacked == other && othStacked == array;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
module.exports = equalArrays;
/***/ }),
/* 116 */
/***/ (function(module, exports, __webpack_require__) {
var root = __webpack_require__(14);
/** Built-in value references. */
var Uint8Array = root.Uint8Array;
module.exports = Uint8Array;
/***/ }),
/* 117 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetAllKeys = __webpack_require__(118),
getSymbols = __webpack_require__(77),
keys = __webpack_require__(34);
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
module.exports = getAllKeys;
/***/ }),
/* 118 */
/***/ (function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(119),
isArray = __webpack_require__(3);
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
module.exports = baseGetAllKeys;
/***/ }),
/* 119 */
/***/ (function(module, exports) {
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
module.exports = arrayPush;
/***/ }),
/* 120 */
/***/ (function(module, exports) {
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
module.exports = stubArray;
/***/ }),
/* 121 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(18);
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
module.exports = isStrictComparable;
/***/ }),
/* 122 */
/***/ (function(module, exports) {
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
module.exports = matchesStrictComparable;
/***/ }),
/* 123 */
/***/ (function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(124),
toKey = __webpack_require__(58);
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = castPath(path, object);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[toKey(path[index++])];
}
return (index && index == length) ? object : undefined;
}
module.exports = baseGet;
/***/ }),
/* 124 */
/***/ (function(module, exports, __webpack_require__) {
var isArray = __webpack_require__(3),
isKey = __webpack_require__(78),
stringToPath = __webpack_require__(261),
toString = __webpack_require__(79);
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value, object) {
if (isArray(value)) {
return value;
}
return isKey(value, object) ? [value] : stringToPath(toString(value));
}
module.exports = castPath;
/***/ }),
/* 125 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
module.exports = baseProperty;
/***/ }),
/* 126 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*
Copyright 2013 Daniel Wirtz <dcode@dcode.io>
Copyright 2009 The Closure Library Authors. All Rights Reserved.
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.
*/
/**
* @license Long.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
* Released under the Apache License, Version 2.0
* see: https://github.com/dcodeIO/Long.js for details
*/
(function(global, factory) {
/* AMD */ if (true)
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
/* CommonJS */ else {}
})(this, function() {
"use strict";
/**
* Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
* See the from* functions below for more convenient ways of constructing Longs.
* @exports Long
* @class A Long class for representing a 64 bit two's-complement integer value.
* @param {number} low The low (signed) 32 bits of the long
* @param {number} high The high (signed) 32 bits of the long
* @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
* @constructor
*/
function Long(low, high, unsigned) {
/**
* The low 32 bits as a signed value.
* @type {number}
* @expose
*/
this.low = low|0;
/**
* The high 32 bits as a signed value.
* @type {number}
* @expose
*/
this.high = high|0;
/**
* Whether unsigned or not.
* @type {boolean}
* @expose
*/
this.unsigned = !!unsigned;
}
// The internal representation of a long is the two given signed, 32-bit values.
// We use 32-bit pieces because these are the size of integers on which
// Javascript performs bit-operations. For operations like addition and
// multiplication, we split each number into 16 bit pieces, which can easily be
// multiplied within Javascript's floating-point representation without overflow
// or change in sign.
//
// In the algorithms below, we frequently reduce the negative case to the
// positive case by negating the input(s) and then post-processing the result.
// Note that we must ALWAYS check specially whether those values are MIN_VALUE
// (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
// a positive number, it overflows back into a negative). Not handling this
// case would often result in infinite recursion.
//
// Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
// methods on which they depend.
/**
* An indicator used to reliably determine if an object is a Long or not.
* @type {boolean}
* @const
* @expose
* @private
*/
Long.__isLong__;
Object.defineProperty(Long.prototype, "__isLong__", {
value: true,
enumerable: false,
configurable: false
});
/**
* Tests if the specified object is a Long.
* @param {*} obj Object
* @returns {boolean}
* @expose
*/
Long.isLong = function isLong(obj) {
return (obj && obj["__isLong__"]) === true;
};
/**
* A cache of the Long representations of small integer values.
* @type {!Object}
* @inner
*/
var INT_CACHE = {};
/**
* A cache of the Long representations of small unsigned integer values.
* @type {!Object}
* @inner
*/
var UINT_CACHE = {};
/**
* Returns a Long representing the given 32 bit integer value.
* @param {number} value The 32 bit integer in question
* @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
* @returns {!Long} The corresponding Long value
* @expose
*/
Long.fromInt = function fromInt(value, unsigned) {
var obj, cachedObj;
if (!unsigned) {
value = value | 0;
if (-128 <= value && value < 128) {
cachedObj = INT_CACHE[value];
if (cachedObj)
return cachedObj;
}
obj = new Long(value, value < 0 ? -1 : 0, false);
if (-128 <= value && value < 128)
INT_CACHE[value] = obj;
return obj;
} else {
value = value >>> 0;
if (0 <= value && value < 256) {
cachedObj = UINT_CACHE[value];
if (cachedObj)
return cachedObj;
}
obj = new Long(value, (value | 0) < 0 ? -1 : 0, true);
if (0 <= value && value < 256)
UINT_CACHE[value] = obj;
return obj;
}
};
/**
* Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
* @param {number} value The number in question
* @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
* @returns {!Long} The corresponding Long value
* @expose
*/
Long.fromNumber = function fromNumber(value, unsigned) {
unsigned = !!unsigned;
if (isNaN(value) || !isFinite(value))
return Long.ZERO;
if (!unsigned && value <= -TWO_PWR_63_DBL)
return Long.MIN_VALUE;
if (!unsigned && value + 1 >= TWO_PWR_63_DBL)
return Long.MAX_VALUE;
if (unsigned && value >= TWO_PWR_64_DBL)
return Long.MAX_UNSIGNED_VALUE;
if (value < 0)
return Long.fromNumber(-value, unsigned).negate();
return new Long((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
};
/**
* Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
* assumed to use 32 bits.
* @param {number} lowBits The low 32 bits
* @param {number} highBits The high 32 bits
* @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
* @returns {!Long} The corresponding Long value
* @expose
*/
Long.fromBits = function fromBits(lowBits, highBits, unsigned) {
return new Long(lowBits, highBits, unsigned);
};
/**
* Returns a Long representation of the given string, written using the specified radix.
* @param {string} str The textual representation of the Long
* @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to `false` for signed
* @param {number=} radix The radix in which the text is written (2-36), defaults to 10
* @returns {!Long} The corresponding Long value
* @expose
*/
Long.fromString = function fromString(str, unsigned, radix) {
if (str.length === 0)
throw Error('number format error: empty string');
if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
return Long.ZERO;
if (typeof unsigned === 'number') // For goog.math.long compatibility
radix = unsigned,
unsigned = false;
radix = radix || 10;
if (radix < 2 || 36 < radix)
throw Error('radix out of range: ' + radix);
var p;
if ((p = str.indexOf('-')) > 0)
throw Error('number format error: interior "-" character: ' + str);
else if (p === 0)
return Long.fromString(str.substring(1), unsigned, radix).negate();
// Do several (8) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = Long.fromNumber(Math.pow(radix, 8));
var result = Long.ZERO;
for (var i = 0; i < str.length; i += 8) {
var size = Math.min(8, str.length - i);
var value = parseInt(str.substring(i, i + size), radix);
if (size < 8) {
var power = Long.fromNumber(Math.pow(radix, size));
result = result.multiply(power).add(Long.fromNumber(value));
} else {
result = result.multiply(radixToPower);
result = result.add(Long.fromNumber(value));
}
}
result.unsigned = unsigned;
return result;
};
/**
* Converts the specified value to a Long.
* @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
* @returns {!Long}
* @expose
*/
Long.fromValue = function fromValue(val) {
if (val /* is compatible */ instanceof Long)
return val;
if (typeof val === 'number')
return Long.fromNumber(val);
if (typeof val === 'string')
return Long.fromString(val);
// Throws for non-objects, converts non-instanceof Long:
return new Long(val.low, val.high, val.unsigned);
};
// NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
// no runtime penalty for these.
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_16_DBL = 1 << 16;
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_24_DBL = 1 << 24;
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
/**
* @type {number}
* @const
* @inner
*/
var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
/**
* @type {!Long}
* @const
* @inner
*/
var TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
/**
* Signed zero.
* @type {!Long}
* @expose
*/
Long.ZERO = Long.fromInt(0);
/**
* Unsigned zero.
* @type {!Long}
* @expose
*/
Long.UZERO = Long.fromInt(0, true);
/**
* Signed one.
* @type {!Long}
* @expose
*/
Long.ONE = Long.fromInt(1);
/**
* Unsigned one.
* @type {!Long}
* @expose
*/
Long.UONE = Long.fromInt(1, true);
/**
* Signed negative one.
* @type {!Long}
* @expose
*/
Long.NEG_ONE = Long.fromInt(-1);
/**
* Maximum signed value.
* @type {!Long}
* @expose
*/
Long.MAX_VALUE = Long.fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);
/**
* Maximum unsigned value.
* @type {!Long}
* @expose
*/
Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);
/**
* Minimum signed value.
* @type {!Long}
* @expose
*/
Long.MIN_VALUE = Long.fromBits(0, 0x80000000|0, false);
/**
* Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
* @returns {number}
* @expose
*/
Long.prototype.toInt = function toInt() {
return this.unsigned ? this.low >>> 0 : this.low;
};
/**
* Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
* @returns {number}
* @expose
*/
Long.prototype.toNumber = function toNumber() {
if (this.unsigned) {
return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
}
return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
};
/**
* Converts the Long to a string written in the specified radix.
* @param {number=} radix Radix (2-36), defaults to 10
* @returns {string}
* @override
* @throws {RangeError} If `radix` is out of range
* @expose
*/
Long.prototype.toString = function toString(radix) {
radix = radix || 10;
if (radix < 2 || 36 < radix)
throw RangeError('radix out of range: ' + radix);
if (this.isZero())
return '0';
var rem;
if (this.isNegative()) { // Unsigned Longs are never negative
if (this.equals(Long.MIN_VALUE)) {
// We need to change the Long value before it can be negated, so we remove
// the bottom-most digit in this base and then recurse to do the rest.
var radixLong = Long.fromNumber(radix);
var div = this.divide(radixLong);
rem = div.multiply(radixLong).subtract(this);
return div.toString(radix) + rem.toInt().toString(radix);
} else
return '-' + this.negate().toString(radix);
}
// Do several (6) digits each time through the loop, so as to
// minimize the calls to the very expensive emulated div.
var radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
rem = this;
var result = '';
while (true) {
var remDiv = rem.divide(radixToPower),
intval = rem.subtract(remDiv.multiply(radixToPower)).toInt() >>> 0,
digits = intval.toString(radix);
rem = remDiv;
if (rem.isZero())
return digits + result;
else {
while (digits.length < 6)
digits = '0' + digits;
result = '' + digits + result;
}
}
};
/**
* Gets the high 32 bits as a signed integer.
* @returns {number} Signed high bits
* @expose
*/
Long.prototype.getHighBits = function getHighBits() {
return this.high;
};
/**
* Gets the high 32 bits as an unsigned integer.
* @returns {number} Unsigned high bits
* @expose
*/
Long.prototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
return this.high >>> 0;
};
/**
* Gets the low 32 bits as a signed integer.
* @returns {number} Signed low bits
* @expose
*/
Long.prototype.getLowBits = function getLowBits() {
return this.low;
};
/**
* Gets the low 32 bits as an unsigned integer.
* @returns {number} Unsigned low bits
* @expose
*/
Long.prototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
return this.low >>> 0;
};
/**
* Gets the number of bits needed to represent the absolute value of this Long.
* @returns {number}
* @expose
*/
Long.prototype.getNumBitsAbs = function getNumBitsAbs() {
if (this.isNegative()) // Unsigned Longs are never negative
return this.equals(Long.MIN_VALUE) ? 64 : this.negate().getNumBitsAbs();
var val = this.high != 0 ? this.high : this.low;
for (var bit = 31; bit > 0; bit--)
if ((val & (1 << bit)) != 0)
break;
return this.high != 0 ? bit + 33 : bit + 1;
};
/**
* Tests if this Long's value equals zero.
* @returns {boolean}
* @expose
*/
Long.prototype.isZero = function isZero() {
return this.high === 0 && this.low === 0;
};
/**
* Tests if this Long's value is negative.
* @returns {boolean}
* @expose
*/
Long.prototype.isNegative = function isNegative() {
return !this.unsigned && this.high < 0;
};
/**
* Tests if this Long's value is positive.
* @returns {boolean}
* @expose
*/
Long.prototype.isPositive = function isPositive() {
return this.unsigned || this.high >= 0;
};
/**
* Tests if this Long's value is odd.
* @returns {boolean}
* @expose
*/
Long.prototype.isOdd = function isOdd() {
return (this.low & 1) === 1;
};
/**
* Tests if this Long's value is even.
* @returns {boolean}
* @expose
*/
Long.prototype.isEven = function isEven() {
return (this.low & 1) === 0;
};
/**
* Tests if this Long's value equals the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
* @expose
*/
Long.prototype.equals = function equals(other) {
if (!Long.isLong(other))
other = Long.fromValue(other);
if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
return false;
return this.high === other.high && this.low === other.low;
};
/**
* Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
* @expose
*/
Long.eq = Long.prototype.equals;
/**
* Tests if this Long's value differs from the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
* @expose
*/
Long.prototype.notEquals = function notEquals(other) {
return !this.equals(/* validates */ other);
};
/**
* Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
* @expose
*/
Long.neq = Long.prototype.notEquals;
/**
* Tests if this Long's value is less than the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
* @expose
*/
Long.prototype.lessThan = function lessThan(other) {
return this.compare(/* validates */ other) < 0;
};
/**
* Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
* @expose
*/
Long.prototype.lt = Long.prototype.lessThan;
/**
* Tests if this Long's value is less than or equal the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
* @expose
*/
Long.prototype.lessThanOrEqual = function lessThanOrEqual(other) {
return this.compare(/* validates */ other) <= 0;
};
/**
* Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
* @expose
*/
Long.prototype.lte = Long.prototype.lessThanOrEqual;
/**
* Tests if this Long's value is greater than the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
* @expose
*/
Long.prototype.greaterThan = function greaterThan(other) {
return this.compare(/* validates */ other) > 0;
};
/**
* Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
* @expose
*/
Long.prototype.gt = Long.prototype.greaterThan;
/**
* Tests if this Long's value is greater than or equal the specified's.
* @param {!Long|number|string} other Other value
* @returns {boolean}
* @expose
*/
Long.prototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
return this.compare(/* validates */ other) >= 0;
};
/**
* Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
* @function
* @param {!Long|number|string} other Other value
* @returns {boolean}
* @expose
*/
Long.prototype.gte = Long.prototype.greaterThanOrEqual;
/**
* Compares this Long's value with the specified's.
* @param {!Long|number|string} other Other value
* @returns {number} 0 if they are the same, 1 if the this is greater and -1
* if the given one is greater
* @expose
*/
Long.prototype.compare = function compare(other) {
if (!Long.isLong(other))
other = Long.fromValue(other);
if (this.equals(other))
return 0;
var thisNeg = this.isNegative(),
otherNeg = other.isNegative();
if (thisNeg && !otherNeg)
return -1;
if (!thisNeg && otherNeg)
return 1;
// At this point the sign bits are the same
if (!this.unsigned)
return this.subtract(other).isNegative() ? -1 : 1;
// Both are positive if at least one is unsigned
return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
};
/**
* Negates this Long's value.
* @returns {!Long} Negated Long
* @expose
*/
Long.prototype.negate = function negate() {
if (!this.unsigned && this.equals(Long.MIN_VALUE))
return Long.MIN_VALUE;
return this.not().add(Long.ONE);
};
/**
* Negates this Long's value. This is an alias of {@link Long#negate}.
* @function
* @returns {!Long} Negated Long
* @expose
*/
Long.prototype.neg = Long.prototype.negate;
/**
* Returns the sum of this and the specified Long.
* @param {!Long|number|string} addend Addend
* @returns {!Long} Sum
* @expose
*/
Long.prototype.add = function add(addend) {
if (!Long.isLong(addend))
addend = Long.fromValue(addend);
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
var a48 = this.high >>> 16;
var a32 = this.high & 0xFFFF;
var a16 = this.low >>> 16;
var a00 = this.low & 0xFFFF;
var b48 = addend.high >>> 16;
var b32 = addend.high & 0xFFFF;
var b16 = addend.low >>> 16;
var b00 = addend.low & 0xFFFF;
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
c00 += a00 + b00;
c16 += c00 >>> 16;
c00 &= 0xFFFF;
c16 += a16 + b16;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c32 += a32 + b32;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c48 += a48 + b48;
c48 &= 0xFFFF;
return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
};
/**
* Returns the difference of this and the specified Long.
* @param {!Long|number|string} subtrahend Subtrahend
* @returns {!Long} Difference
* @expose
*/
Long.prototype.subtract = function subtract(subtrahend) {
if (!Long.isLong(subtrahend))
subtrahend = Long.fromValue(subtrahend);
return this.add(subtrahend.negate());
};
/**
* Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
* @function
* @param {!Long|number|string} subtrahend Subtrahend
* @returns {!Long} Difference
* @expose
*/
Long.prototype.sub = Long.prototype.subtract;
/**
* Returns the product of this and the specified Long.
* @param {!Long|number|string} multiplier Multiplier
* @returns {!Long} Product
* @expose
*/
Long.prototype.multiply = function multiply(multiplier) {
if (this.isZero())
return Long.ZERO;
if (!Long.isLong(multiplier))
multiplier = Long.fromValue(multiplier);
if (multiplier.isZero())
return Long.ZERO;
if (this.equals(Long.MIN_VALUE))
return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
if (multiplier.equals(Long.MIN_VALUE))
return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
if (this.isNegative()) {
if (multiplier.isNegative())
return this.negate().multiply(multiplier.negate());
else
return this.negate().multiply(multiplier).negate();
} else if (multiplier.isNegative())
return this.multiply(multiplier.negate()).negate();
// If both longs are small, use float multiplication
if (this.lessThan(TWO_PWR_24) && multiplier.lessThan(TWO_PWR_24))
return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
// Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
// We can skip products that would overflow.
var a48 = this.high >>> 16;
var a32 = this.high & 0xFFFF;
var a16 = this.low >>> 16;
var a00 = this.low & 0xFFFF;
var b48 = multiplier.high >>> 16;
var b32 = multiplier.high & 0xFFFF;
var b16 = multiplier.low >>> 16;
var b00 = multiplier.low & 0xFFFF;
var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
c00 += a00 * b00;
c16 += c00 >>> 16;
c00 &= 0xFFFF;
c16 += a16 * b00;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c16 += a00 * b16;
c32 += c16 >>> 16;
c16 &= 0xFFFF;
c32 += a32 * b00;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c32 += a16 * b16;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c32 += a00 * b32;
c48 += c32 >>> 16;
c32 &= 0xFFFF;
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
c48 &= 0xFFFF;
return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
};
/**
* Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
* @function
* @param {!Long|number|string} multiplier Multiplier
* @returns {!Long} Product
* @expose
*/
Long.prototype.mul = Long.prototype.multiply;
/**
* Returns this Long divided by the specified.
* @param {!Long|number|string} divisor Divisor
* @returns {!Long} Quotient
* @expose
*/
Long.prototype.divide = function divide(divisor) {
if (!Long.isLong(divisor))
divisor = Long.fromValue(divisor);
if (divisor.isZero())
throw(new Error('division by zero'));
if (this.isZero())
return this.unsigned ? Long.UZERO : Long.ZERO;
var approx, rem, res;
if (this.equals(Long.MIN_VALUE)) {
if (divisor.equals(Long.ONE) || divisor.equals(Long.NEG_ONE))
return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
else if (divisor.equals(Long.MIN_VALUE))
return Long.ONE;
else {
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
var halfThis = this.shiftRight(1);
approx = halfThis.divide(divisor).shiftLeft(1);
if (approx.equals(Long.ZERO)) {
return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
} else {
rem = this.subtract(divisor.multiply(approx));
res = approx.add(rem.divide(divisor));
return res;
}
}
} else if (divisor.equals(Long.MIN_VALUE))
return this.unsigned ? Long.UZERO : Long.ZERO;
if (this.isNegative()) {
if (divisor.isNegative())
return this.negate().divide(divisor.negate());
return this.negate().divide(divisor).negate();
} else if (divisor.isNegative())
return this.divide(divisor.negate()).negate();
// Repeat the following until the remainder is less than other: find a
// floating-point that approximates remainder / other *from below*, add this
// into the result, and subtract it from the remainder. It is critical that
// the approximate value is less than or equal to the real value so that the
// remainder never becomes negative.
res = Long.ZERO;
rem = this;
while (rem.greaterThanOrEqual(divisor)) {
// Approximate the result of division. This may be a little greater or
// smaller than the actual value.
approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
// We will tweak the approximate result by changing it in the 48-th digit or
// the smallest non-fractional digit, whichever is larger.
var log2 = Math.ceil(Math.log(approx) / Math.LN2),
delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48),
// Decrease the approximation until it is smaller than the remainder. Note
// that if it is too large, the product overflows and is negative.
approxRes = Long.fromNumber(approx),
approxRem = approxRes.multiply(divisor);
while (approxRem.isNegative() || approxRem.greaterThan(rem)) {
approx -= delta;
approxRes = Long.fromNumber(approx, this.unsigned);
approxRem = approxRes.multiply(divisor);
}
// We know the answer can't be zero... and actually, zero would cause
// infinite recursion since we would make no progress.
if (approxRes.isZero())
approxRes = Long.ONE;
res = res.add(approxRes);
rem = rem.subtract(approxRem);
}
return res;
};
/**
* Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
* @function
* @param {!Long|number|string} divisor Divisor
* @returns {!Long} Quotient
* @expose
*/
Long.prototype.div = Long.prototype.divide;
/**
* Returns this Long modulo the specified.
* @param {!Long|number|string} divisor Divisor
* @returns {!Long} Remainder
* @expose
*/
Long.prototype.modulo = function modulo(divisor) {
if (!Long.isLong(divisor))
divisor = Long.fromValue(divisor);
return this.subtract(this.divide(divisor).multiply(divisor));
};
/**
* Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
* @function
* @param {!Long|number|string} divisor Divisor
* @returns {!Long} Remainder
* @expose
*/
Long.prototype.mod = Long.prototype.modulo;
/**
* Returns the bitwise NOT of this Long.
* @returns {!Long}
* @expose
*/
Long.prototype.not = function not() {
return Long.fromBits(~this.low, ~this.high, this.unsigned);
};
/**
* Returns the bitwise AND of this Long and the specified.
* @param {!Long|number|string} other Other Long
* @returns {!Long}
* @expose
*/
Long.prototype.and = function and(other) {
if (!Long.isLong(other))
other = Long.fromValue(other);
return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
};
/**
* Returns the bitwise OR of this Long and the specified.
* @param {!Long|number|string} other Other Long
* @returns {!Long}
* @expose
*/
Long.prototype.or = function or(other) {
if (!Long.isLong(other))
other = Long.fromValue(other);
return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
};
/**
* Returns the bitwise XOR of this Long and the given one.
* @param {!Long|number|string} other Other Long
* @returns {!Long}
* @expose
*/
Long.prototype.xor = function xor(other) {
if (!Long.isLong(other))
other = Long.fromValue(other);
return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
};
/**
* Returns this Long with bits shifted to the left by the given amount.
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
* @expose
*/
Long.prototype.shiftLeft = function shiftLeft(numBits) {
if (Long.isLong(numBits))
numBits = numBits.toInt();
if ((numBits &= 63) === 0)
return this;
else if (numBits < 32)
return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
else
return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
};
/**
* Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
* @function
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
* @expose
*/
Long.prototype.shl = Long.prototype.shiftLeft;
/**
* Returns this Long with bits arithmetically shifted to the right by the given amount.
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
* @expose
*/
Long.prototype.shiftRight = function shiftRight(numBits) {
if (Long.isLong(numBits))
numBits = numBits.toInt();
if ((numBits &= 63) === 0)
return this;
else if (numBits < 32)
return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
else
return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
};
/**
* Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
* @function
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
* @expose
*/
Long.prototype.shr = Long.prototype.shiftRight;
/**
* Returns this Long with bits logically shifted to the right by the given amount.
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
* @expose
*/
Long.prototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
if (Long.isLong(numBits))
numBits = numBits.toInt();
numBits &= 63;
if (numBits === 0)
return this;
else {
var high = this.high;
if (numBits < 32) {
var low = this.low;
return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
} else if (numBits === 32)
return Long.fromBits(high, 0, this.unsigned);
else
return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
}
};
/**
* Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
* @function
* @param {number|!Long} numBits Number of bits
* @returns {!Long} Shifted Long
* @expose
*/
Long.prototype.shru = Long.prototype.shiftRightUnsigned;
/**
* Converts this Long to signed.
* @returns {!Long} Signed long
* @expose
*/
Long.prototype.toSigned = function toSigned() {
if (!this.unsigned)
return this;
return new Long(this.low, this.high, false);
};
/**
* Converts this Long to unsigned.
* @returns {!Long} Unsigned long
* @expose
*/
Long.prototype.toUnsigned = function toUnsigned() {
if (this.unsigned)
return this;
return new Long(this.low, this.high, true);
};
return Long;
});
/***/ }),
/* 127 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Bool = undefined;
var _isBoolean = __webpack_require__(274);
var _isBoolean2 = _interopRequireDefault(_isBoolean);
var _int = __webpack_require__(32);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Bool = exports.Bool = {
read: function read(io) {
var value = _int.Int.read(io);
switch (value) {
case 0:
return false;
case 1:
return true;
default:
throw new Error('XDR Read Error: Got ' + value + ' when trying to read a bool');
}
},
write: function write(value, io) {
var intVal = value ? 1 : 0;
return _int.Int.write(intVal, io);
},
isValid: function isValid(value) {
return (0, _isBoolean2.default)(value);
}
};
(0, _ioMixin2.default)(Bool);
/***/ }),
/* 128 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
module.exports = arrayEach;
/***/ }),
/* 129 */
/***/ (function(module, exports, __webpack_require__) {
var baseTimes = __webpack_require__(97),
castFunction = __webpack_require__(67),
toInteger = __webpack_require__(130);
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMin = Math.min;
/**
* Invokes the iteratee `n` times, returning an array of the results of
* each invocation. The iteratee is invoked with one argument; (index).
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of results.
* @example
*
* _.times(3, String);
* // => ['0', '1', '2']
*
* _.times(4, _.constant(0));
* // => [0, 0, 0, 0]
*/
function times(n, iteratee) {
n = toInteger(n);
if (n < 1 || n > MAX_SAFE_INTEGER) {
return [];
}
var index = MAX_ARRAY_LENGTH,
length = nativeMin(n, MAX_ARRAY_LENGTH);
iteratee = castFunction(iteratee);
n -= MAX_ARRAY_LENGTH;
var result = baseTimes(length, iteratee);
while (++index < n) {
iteratee(index);
}
return result;
}
module.exports = times;
/***/ }),
/* 130 */
/***/ (function(module, exports, __webpack_require__) {
var toFinite = __webpack_require__(280);
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
module.exports = toInteger;
/***/ }),
/* 131 */
/***/ (function(module, exports) {
/** Used to match a single whitespace character. */
var reWhitespace = /\s/;
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
* character of `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the index of the last non-whitespace character.
*/
function trimmedEndIndex(string) {
var index = string.length;
while (index-- && reWhitespace.test(string.charAt(index))) {}
return index;
}
module.exports = trimmedEndIndex;
/***/ }),
/* 132 */
/***/ (function(module, exports) {
/**
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(void 0);
* // => false
*/
function isNull(value) {
return value === null;
}
module.exports = isNull;
/***/ }),
/* 133 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Void = undefined;
var _isUndefined = __webpack_require__(7);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Void = exports.Void = {
/* jshint unused: false */
read: function read() {
return undefined;
},
write: function write(value) {
if (!(0, _isUndefined2.default)(value)) {
throw new Error('XDR Write Error: trying to write value to a void slot');
}
},
isValid: function isValid(value) {
return (0, _isUndefined2.default)(value);
}
};
(0, _ioMixin2.default)(Void);
/***/ }),
/* 134 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(81),
baseIteratee = __webpack_require__(113),
baseMap = __webpack_require__(289),
isArray = __webpack_require__(3);
/**
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee) {
var func = isArray(collection) ? arrayMap : baseMap;
return func(collection, baseIteratee(iteratee, 3));
}
module.exports = map;
/***/ }),
/* 135 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(14);
/** Detect free variable `exports`. */
var freeExports = true && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Built-in value references. */
var Buffer = moduleExports ? root.Buffer : undefined,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
module.exports = cloneBuffer;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(41)(module)))
/***/ }),
/* 136 */
/***/ (function(module, exports) {
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
module.exports = copyArray;
/***/ }),
/* 137 */
/***/ (function(module, exports, __webpack_require__) {
var arrayPush = __webpack_require__(119),
getPrototype = __webpack_require__(83),
getSymbols = __webpack_require__(77),
stubArray = __webpack_require__(120);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetSymbols = Object.getOwnPropertySymbols;
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
var result = [];
while (object) {
arrayPush(result, getSymbols(object));
object = getPrototype(object);
}
return result;
};
module.exports = getSymbolsIn;
/***/ }),
/* 138 */
/***/ (function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(84);
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
module.exports = cloneTypedArray;
/***/ }),
/* 139 */
/***/ (function(module, exports, __webpack_require__) {
var baseCreate = __webpack_require__(304),
getPrototype = __webpack_require__(83),
isPrototype = __webpack_require__(49);
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !isPrototype(object))
? baseCreate(getPrototype(object))
: {};
}
module.exports = initCloneObject;
/***/ }),
/* 140 */
/***/ (function(module, exports, __webpack_require__) {
var createPadding = __webpack_require__(309),
stringSize = __webpack_require__(142),
toInteger = __webpack_require__(130),
toString = __webpack_require__(79);
/**
* Pads `string` on the right side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padEnd('abc', 6);
* // => 'abc '
*
* _.padEnd('abc', 6, '_-');
* // => 'abc_-_'
*
* _.padEnd('abc', 3);
* // => 'abc'
*/
function padEnd(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
return (length && strLength < length)
? (string + createPadding(length - strLength, chars))
: string;
}
module.exports = padEnd;
/***/ }),
/* 141 */
/***/ (function(module, exports, __webpack_require__) {
var baseSlice = __webpack_require__(311);
/**
* Casts `array` to a slice if it's needed.
*
* @private
* @param {Array} array The array to inspect.
* @param {number} start The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the cast slice.
*/
function castSlice(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (!start && end >= length) ? array : baseSlice(array, start, end);
}
module.exports = castSlice;
/***/ }),
/* 142 */
/***/ (function(module, exports, __webpack_require__) {
var asciiSize = __webpack_require__(312),
hasUnicode = __webpack_require__(85),
unicodeSize = __webpack_require__(313);
/**
* Gets the number of symbols in `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the string size.
*/
function stringSize(string) {
return hasUnicode(string)
? unicodeSize(string)
: asciiSize(string);
}
module.exports = stringSize;
/***/ }),
/* 143 */
/***/ (function(module, exports, __webpack_require__) {
var asciiToArray = __webpack_require__(314),
hasUnicode = __webpack_require__(85),
unicodeToArray = __webpack_require__(315);
/**
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function stringToArray(string) {
return hasUnicode(string)
? unicodeToArray(string)
: asciiToArray(string);
}
module.exports = stringToArray;
/***/ }),
/* 144 */
/***/ (function(module, exports, __webpack_require__) {
var baseToString = __webpack_require__(80),
castSlice = __webpack_require__(141),
charsEndIndex = __webpack_require__(316),
stringToArray = __webpack_require__(143),
toString = __webpack_require__(79),
trimmedEndIndex = __webpack_require__(131);
/**
* Removes trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimEnd(' abc ');
* // => ' abc'
*
* _.trimEnd('-_-abc-_-', '_-');
* // => '-_-abc'
*/
function trimEnd(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.slice(0, trimmedEndIndex(string) + 1);
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
return castSlice(strSymbols, 0, end).join('');
}
module.exports = trimEnd;
/***/ }),
/* 145 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Operation = exports.AuthClawbackEnabledFlag = exports.AuthImmutableFlag = exports.AuthRevocableFlag = exports.AuthRequiredFlag = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /* eslint-disable no-bitwise */
var _jsXdr = __webpack_require__(22);
var _bignumber = __webpack_require__(23);
var _bignumber2 = _interopRequireDefault(_bignumber);
var _trimEnd = __webpack_require__(144);
var _trimEnd2 = _interopRequireDefault(_trimEnd);
var _isUndefined = __webpack_require__(7);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _isString = __webpack_require__(9);
var _isString2 = _interopRequireDefault(_isString);
var _isNumber = __webpack_require__(42);
var _isNumber2 = _interopRequireDefault(_isNumber);
var _isFinite = __webpack_require__(335);
var _isFinite2 = _interopRequireDefault(_isFinite);
var _continued_fraction = __webpack_require__(336);
var _asset = __webpack_require__(27);
var _liquidity_pool_asset = __webpack_require__(88);
var _claimant = __webpack_require__(146);
var _strkey = __webpack_require__(8);
var _liquidity_pool_id = __webpack_require__(89);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _index = __webpack_require__(337);
var ops = _interopRequireWildcard(_index);
var _decode_encode_muxed_account = __webpack_require__(17);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var ONE = 10000000;
var MAX_INT64 = '9223372036854775807';
/**
* When set using `{@link Operation.setOptions}` option, requires the issuing
* account to give other accounts permission before they can hold the issuing
* account’s credit.
*
* @constant
* @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags)
*/
var AuthRequiredFlag = exports.AuthRequiredFlag = 1 << 0;
/**
* When set using `{@link Operation.setOptions}` option, allows the issuing
* account to revoke its credit held by other accounts.
*
* @constant
* @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags)
*/
var AuthRevocableFlag = exports.AuthRevocableFlag = 1 << 1;
/**
* When set using `{@link Operation.setOptions}` option, then none of the
* authorization flags can be set and the account can never be deleted.
*
* @constant
* @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags)
*/
var AuthImmutableFlag = exports.AuthImmutableFlag = 1 << 2;
/**
* When set using `{@link Operation.setOptions}` option, then any trustlines
* created by this account can have a ClawbackOp operation submitted for the
* corresponding asset.
*
* @constant
* @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags)
*/
var AuthClawbackEnabledFlag = exports.AuthClawbackEnabledFlag = 1 << 3;
/**
* `Operation` class represents [operations](https://developers.stellar.org/docs/glossary/operations/) in Stellar network.
* Use one of static methods to create operations:
* * `{@link Operation.createAccount}`
* * `{@link Operation.payment}`
* * `{@link Operation.pathPaymentStrictReceive}`
* * `{@link Operation.pathPaymentStrictSend}`
* * `{@link Operation.manageSellOffer}`
* * `{@link Operation.manageBuyOffer}`
* * `{@link Operation.createPassiveSellOffer}`
* * `{@link Operation.setOptions}`
* * `{@link Operation.changeTrust}`
* * `{@link Operation.allowTrust}`
* * `{@link Operation.accountMerge}`
* * `{@link Operation.inflation}`
* * `{@link Operation.manageData}`
* * `{@link Operation.bumpSequence}`
* * `{@link Operation.createClaimableBalance}`
* * `{@link Operation.claimClaimableBalance}`
* * `{@link Operation.beginSponsoringFutureReserves}`
* * `{@link Operation.endSponsoringFutureReserves}`
* * `{@link Operation.revokeAccountSponsorship}`
* * `{@link Operation.revokeTrustlineSponsorship}`
* * `{@link Operation.revokeOfferSponsorship}`
* * `{@link Operation.revokeDataSponsorship}`
* * `{@link Operation.revokeClaimableBalanceSponsorship}`
* * `{@link Operation.revokeLiquidityPoolSponsorship}`
* * `{@link Operation.revokeSignerSponsorship}`
* * `{@link Operation.clawback}`
* * `{@link Operation.clawbackClaimableBalance}`
* * `{@link Operation.setTrustLineFlags}`
* * `{@link Operation.liquidityPoolDeposit}`
* * `{@link Operation.liquidityPoolWithdraw}`
*
* @class Operation
*/
var Operation = exports.Operation = function () {
function Operation() {
_classCallCheck(this, Operation);
}
_createClass(Operation, null, [{
key: 'setSourceAccount',
value: function setSourceAccount(opAttributes, opts) {
if (opts.source) {
try {
opAttributes.sourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.source);
} catch (e) {
throw new Error('Source address is invalid');
}
}
}
/**
* Deconstructs the raw XDR operation object into the structured object that
* was used to create the operation (i.e. the `opts` parameter to most ops).
*
* @param {xdr.Operation} operation - An XDR Operation.
* @return {Operation}
*/
}, {
key: 'fromXDRObject',
value: function fromXDRObject(operation) {
var result = {};
if (operation.sourceAccount()) {
result.source = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(operation.sourceAccount());
}
var attrs = operation.body().value();
var operationName = operation.body().switch().name;
switch (operationName) {
case 'createAccount':
{
result.type = 'createAccount';
result.destination = accountIdtoAddress(attrs.destination());
result.startingBalance = this._fromXDRAmount(attrs.startingBalance());
break;
}
case 'payment':
{
result.type = 'payment';
result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination());
result.asset = _asset.Asset.fromOperation(attrs.asset());
result.amount = this._fromXDRAmount(attrs.amount());
break;
}
case 'pathPaymentStrictReceive':
{
result.type = 'pathPaymentStrictReceive';
result.sendAsset = _asset.Asset.fromOperation(attrs.sendAsset());
result.sendMax = this._fromXDRAmount(attrs.sendMax());
result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination());
result.destAsset = _asset.Asset.fromOperation(attrs.destAsset());
result.destAmount = this._fromXDRAmount(attrs.destAmount());
result.path = [];
var path = attrs.path();
// note that Object.values isn't supported by node 6!
Object.keys(path).forEach(function (pathKey) {
result.path.push(_asset.Asset.fromOperation(path[pathKey]));
});
break;
}
case 'pathPaymentStrictSend':
{
result.type = 'pathPaymentStrictSend';
result.sendAsset = _asset.Asset.fromOperation(attrs.sendAsset());
result.sendAmount = this._fromXDRAmount(attrs.sendAmount());
result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.destination());
result.destAsset = _asset.Asset.fromOperation(attrs.destAsset());
result.destMin = this._fromXDRAmount(attrs.destMin());
result.path = [];
var _path = attrs.path();
// note that Object.values isn't supported by node 6!
Object.keys(_path).forEach(function (pathKey) {
result.path.push(_asset.Asset.fromOperation(_path[pathKey]));
});
break;
}
case 'changeTrust':
{
result.type = 'changeTrust';
switch (attrs.line().switch()) {
case _xdr2.default.AssetType.assetTypePoolShare():
result.line = _liquidity_pool_asset.LiquidityPoolAsset.fromOperation(attrs.line());
break;
default:
result.line = _asset.Asset.fromOperation(attrs.line());
break;
}
result.limit = this._fromXDRAmount(attrs.limit());
break;
}
case 'allowTrust':
{
result.type = 'allowTrust';
result.trustor = accountIdtoAddress(attrs.trustor());
result.assetCode = attrs.asset().value().toString();
result.assetCode = (0, _trimEnd2.default)(result.assetCode, '\0');
result.authorize = attrs.authorize();
break;
}
case 'setOptions':
{
result.type = 'setOptions';
if (attrs.inflationDest()) {
result.inflationDest = accountIdtoAddress(attrs.inflationDest());
}
result.clearFlags = attrs.clearFlags();
result.setFlags = attrs.setFlags();
result.masterWeight = attrs.masterWeight();
result.lowThreshold = attrs.lowThreshold();
result.medThreshold = attrs.medThreshold();
result.highThreshold = attrs.highThreshold();
// home_domain is checked by iscntrl in stellar-core
result.homeDomain = attrs.homeDomain() !== undefined ? attrs.homeDomain().toString('ascii') : undefined;
if (attrs.signer()) {
var signer = {};
var arm = attrs.signer().key().arm();
if (arm === 'ed25519') {
signer.ed25519PublicKey = accountIdtoAddress(attrs.signer().key());
} else if (arm === 'preAuthTx') {
signer.preAuthTx = attrs.signer().key().preAuthTx();
} else if (arm === 'hashX') {
signer.sha256Hash = attrs.signer().key().hashX();
} else if (arm === 'ed25519SignedPayload') {
var signedPayload = attrs.signer().key().ed25519SignedPayload();
signer.ed25519SignedPayload = _strkey.StrKey.encodeSignedPayload(signedPayload.toXDR());
}
signer.weight = attrs.signer().weight();
result.signer = signer;
}
break;
}
// the next case intentionally falls through!
case 'manageOffer':
case 'manageSellOffer':
{
result.type = 'manageSellOffer';
result.selling = _asset.Asset.fromOperation(attrs.selling());
result.buying = _asset.Asset.fromOperation(attrs.buying());
result.amount = this._fromXDRAmount(attrs.amount());
result.price = this._fromXDRPrice(attrs.price());
result.offerId = attrs.offerId().toString();
break;
}
case 'manageBuyOffer':
{
result.type = 'manageBuyOffer';
result.selling = _asset.Asset.fromOperation(attrs.selling());
result.buying = _asset.Asset.fromOperation(attrs.buying());
result.buyAmount = this._fromXDRAmount(attrs.buyAmount());
result.price = this._fromXDRPrice(attrs.price());
result.offerId = attrs.offerId().toString();
break;
}
// the next case intentionally falls through!
case 'createPassiveOffer':
case 'createPassiveSellOffer':
{
result.type = 'createPassiveSellOffer';
result.selling = _asset.Asset.fromOperation(attrs.selling());
result.buying = _asset.Asset.fromOperation(attrs.buying());
result.amount = this._fromXDRAmount(attrs.amount());
result.price = this._fromXDRPrice(attrs.price());
break;
}
case 'accountMerge':
{
result.type = 'accountMerge';
result.destination = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs);
break;
}
case 'manageData':
{
result.type = 'manageData';
// manage_data.name is checked by iscntrl in stellar-core
result.name = attrs.dataName().toString('ascii');
result.value = attrs.dataValue();
break;
}
case 'inflation':
{
result.type = 'inflation';
break;
}
case 'bumpSequence':
{
result.type = 'bumpSequence';
result.bumpTo = attrs.bumpTo().toString();
break;
}
case 'createClaimableBalance':
{
result.type = 'createClaimableBalance';
result.asset = _asset.Asset.fromOperation(attrs.asset());
result.amount = this._fromXDRAmount(attrs.amount());
result.claimants = [];
attrs.claimants().forEach(function (claimant) {
result.claimants.push(_claimant.Claimant.fromXDR(claimant));
});
break;
}
case 'claimClaimableBalance':
{
result.type = 'claimClaimableBalance';
result.balanceId = attrs.toXDR('hex');
break;
}
case 'beginSponsoringFutureReserves':
{
result.type = 'beginSponsoringFutureReserves';
result.sponsoredId = accountIdtoAddress(attrs.sponsoredId());
break;
}
case 'endSponsoringFutureReserves':
{
result.type = 'endSponsoringFutureReserves';
break;
}
case 'revokeSponsorship':
{
extractRevokeSponshipDetails(attrs, result);
break;
}
case 'clawback':
{
result.type = 'clawback';
result.amount = this._fromXDRAmount(attrs.amount());
result.from = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(attrs.from());
result.asset = _asset.Asset.fromOperation(attrs.asset());
break;
}
case 'clawbackClaimableBalance':
{
result.type = 'clawbackClaimableBalance';
result.balanceId = attrs.toXDR('hex');
break;
}
case 'setTrustLineFlags':
{
result.type = 'setTrustLineFlags';
result.asset = _asset.Asset.fromOperation(attrs.asset());
result.trustor = accountIdtoAddress(attrs.trustor());
// Convert from the integer-bitwised flag into a sensible object that
// indicates true/false for each flag that's on/off.
var clears = attrs.clearFlags();
var sets = attrs.setFlags();
var mapping = {
authorized: _xdr2.default.TrustLineFlags.authorizedFlag(),
authorizedToMaintainLiabilities: _xdr2.default.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(),
clawbackEnabled: _xdr2.default.TrustLineFlags.trustlineClawbackEnabledFlag()
};
var getFlagValue = function getFlagValue(key) {
var bit = mapping[key].value;
if (sets & bit) {
return true;
}
if (clears & bit) {
return false;
}
return undefined;
};
result.flags = {};
Object.keys(mapping).forEach(function (flagName) {
result.flags[flagName] = getFlagValue(flagName);
});
break;
}
case 'liquidityPoolDeposit':
{
result.type = 'liquidityPoolDeposit';
result.liquidityPoolId = attrs.liquidityPoolId().toString('hex');
result.maxAmountA = this._fromXDRAmount(attrs.maxAmountA());
result.maxAmountB = this._fromXDRAmount(attrs.maxAmountB());
result.minPrice = this._fromXDRPrice(attrs.minPrice());
result.maxPrice = this._fromXDRPrice(attrs.maxPrice());
break;
}
case 'liquidityPoolWithdraw':
{
result.type = 'liquidityPoolWithdraw';
result.liquidityPoolId = attrs.liquidityPoolId().toString('hex');
result.amount = this._fromXDRAmount(attrs.amount());
result.minAmountA = this._fromXDRAmount(attrs.minAmountA());
result.minAmountB = this._fromXDRAmount(attrs.minAmountB());
break;
}
default:
{
throw new Error('Unknown operation: ' + operationName);
}
}
return result;
}
}, {
key: 'isValidAmount',
value: function isValidAmount(value) {
var allowZero = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (!(0, _isString2.default)(value)) {
return false;
}
var amount = void 0;
try {
amount = new _bignumber2.default(value);
} catch (e) {
return false;
}
if (
// == 0
!allowZero && amount.isZero() ||
// < 0
amount.isNegative() ||
// > Max value
amount.times(ONE).greaterThan(new _bignumber2.default(MAX_INT64).toString()) ||
// Decimal places (max 7)
amount.decimalPlaces() > 7 ||
// NaN or Infinity
amount.isNaN() || !amount.isFinite()) {
return false;
}
return true;
}
}, {
key: 'constructAmountRequirementsError',
value: function constructAmountRequirementsError(arg) {
return arg + ' argument must be of type String, represent a positive number and have at most 7 digits after the decimal';
}
/**
* Returns value converted to uint32 value or undefined.
* If `value` is not `Number`, `String` or `Undefined` then throws an error.
* Used in {@link Operation.setOptions}.
* @private
* @param {string} name Name of the property (used in error message only)
* @param {*} value Value to check
* @param {function(value, name)} isValidFunction Function to check other constraints (the argument will be a `Number`)
* @returns {undefined|Number}
*/
}, {
key: '_checkUnsignedIntValue',
value: function _checkUnsignedIntValue(name, value) {
var isValidFunction = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
if ((0, _isUndefined2.default)(value)) {
return undefined;
}
if ((0, _isString2.default)(value)) {
value = parseFloat(value);
}
switch (true) {
case !(0, _isNumber2.default)(value) || !(0, _isFinite2.default)(value) || value % 1 !== 0:
throw new Error(name + ' value is invalid');
case value < 0:
throw new Error(name + ' value must be unsigned');
case !isValidFunction || isValidFunction && isValidFunction(value, name):
return value;
default:
throw new Error(name + ' value is invalid');
}
}
/**
* @private
* @param {string|BigNumber} value Value
* @returns {Hyper} XDR amount
*/
}, {
key: '_toXDRAmount',
value: function _toXDRAmount(value) {
var amount = new _bignumber2.default(value).mul(ONE);
return _jsXdr.Hyper.fromString(amount.toString());
}
/**
* @private
* @param {string|BigNumber} value XDR amount
* @returns {BigNumber} Number
*/
}, {
key: '_fromXDRAmount',
value: function _fromXDRAmount(value) {
return new _bignumber2.default(value).div(ONE).toFixed(7);
}
/**
* @private
* @param {object} price Price object
* @param {function} price.n numerator function that returns a value
* @param {function} price.d denominator function that returns a value
* @returns {BigNumber} Big string
*/
}, {
key: '_fromXDRPrice',
value: function _fromXDRPrice(price) {
var n = new _bignumber2.default(price.n());
return n.div(new _bignumber2.default(price.d())).toString();
}
/**
* @private
* @param {object} price Price object
* @param {function} price.n numerator function that returns a value
* @param {function} price.d denominator function that returns a value
* @returns {object} XDR price object
*/
}, {
key: '_toXDRPrice',
value: function _toXDRPrice(price) {
var xdrObject = void 0;
if (price.n && price.d) {
xdrObject = new _xdr2.default.Price(price);
} else {
price = new _bignumber2.default(price);
var approx = (0, _continued_fraction.best_r)(price);
xdrObject = new _xdr2.default.Price({
n: parseInt(approx[0], 10),
d: parseInt(approx[1], 10)
});
}
if (xdrObject.n() < 0 || xdrObject.d() < 0) {
throw new Error('price must be positive');
}
return xdrObject;
}
}]);
return Operation;
}();
function extractRevokeSponshipDetails(attrs, result) {
switch (attrs.switch().name) {
case 'revokeSponsorshipLedgerEntry':
{
var ledgerKey = attrs.ledgerKey();
switch (ledgerKey.switch().name) {
case _xdr2.default.LedgerEntryType.account().name:
{
result.type = 'revokeAccountSponsorship';
result.account = accountIdtoAddress(ledgerKey.account().accountId());
break;
}
case _xdr2.default.LedgerEntryType.trustline().name:
{
result.type = 'revokeTrustlineSponsorship';
result.account = accountIdtoAddress(ledgerKey.trustLine().accountId());
var xdrAsset = ledgerKey.trustLine().asset();
switch (xdrAsset.switch()) {
case _xdr2.default.AssetType.assetTypePoolShare():
result.asset = _liquidity_pool_id.LiquidityPoolId.fromOperation(xdrAsset);
break;
default:
result.asset = _asset.Asset.fromOperation(xdrAsset);
break;
}
break;
}
case _xdr2.default.LedgerEntryType.offer().name:
{
result.type = 'revokeOfferSponsorship';
result.seller = accountIdtoAddress(ledgerKey.offer().sellerId());
result.offerId = ledgerKey.offer().offerId().toString();
break;
}
case _xdr2.default.LedgerEntryType.data().name:
{
result.type = 'revokeDataSponsorship';
result.account = accountIdtoAddress(ledgerKey.data().accountId());
result.name = ledgerKey.data().dataName().toString('ascii');
break;
}
case _xdr2.default.LedgerEntryType.claimableBalance().name:
{
result.type = 'revokeClaimableBalanceSponsorship';
result.balanceId = ledgerKey.claimableBalance().balanceId().toXDR('hex');
break;
}
case _xdr2.default.LedgerEntryType.liquidityPool().name:
{
result.type = 'revokeLiquidityPoolSponsorship';
result.liquidityPoolId = ledgerKey.liquidityPool().liquidityPoolId().toString('hex');
break;
}
default:
{
throw new Error('Unknown ledgerKey: ' + attrs.switch().name);
}
}
break;
}
case 'revokeSponsorshipSigner':
{
result.type = 'revokeSignerSponsorship';
result.account = accountIdtoAddress(attrs.signer().accountId());
result.signer = convertXDRSignerKeyToObject(attrs.signer().signerKey());
break;
}
default:
{
throw new Error('Unknown revokeSponsorship: ' + attrs.switch().name);
}
}
}
function convertXDRSignerKeyToObject(signerKey) {
var attrs = {};
switch (signerKey.switch().name) {
case _xdr2.default.SignerKeyType.signerKeyTypeEd25519().name:
{
attrs.ed25519PublicKey = _strkey.StrKey.encodeEd25519PublicKey(signerKey.ed25519());
break;
}
case _xdr2.default.SignerKeyType.signerKeyTypePreAuthTx().name:
{
attrs.preAuthTx = signerKey.preAuthTx().toString('hex');
break;
}
case _xdr2.default.SignerKeyType.signerKeyTypeHashX().name:
{
attrs.sha256Hash = signerKey.hashX().toString('hex');
break;
}
default:
{
throw new Error('Unknown signerKey: ' + signerKey.switch().name);
}
}
return attrs;
}
function accountIdtoAddress(accountId) {
return _strkey.StrKey.encodeEd25519PublicKey(accountId.ed25519());
}
// Attach all imported operations as static methods on the Operation class
Operation.accountMerge = ops.accountMerge;
Operation.allowTrust = ops.allowTrust;
Operation.bumpSequence = ops.bumpSequence;
Operation.changeTrust = ops.changeTrust;
Operation.createAccount = ops.createAccount;
Operation.createClaimableBalance = ops.createClaimableBalance;
Operation.claimClaimableBalance = ops.claimClaimableBalance;
Operation.clawbackClaimableBalance = ops.clawbackClaimableBalance;
Operation.createPassiveSellOffer = ops.createPassiveSellOffer;
Operation.inflation = ops.inflation;
Operation.manageData = ops.manageData;
Operation.manageSellOffer = ops.manageSellOffer;
Operation.manageBuyOffer = ops.manageBuyOffer;
Operation.pathPaymentStrictReceive = ops.pathPaymentStrictReceive;
Operation.pathPaymentStrictSend = ops.pathPaymentStrictSend;
Operation.payment = ops.payment;
Operation.setOptions = ops.setOptions;
Operation.beginSponsoringFutureReserves = ops.beginSponsoringFutureReserves;
Operation.endSponsoringFutureReserves = ops.endSponsoringFutureReserves;
Operation.revokeAccountSponsorship = ops.revokeAccountSponsorship;
Operation.revokeTrustlineSponsorship = ops.revokeTrustlineSponsorship;
Operation.revokeOfferSponsorship = ops.revokeOfferSponsorship;
Operation.revokeDataSponsorship = ops.revokeDataSponsorship;
Operation.revokeClaimableBalanceSponsorship = ops.revokeClaimableBalanceSponsorship;
Operation.revokeLiquidityPoolSponsorship = ops.revokeLiquidityPoolSponsorship;
Operation.revokeSignerSponsorship = ops.revokeSignerSponsorship;
Operation.clawback = ops.clawback;
Operation.setTrustLineFlags = ops.setTrustLineFlags;
Operation.liquidityPoolDeposit = ops.liquidityPoolDeposit;
Operation.liquidityPoolWithdraw = ops.liquidityPoolWithdraw;
/***/ }),
/* 146 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Claimant = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _keypair = __webpack_require__(19);
var _strkey = __webpack_require__(8);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Claimant class represents an xdr.Claimant
*
* The claim predicate is optional, it defaults to unconditional if none is specified.
*
* @constructor
* @param {string} destination - The destination account ID.
* @param {xdr.ClaimPredicate} [predicate] - The claim predicate.
*/
var Claimant = exports.Claimant = function () {
function Claimant(destination, predicate) {
_classCallCheck(this, Claimant);
if (destination && !_strkey.StrKey.isValidEd25519PublicKey(destination)) {
throw new Error('Destination is invalid');
}
this._destination = destination;
if (!predicate) {
this._predicate = _xdr2.default.ClaimPredicate.claimPredicateUnconditional();
} else if (predicate instanceof _xdr2.default.ClaimPredicate) {
this._predicate = predicate;
} else {
throw new Error('Predicate should be an xdr.ClaimPredicate');
}
}
/**
* Returns an unconditional claim predicate
* @Return {xdr.ClaimPredicate}
*/
_createClass(Claimant, [{
key: 'toXDRObject',
/**
* Returns the xdr object for this claimant.
* @returns {xdr.Claimant} XDR Claimant object
*/
value: function toXDRObject() {
var claimant = new _xdr2.default.ClaimantV0({
destination: _keypair.Keypair.fromPublicKey(this._destination).xdrAccountId(),
predicate: this._predicate
});
return _xdr2.default.Claimant.claimantTypeV0(claimant);
}
/**
* @type {string}
* @readonly
*/
}, {
key: 'destination',
get: function get() {
return this._destination;
},
set: function set(value) {
throw new Error('Claimant is immutable');
}
/**
* @type {xdr.ClaimPredicate}
* @readonly
*/
}, {
key: 'predicate',
get: function get() {
return this._predicate;
},
set: function set(value) {
throw new Error('Claimant is immutable');
}
}], [{
key: 'predicateUnconditional',
value: function predicateUnconditional() {
return _xdr2.default.ClaimPredicate.claimPredicateUnconditional();
}
/**
* Returns an `and` claim predicate
* @param {xdr.ClaimPredicate} left an xdr.ClaimPredicate
* @param {xdr.ClaimPredicate} right an xdr.ClaimPredicate
* @Return {xdr.ClaimPredicate}
*/
}, {
key: 'predicateAnd',
value: function predicateAnd(left, right) {
if (!(left instanceof _xdr2.default.ClaimPredicate)) {
throw new Error('left Predicate should be an xdr.ClaimPredicate');
}
if (!(right instanceof _xdr2.default.ClaimPredicate)) {
throw new Error('right Predicate should be an xdr.ClaimPredicate');
}
return _xdr2.default.ClaimPredicate.claimPredicateAnd([left, right]);
}
/**
* Returns an `or` claim predicate
* @param {xdr.ClaimPredicate} left an xdr.ClaimPredicate
* @param {xdr.ClaimPredicate} right an xdr.ClaimPredicate
* @Return {xdr.ClaimPredicate}
*/
}, {
key: 'predicateOr',
value: function predicateOr(left, right) {
if (!(left instanceof _xdr2.default.ClaimPredicate)) {
throw new Error('left Predicate should be an xdr.ClaimPredicate');
}
if (!(right instanceof _xdr2.default.ClaimPredicate)) {
throw new Error('right Predicate should be an xdr.ClaimPredicate');
}
return _xdr2.default.ClaimPredicate.claimPredicateOr([left, right]);
}
/**
* Returns a `not` claim predicate
* @param {xdr.ClaimPredicate} predicate an xdr.ClaimPredicate
* @Return {xdr.ClaimPredicate}
*/
}, {
key: 'predicateNot',
value: function predicateNot(predicate) {
if (!(predicate instanceof _xdr2.default.ClaimPredicate)) {
throw new Error('right Predicate should be an xdr.ClaimPredicate');
}
return _xdr2.default.ClaimPredicate.claimPredicateNot(predicate);
}
/**
* Returns a `BeforeAbsoluteTime` claim predicate
*
* This predicate will be fulfilled if the closing time of the ledger that
* includes the CreateClaimableBalance operation is less than this (absolute)
* Unix timestamp (expressed in seconds).
*
* @param {string} absBefore Unix epoch (in seconds) as a string
* @Return {xdr.ClaimPredicate}
*/
}, {
key: 'predicateBeforeAbsoluteTime',
value: function predicateBeforeAbsoluteTime(absBefore) {
return _xdr2.default.ClaimPredicate.claimPredicateBeforeAbsoluteTime(_xdr2.default.Int64.fromString(absBefore));
}
/**
* Returns a `BeforeRelativeTime` claim predicate
*
* This predicate will be fulfilled if the closing time of the ledger that
* includes the CreateClaimableBalance operation plus this relative time delta
* (in seconds) is less than the current time.
*
* @param {strings} seconds seconds since closeTime of the ledger in which the ClaimableBalanceEntry was created (as string)
* @Return {xdr.ClaimPredicate}
*/
}, {
key: 'predicateBeforeRelativeTime',
value: function predicateBeforeRelativeTime(seconds) {
return _xdr2.default.ClaimPredicate.claimPredicateBeforeRelativeTime(_xdr2.default.Int64.fromString(seconds));
}
/**
* Returns a claimant object from its XDR object representation.
* @param {xdr.Claimant} claimantXdr - The claimant xdr object.
* @returns {Claimant}
*/
}, {
key: 'fromXDR',
value: function fromXDR(claimantXdr) {
var value = void 0;
switch (claimantXdr.switch()) {
case _xdr2.default.ClaimantType.claimantTypeV0():
value = claimantXdr.v0();
return new this(_strkey.StrKey.encodeEd25519PublicKey(value.destination().ed25519()), value.predicate());
default:
throw new Error('Invalid claimant type: ' + claimantXdr.switch().name);
}
}
}]);
return Claimant;
}();
/***/ }),
/* 147 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.claimClaimableBalance = claimClaimableBalance;
exports.validateClaimableBalanceId = validateClaimableBalanceId;
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Create a new claim claimable balance operation.
* @function
* @alias Operation.claimClaimableBalance
* @param {object} opts Options object
* @param {string} opts.balanceId - The claimable balance id to be claimed.
* @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account.
* @returns {xdr.Operation} Claim claimable balance operation
*
* @example
* const op = Operation.claimClaimableBalance({
* balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be',
* });
*
*/
function claimClaimableBalance() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
validateClaimableBalanceId(opts.balanceId);
var attributes = {};
attributes.balanceId = _xdr2.default.ClaimableBalanceId.fromXDR(opts.balanceId, 'hex');
var claimClaimableBalanceOp = new _xdr2.default.ClaimClaimableBalanceOp(attributes);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.claimClaimableBalance(claimClaimableBalanceOp);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
function validateClaimableBalanceId(balanceId) {
if (typeof balanceId !== 'string' || balanceId.length !== 8 + 64 /* 8b discriminant + 64b string */
) {
throw new Error('must provide a valid claimable balance id');
}
}
/***/ }),
/* 148 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.FeeBumpTransaction = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _hashing = __webpack_require__(30);
var _transaction = __webpack_require__(87);
var _transaction_base = __webpack_require__(86);
var _decode_encode_muxed_account = __webpack_require__(17);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* Use {@link TransactionBuilder.buildFeeBumpTransaction} to build a
* FeeBumpTransaction object. If you have an object or base64-encoded string of
* the transaction envelope XDR use {@link TransactionBuilder.fromXDR}.
*
* Once a {@link FeeBumpTransaction} has been created, its attributes and operations
* should not be changed. You should only add signatures (using {@link FeeBumpTransaction#sign}) before
* submitting to the network or forwarding on to additional signers.
*
* @param {string|xdr.TransactionEnvelope} envelope - transaction envelope
* object or base64 encoded string.
* @param {string} networkPassphrase - passphrase of the target Stellar network
* (e.g. "Public Global Stellar Network ; September 2015").
*
* @extends TransactionBase
*/
var FeeBumpTransaction = exports.FeeBumpTransaction = function (_TransactionBase) {
_inherits(FeeBumpTransaction, _TransactionBase);
function FeeBumpTransaction(envelope, networkPassphrase) {
_classCallCheck(this, FeeBumpTransaction);
if (typeof envelope === 'string') {
var buffer = Buffer.from(envelope, 'base64');
envelope = _xdr2.default.TransactionEnvelope.fromXDR(buffer);
}
var envelopeType = envelope.switch();
if (envelopeType !== _xdr2.default.EnvelopeType.envelopeTypeTxFeeBump()) {
throw new Error('Invalid TransactionEnvelope: expected an envelopeTypeTxFeeBump but received an ' + envelopeType.name + '.');
}
var txEnvelope = envelope.value();
var tx = txEnvelope.tx();
var fee = tx.fee().toString();
// clone signatures
var signatures = (txEnvelope.signatures() || []).slice();
var _this = _possibleConstructorReturn(this, (FeeBumpTransaction.__proto__ || Object.getPrototypeOf(FeeBumpTransaction)).call(this, tx, signatures, fee, networkPassphrase));
var innerTxEnvelope = _xdr2.default.TransactionEnvelope.envelopeTypeTx(tx.innerTx().v1());
_this._feeSource = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(_this.tx.feeSource());
_this._innerTransaction = new _transaction.Transaction(innerTxEnvelope, networkPassphrase);
return _this;
}
/**
* @type {Transaction}
* @readonly
*/
_createClass(FeeBumpTransaction, [{
key: 'signatureBase',
/**
* Returns the "signature base" of this transaction, which is the value
* that, when hashed, should be signed to create a signature that
* validators on the Stellar Network will accept.
*
* It is composed of a 4 prefix bytes followed by the xdr-encoded form
* of this transaction.
* @returns {Buffer}
*/
value: function signatureBase() {
var taggedTransaction = new _xdr2.default.TransactionSignaturePayloadTaggedTransaction.envelopeTypeTxFeeBump(this.tx);
var txSignature = new _xdr2.default.TransactionSignaturePayload({
networkId: _xdr2.default.Hash.fromXDR((0, _hashing.hash)(this.networkPassphrase)),
taggedTransaction: taggedTransaction
});
return txSignature.toXDR();
}
/**
* To envelope returns a xdr.TransactionEnvelope which can be submitted to the network.
* @returns {xdr.TransactionEnvelope}
*/
}, {
key: 'toEnvelope',
value: function toEnvelope() {
var envelope = new _xdr2.default.FeeBumpTransactionEnvelope({
tx: _xdr2.default.FeeBumpTransaction.fromXDR(this.tx.toXDR()), // make a copy of the tx
signatures: this.signatures.slice() // make a copy of the signatures
});
return new _xdr2.default.TransactionEnvelope.envelopeTypeTxFeeBump(envelope);
}
}, {
key: 'innerTransaction',
get: function get() {
return this._innerTransaction;
}
/**
* @type {string}
* @readonly
*/
}, {
key: 'feeSource',
get: function get() {
return this._feeSource;
}
}]);
return FeeBumpTransaction;
}(_transaction_base.TransactionBase);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 149 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SignerKey = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _strkey = __webpack_require__(8);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* A container class with helpers to convert between signer keys
* (`xdr.SignerKey`) and {@link StrKey}s.
*
* It's primarly used for manipulating the `extraSigners` precondition on a
* {@link Transaction}.
*
* @see {@link TransactionBuilder.setExtraSigners}
*/
var SignerKey = exports.SignerKey = function () {
function SignerKey() {
_classCallCheck(this, SignerKey);
}
_createClass(SignerKey, null, [{
key: 'decodeAddress',
/**
* Decodes a StrKey address into an xdr.SignerKey instance.
*
* Only ED25519 public keys (G...), pre-auth transactions (T...), hashes
* (H...), and signed payloads (P...) can be signer keys.
*
* @param {string} address a StrKey-encoded signer address
* @returns {xdr.SignerKey}
*/
value: function decodeAddress(address) {
var signerKeyMap = {
ed25519PublicKey: _xdr2.default.SignerKey.signerKeyTypeEd25519,
preAuthTx: _xdr2.default.SignerKey.signerKeyTypePreAuthTx,
sha256Hash: _xdr2.default.SignerKey.signerKeyTypeHashX,
signedPayload: _xdr2.default.SignerKey.signerKeyTypeEd25519SignedPayload
};
var vb = _strkey.StrKey.getVersionByteForPrefix(address);
var encoder = signerKeyMap[vb];
if (!encoder) {
throw new Error('invalid signer key type (' + vb + ')');
}
var raw = (0, _strkey.decodeCheck)(vb, address);
switch (vb) {
case 'signedPayload':
return encoder(new _xdr2.default.SignerKeyEd25519SignedPayload({
ed25519: raw.slice(0, 32),
payload: raw.slice(32 + 4)
}));
case 'ed25519PublicKey': // falls through
case 'preAuthTx': // falls through
case 'sha256Hash': // falls through
default:
return encoder(raw);
}
}
/**
* Encodes a signer key into its StrKey equivalent.
*
* @param {xdr.SignerKey} signerKey the signer
* @returns {string} the StrKey representation of the signer
*/
}, {
key: 'encodeSignerKey',
value: function encodeSignerKey(signerKey) {
var strkeyType = void 0;
var raw = void 0;
switch (signerKey.switch()) {
case _xdr2.default.SignerKeyType.signerKeyTypeEd25519():
strkeyType = 'ed25519PublicKey';
raw = signerKey.value();
break;
case _xdr2.default.SignerKeyType.signerKeyTypePreAuthTx():
strkeyType = 'preAuthTx';
raw = signerKey.value();
break;
case _xdr2.default.SignerKeyType.signerKeyTypeHashX():
strkeyType = 'sha256Hash';
raw = signerKey.value();
break;
case _xdr2.default.SignerKeyType.signerKeyTypeEd25519SignedPayload():
strkeyType = 'signedPayload';
raw = signerKey.ed25519SignedPayload().toXDR('raw');
break;
default:
throw new Error('invalid SignerKey (type: ' + signerKey.switch() + ')');
}
return (0, _strkey.encodeCheck)(strkeyType, raw);
}
}]);
return SignerKey;
}();
/***/ }),
/* 150 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Account = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _isString = __webpack_require__(9);
var _isString2 = _interopRequireDefault(_isString);
var _bignumber = __webpack_require__(23);
var _bignumber2 = _interopRequireDefault(_bignumber);
var _strkey = __webpack_require__(8);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Create a new Account object.
*
* `Account` represents a single account in the Stellar network and its sequence
* number. Account tracks the sequence number as it is used by {@link
* TransactionBuilder}. See
* [Accounts](https://developers.stellar.org/docs/glossary/accounts/) for
* more information about how accounts work in Stellar.
*
* @constructor
*
* @param {string} accountId - ID of the account (ex.
* `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`). If you
* provide a muxed account address, this will throw; use {@link
* MuxedAccount} instead.
* @param {string} sequence - current sequence number of the account
*/
var Account = exports.Account = function () {
function Account(accountId, sequence) {
_classCallCheck(this, Account);
if (_strkey.StrKey.isValidMed25519PublicKey(accountId)) {
throw new Error('accountId is an M-address; use MuxedAccount instead');
}
if (!_strkey.StrKey.isValidEd25519PublicKey(accountId)) {
throw new Error('accountId is invalid');
}
if (!(0, _isString2.default)(sequence)) {
throw new Error('sequence must be of type string');
}
this._accountId = accountId;
this.sequence = new _bignumber2.default(sequence);
}
/**
* Returns Stellar account ID, ex.
* `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`.
* @returns {string}
*/
_createClass(Account, [{
key: 'accountId',
value: function accountId() {
return this._accountId;
}
/**
* @returns {string} sequence number for the account as a string
*/
}, {
key: 'sequenceNumber',
value: function sequenceNumber() {
return this.sequence.toString();
}
/**
* Increments sequence number in this object by one.
* @returns {void}
*/
}, {
key: 'incrementSequenceNumber',
value: function incrementSequenceNumber() {
this.sequence = this.sequence.add(1);
}
}]);
return Account;
}();
/***/ }),
/* 151 */
/***/ (function(module, exports, __webpack_require__) {
var baseAssignValue = __webpack_require__(72),
eq = __webpack_require__(43);
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignMergeValue(object, key, value) {
if ((value !== undefined && !eq(object[key], value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
module.exports = assignMergeValue;
/***/ }),
/* 152 */
/***/ (function(module, exports) {
/**
* Gets the value at `key`, unless `key` is "__proto__" or "constructor".
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function safeGet(object, key) {
if (key === 'constructor' && typeof object[key] === 'function') {
return;
}
if (key == '__proto__') {
return;
}
return object[key];
}
module.exports = safeGet;
/***/ }),
/* 153 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.0 by @mathias */
;(function(root) {
/** Detect free variables */
var freeExports = true && exports &&
!exports.nodeType && exports;
var freeModule = true && module &&
!module.nodeType && module;
var freeGlobal = typeof global == 'object' && global;
if (
freeGlobal.global === freeGlobal ||
freeGlobal.window === freeGlobal ||
freeGlobal.self === freeGlobal
) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
var result = [];
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
var parts = string.split('@');
var result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
string = string.replace(regexSeparators, '\x2E');
var labels = string.split('.');
var encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
function toASCII(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.3.2',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
true
) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
return punycode;
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}(this));
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(41)(module), __webpack_require__(5)))
/***/ }),
/* 154 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* URI.js - Mutating URLs
* IPv6 Support
*
* Version: 1.19.11
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/
(function (root, factory) {
'use strict';
// https://github.com/umdjs/umd/blob/master/returnExports.js
if ( true && module.exports) {
// Node
module.exports = factory();
} else if (true) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}(this, function (root) {
'use strict';
/*
var _in = "fe80:0000:0000:0000:0204:61ff:fe9d:f156";
var _out = IPv6.best(_in);
var _expected = "fe80::204:61ff:fe9d:f156";
console.log(_in, _out, _expected, _out === _expected);
*/
// save current IPv6 variable, if any
var _IPv6 = root && root.IPv6;
function bestPresentation(address) {
// based on:
// Javascript to test an IPv6 address for proper format, and to
// present the "best text representation" according to IETF Draft RFC at
// http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04
// 8 Feb 2010 Rich Brown, Dartware, LLC
// Please feel free to use this code as long as you provide a link to
// http://www.intermapper.com
// http://intermapper.com/support/tools/IPV6-Validator.aspx
// http://download.dartware.com/thirdparty/ipv6validator.js
var _address = address.toLowerCase();
var segments = _address.split(':');
var length = segments.length;
var total = 8;
// trim colons (:: or ::a:b:c… or …a:b:c::)
if (segments[0] === '' && segments[1] === '' && segments[2] === '') {
// must have been ::
// remove first two items
segments.shift();
segments.shift();
} else if (segments[0] === '' && segments[1] === '') {
// must have been ::xxxx
// remove the first item
segments.shift();
} else if (segments[length - 1] === '' && segments[length - 2] === '') {
// must have been xxxx::
segments.pop();
}
length = segments.length;
// adjust total segments for IPv4 trailer
if (segments[length - 1].indexOf('.') !== -1) {
// found a "." which means IPv4
total = 7;
}
// fill empty segments them with "0000"
var pos;
for (pos = 0; pos < length; pos++) {
if (segments[pos] === '') {
break;
}
}
if (pos < total) {
segments.splice(pos, 1, '0000');
while (segments.length < total) {
segments.splice(pos, 0, '0000');
}
}
// strip leading zeros
var _segments;
for (var i = 0; i < total; i++) {
_segments = segments[i].split('');
for (var j = 0; j < 3 ; j++) {
if (_segments[0] === '0' && _segments.length > 1) {
_segments.splice(0,1);
} else {
break;
}
}
segments[i] = _segments.join('');
}
// find longest sequence of zeroes and coalesce them into one segment
var best = -1;
var _best = 0;
var _current = 0;
var current = -1;
var inzeroes = false;
// i; already declared
for (i = 0; i < total; i++) {
if (inzeroes) {
if (segments[i] === '0') {
_current += 1;
} else {
inzeroes = false;
if (_current > _best) {
best = current;
_best = _current;
}
}
} else {
if (segments[i] === '0') {
inzeroes = true;
current = i;
_current = 1;
}
}
}
if (_current > _best) {
best = current;
_best = _current;
}
if (_best > 1) {
segments.splice(best, _best, '');
}
length = segments.length;
// assemble remaining segments
var result = '';
if (segments[0] === '') {
result = ':';
}
for (i = 0; i < length; i++) {
result += segments[i];
if (i === length - 1) {
break;
}
result += ':';
}
if (segments[length - 1] === '') {
result += ':';
}
return result;
}
function noConflict() {
/*jshint validthis: true */
if (root.IPv6 === this) {
root.IPv6 = _IPv6;
}
return this;
}
return {
best: bestPresentation,
noConflict: noConflict
};
}));
/***/ }),
/* 155 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* URI.js - Mutating URLs
* Second Level Domain (SLD) Support
*
* Version: 1.19.11
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/
(function (root, factory) {
'use strict';
// https://github.com/umdjs/umd/blob/master/returnExports.js
if ( true && module.exports) {
// Node
module.exports = factory();
} else if (true) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}(this, function (root) {
'use strict';
// save current SecondLevelDomains variable, if any
var _SecondLevelDomains = root && root.SecondLevelDomains;
var SLD = {
// list of known Second Level Domains
// converted list of SLDs from https://github.com/gavingmiller/second-level-domains
// ----
// publicsuffix.org is more current and actually used by a couple of browsers internally.
// downside is it also contains domains like "dyndns.org" - which is fine for the security
// issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js
// ----
list: {
'ac':' com gov mil net org ',
'ae':' ac co gov mil name net org pro sch ',
'af':' com edu gov net org ',
'al':' com edu gov mil net org ',
'ao':' co ed gv it og pb ',
'ar':' com edu gob gov int mil net org tur ',
'at':' ac co gv or ',
'au':' asn com csiro edu gov id net org ',
'ba':' co com edu gov mil net org rs unbi unmo unsa untz unze ',
'bb':' biz co com edu gov info net org store tv ',
'bh':' biz cc com edu gov info net org ',
'bn':' com edu gov net org ',
'bo':' com edu gob gov int mil net org tv ',
'br':' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ',
'bs':' com edu gov net org ',
'bz':' du et om ov rg ',
'ca':' ab bc mb nb nf nl ns nt nu on pe qc sk yk ',
'ck':' biz co edu gen gov info net org ',
'cn':' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ',
'co':' com edu gov mil net nom org ',
'cr':' ac c co ed fi go or sa ',
'cy':' ac biz com ekloges gov ltd name net org parliament press pro tm ',
'do':' art com edu gob gov mil net org sld web ',
'dz':' art asso com edu gov net org pol ',
'ec':' com edu fin gov info med mil net org pro ',
'eg':' com edu eun gov mil name net org sci ',
'er':' com edu gov ind mil net org rochest w ',
'es':' com edu gob nom org ',
'et':' biz com edu gov info name net org ',
'fj':' ac biz com info mil name net org pro ',
'fk':' ac co gov net nom org ',
'fr':' asso com f gouv nom prd presse tm ',
'gg':' co net org ',
'gh':' com edu gov mil org ',
'gn':' ac com gov net org ',
'gr':' com edu gov mil net org ',
'gt':' com edu gob ind mil net org ',
'gu':' com edu gov net org ',
'hk':' com edu gov idv net org ',
'hu':' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ',
'id':' ac co go mil net or sch web ',
'il':' ac co gov idf k12 muni net org ',
'in':' ac co edu ernet firm gen gov i ind mil net nic org res ',
'iq':' com edu gov i mil net org ',
'ir':' ac co dnssec gov i id net org sch ',
'it':' edu gov ',
'je':' co net org ',
'jo':' com edu gov mil name net org sch ',
'jp':' ac ad co ed go gr lg ne or ',
'ke':' ac co go info me mobi ne or sc ',
'kh':' com edu gov mil net org per ',
'ki':' biz com de edu gov info mob net org tel ',
'km':' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ',
'kn':' edu gov net org ',
'kr':' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ',
'kw':' com edu gov net org ',
'ky':' com edu gov net org ',
'kz':' com edu gov mil net org ',
'lb':' com edu gov net org ',
'lk':' assn com edu gov grp hotel int ltd net ngo org sch soc web ',
'lr':' com edu gov net org ',
'lv':' asn com conf edu gov id mil net org ',
'ly':' com edu gov id med net org plc sch ',
'ma':' ac co gov m net org press ',
'mc':' asso tm ',
'me':' ac co edu gov its net org priv ',
'mg':' com edu gov mil nom org prd tm ',
'mk':' com edu gov inf name net org pro ',
'ml':' com edu gov net org presse ',
'mn':' edu gov org ',
'mo':' com edu gov net org ',
'mt':' com edu gov net org ',
'mv':' aero biz com coop edu gov info int mil museum name net org pro ',
'mw':' ac co com coop edu gov int museum net org ',
'mx':' com edu gob net org ',
'my':' com edu gov mil name net org sch ',
'nf':' arts com firm info net other per rec store web ',
'ng':' biz com edu gov mil mobi name net org sch ',
'ni':' ac co com edu gob mil net nom org ',
'np':' com edu gov mil net org ',
'nr':' biz com edu gov info net org ',
'om':' ac biz co com edu gov med mil museum net org pro sch ',
'pe':' com edu gob mil net nom org sld ',
'ph':' com edu gov i mil net ngo org ',
'pk':' biz com edu fam gob gok gon gop gos gov net org web ',
'pl':' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ',
'pr':' ac biz com edu est gov info isla name net org pro prof ',
'ps':' com edu gov net org plo sec ',
'pw':' belau co ed go ne or ',
'ro':' arts com firm info nom nt org rec store tm www ',
'rs':' ac co edu gov in org ',
'sb':' com edu gov net org ',
'sc':' com edu gov net org ',
'sh':' co com edu gov net nom org ',
'sl':' com edu gov net org ',
'st':' co com consulado edu embaixada gov mil net org principe saotome store ',
'sv':' com edu gob org red ',
'sz':' ac co org ',
'tr':' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ',
'tt':' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ',
'tw':' club com ebiz edu game gov idv mil net org ',
'mu':' ac co com gov net or org ',
'mz':' ac co edu gov org ',
'na':' co com ',
'nz':' ac co cri geek gen govt health iwi maori mil net org parliament school ',
'pa':' abo ac com edu gob ing med net nom org sld ',
'pt':' com edu gov int net nome org publ ',
'py':' com edu gov mil net org ',
'qa':' com edu gov mil net org ',
're':' asso com nom ',
'ru':' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ',
'rw':' ac co com edu gouv gov int mil net ',
'sa':' com edu gov med net org pub sch ',
'sd':' com edu gov info med net org tv ',
'se':' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ',
'sg':' com edu gov idn net org per ',
'sn':' art com edu gouv org perso univ ',
'sy':' com edu gov mil net news org ',
'th':' ac co go in mi net or ',
'tj':' ac biz co com edu go gov info int mil name net nic org test web ',
'tn':' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ',
'tz':' ac co go ne or ',
'ua':' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ',
'ug':' ac co go ne or org sc ',
'uk':' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ',
'us':' dni fed isa kids nsn ',
'uy':' com edu gub mil net org ',
've':' co com edu gob info mil net org web ',
'vi':' co com k12 net org ',
'vn':' ac biz com edu gov health info int name net org pro ',
'ye':' co com gov ltd me net org plc ',
'yu':' ac co edu gov org ',
'za':' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ',
'zm':' ac co com edu gov net org sch ',
// https://en.wikipedia.org/wiki/CentralNic#Second-level_domains
'com': 'ar br cn de eu gb gr hu jpn kr no qc ru sa se uk us uy za ',
'net': 'gb jp se uk ',
'org': 'ae',
'de': 'com '
},
// gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost
// in both performance and memory footprint. No initialization required.
// http://jsperf.com/uri-js-sld-regex-vs-binary-search/4
// Following methods use lastIndexOf() rather than array.split() in order
// to avoid any memory allocations.
has: function(domain) {
var tldOffset = domain.lastIndexOf('.');
if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
return false;
}
var sldOffset = domain.lastIndexOf('.', tldOffset-1);
if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {
return false;
}
var sldList = SLD.list[domain.slice(tldOffset+1)];
if (!sldList) {
return false;
}
return sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') >= 0;
},
is: function(domain) {
var tldOffset = domain.lastIndexOf('.');
if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
return false;
}
var sldOffset = domain.lastIndexOf('.', tldOffset-1);
if (sldOffset >= 0) {
return false;
}
var sldList = SLD.list[domain.slice(tldOffset+1)];
if (!sldList) {
return false;
}
return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0;
},
get: function(domain) {
var tldOffset = domain.lastIndexOf('.');
if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {
return null;
}
var sldOffset = domain.lastIndexOf('.', tldOffset-1);
if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {
return null;
}
var sldList = SLD.list[domain.slice(tldOffset+1)];
if (!sldList) {
return null;
}
if (sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') < 0) {
return null;
}
return domain.slice(sldOffset+1);
},
noConflict: function(){
if (root.SecondLevelDomains === this) {
root.SecondLevelDomains = _SecondLevelDomains;
}
return this;
}
};
return SLD;
}));
/***/ }),
/* 156 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function bind(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};
/***/ }),
/* 157 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(10);
function encode(val) {
return encodeURIComponent(val).
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @returns {string} The formatted url
*/
module.exports = function buildURL(url, params, paramsSerializer) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else if (utils.isURLSearchParams(params)) {
serializedParams = params.toString();
} else {
var parts = [];
utils.forEach(params, function serialize(val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (utils.isArray(val)) {
key = key + '[]';
} else {
val = [val];
}
utils.forEach(val, function parseValue(v) {
if (utils.isDate(v)) {
v = v.toISOString();
} else if (utils.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + '=' + encode(v));
});
});
serializedParams = parts.join('&');
}
if (serializedParams) {
var hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
};
/***/ }),
/* 158 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Update an Error with the specified config, error code, and response.
*
* @param {Error} error The error to update.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The error.
*/
module.exports = function enhanceError(error, config, code, request, response) {
error.config = config;
if (code) {
error.code = code;
}
error.request = request;
error.response = response;
error.isAxiosError = true;
error.toJSON = function toJSON() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: this.config,
code: this.code,
status: this.response && this.response.status ? this.response.status : null
};
};
return error;
};
/***/ }),
/* 159 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(10);
var settle = __webpack_require__(380);
var cookies = __webpack_require__(381);
var buildURL = __webpack_require__(157);
var buildFullPath = __webpack_require__(382);
var parseHeaders = __webpack_require__(385);
var isURLSameOrigin = __webpack_require__(386);
var createError = __webpack_require__(160);
var defaults = __webpack_require__(62);
var Cancel = __webpack_require__(63);
module.exports = function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
var responseType = config.responseType;
var onCanceled;
function done() {
if (config.cancelToken) {
config.cancelToken.unsubscribe(onCanceled);
}
if (config.signal) {
config.signal.removeEventListener('abort', onCanceled);
}
}
if (utils.isFormData(requestData)) {
delete requestHeaders['Content-Type']; // Let the browser set it
}
var request = new XMLHttpRequest();
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
var fullPath = buildFullPath(config.baseURL, config.url);
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
// Set the request timeout in MS
request.timeout = config.timeout;
function onloadend() {
if (!request) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
request.responseText : request.response;
var response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config: config,
request: request
};
settle(function _resolve(value) {
resolve(value);
done();
}, function _reject(err) {
reject(err);
done();
}, response);
// Clean up request
request = null;
}
if ('onloadend' in request) {
// Use onloadend if available
request.onloadend = onloadend;
} else {
// Listen for ready state to emulate onloadend
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
// readystate handler is calling before onerror or ontimeout handlers,
// so we should call onloadend on the next 'tick'
setTimeout(onloadend);
};
}
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(createError('Request aborted', config, 'ECONNABORTED', request));
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(createError('Network Error', config, null, request));
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
var transitional = config.transitional || defaults.transitional;
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(createError(
timeoutErrorMessage,
config,
transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',
request));
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
// Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
// Add withCredentials to request if needed
if (!utils.isUndefined(config.withCredentials)) {
request.withCredentials = !!config.withCredentials;
}
// Add responseType to request if needed
if (responseType && responseType !== 'json') {
request.responseType = config.responseType;
}
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', config.onDownloadProgress);
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', config.onUploadProgress);
}
if (config.cancelToken || config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = function(cancel) {
if (!request) {
return;
}
reject(!cancel || (cancel && cancel.type) ? new Cancel('canceled') : cancel);
request.abort();
request = null;
};
config.cancelToken && config.cancelToken.subscribe(onCanceled);
if (config.signal) {
config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
}
}
if (!requestData) {
requestData = null;
}
// Send the request
request.send(requestData);
});
};
/***/ }),
/* 160 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var enhanceError = __webpack_require__(158);
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The created error.
*/
module.exports = function createError(message, config, code, request, response) {
var error = new Error(message);
return enhanceError(error, config, code, request, response);
};
/***/ }),
/* 161 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = function isCancel(value) {
return !!(value && value.__CANCEL__);
};
/***/ }),
/* 162 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(10);
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
* @returns {Object} New object resulting from merging config2 to config1
*/
module.exports = function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
var config = {};
function getMergedValue(target, source) {
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
return utils.merge(target, source);
} else if (utils.isPlainObject(source)) {
return utils.merge({}, source);
} else if (utils.isArray(source)) {
return source.slice();
}
return source;
}
// eslint-disable-next-line consistent-return
function mergeDeepProperties(prop) {
if (!utils.isUndefined(config2[prop])) {
return getMergedValue(config1[prop], config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
return getMergedValue(undefined, config1[prop]);
}
}
// eslint-disable-next-line consistent-return
function valueFromConfig2(prop) {
if (!utils.isUndefined(config2[prop])) {
return getMergedValue(undefined, config2[prop]);
}
}
// eslint-disable-next-line consistent-return
function defaultToConfig2(prop) {
if (!utils.isUndefined(config2[prop])) {
return getMergedValue(undefined, config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
return getMergedValue(undefined, config1[prop]);
}
}
// eslint-disable-next-line consistent-return
function mergeDirectKeys(prop) {
if (prop in config2) {
return getMergedValue(config1[prop], config2[prop]);
} else if (prop in config1) {
return getMergedValue(undefined, config1[prop]);
}
}
var mergeMap = {
'url': valueFromConfig2,
'method': valueFromConfig2,
'data': valueFromConfig2,
'baseURL': defaultToConfig2,
'transformRequest': defaultToConfig2,
'transformResponse': defaultToConfig2,
'paramsSerializer': defaultToConfig2,
'timeout': defaultToConfig2,
'timeoutMessage': defaultToConfig2,
'withCredentials': defaultToConfig2,
'adapter': defaultToConfig2,
'responseType': defaultToConfig2,
'xsrfCookieName': defaultToConfig2,
'xsrfHeaderName': defaultToConfig2,
'onUploadProgress': defaultToConfig2,
'onDownloadProgress': defaultToConfig2,
'decompress': defaultToConfig2,
'maxContentLength': defaultToConfig2,
'maxBodyLength': defaultToConfig2,
'transport': defaultToConfig2,
'httpAgent': defaultToConfig2,
'httpsAgent': defaultToConfig2,
'cancelToken': defaultToConfig2,
'socketPath': defaultToConfig2,
'responseEncoding': defaultToConfig2,
'validateStatus': mergeDirectKeys
};
utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
var merge = mergeMap[prop] || mergeDeepProperties;
var configValue = merge(prop);
(utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
});
return config;
};
/***/ }),
/* 163 */
/***/ (function(module, exports) {
module.exports = {
"version": "0.25.0"
};
/***/ }),
/* 164 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process, Buffer) {var original = __webpack_require__(391)
var parse = __webpack_require__(92).parse
var events = __webpack_require__(93)
var https = __webpack_require__(400)
var http = __webpack_require__(165)
var util = __webpack_require__(412)
var httpsOptions = [
'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers',
'rejectUnauthorized', 'secureProtocol', 'servername', 'checkServerIdentity'
]
var bom = [239, 187, 191]
var colon = 58
var space = 32
var lineFeed = 10
var carriageReturn = 13
function hasBom (buf) {
return bom.every(function (charCode, index) {
return buf[index] === charCode
})
}
/**
* Creates a new EventSource object
*
* @param {String} url the URL to which to connect
* @param {Object} [eventSourceInitDict] extra init params. See README for details.
* @api public
**/
function EventSource (url, eventSourceInitDict) {
var readyState = EventSource.CONNECTING
var headers = eventSourceInitDict && eventSourceInitDict.headers
var hasNewOrigin = false
Object.defineProperty(this, 'readyState', {
get: function () {
return readyState
}
})
Object.defineProperty(this, 'url', {
get: function () {
return url
}
})
var self = this
self.reconnectInterval = 1000
self.connectionInProgress = false
function onConnectionClosed (message) {
if (readyState === EventSource.CLOSED) return
readyState = EventSource.CONNECTING
_emit('error', new Event('error', {message: message}))
// The url may have been changed by a temporary redirect. If that's the case,
// revert it now, and flag that we are no longer pointing to a new origin
if (reconnectUrl) {
url = reconnectUrl
reconnectUrl = null
hasNewOrigin = false
}
setTimeout(function () {
if (readyState !== EventSource.CONNECTING || self.connectionInProgress) {
return
}
self.connectionInProgress = true
connect()
}, self.reconnectInterval)
}
var req
var lastEventId = ''
if (headers && headers['Last-Event-ID']) {
lastEventId = headers['Last-Event-ID']
delete headers['Last-Event-ID']
}
var discardTrailingNewline = false
var data = ''
var eventName = ''
var reconnectUrl = null
function connect () {
var options = parse(url)
var isSecure = options.protocol === 'https:'
options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' }
if (lastEventId) options.headers['Last-Event-ID'] = lastEventId
if (headers) {
var reqHeaders = hasNewOrigin ? removeUnsafeHeaders(headers) : headers
for (var i in reqHeaders) {
var header = reqHeaders[i]
if (header) {
options.headers[i] = header
}
}
}
// Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`,
// but for now exists as a backwards-compatibility layer
options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized)
if (eventSourceInitDict && eventSourceInitDict.createConnection !== undefined) {
options.createConnection = eventSourceInitDict.createConnection
}
// If specify http proxy, make the request to sent to the proxy server,
// and include the original url in path and Host headers
var useProxy = eventSourceInitDict && eventSourceInitDict.proxy
if (useProxy) {
var proxy = parse(eventSourceInitDict.proxy)
isSecure = proxy.protocol === 'https:'
options.protocol = isSecure ? 'https:' : 'http:'
options.path = url
options.headers.Host = options.host
options.hostname = proxy.hostname
options.host = proxy.host
options.port = proxy.port
}
// If https options are specified, merge them into the request options
if (eventSourceInitDict && eventSourceInitDict.https) {
for (var optName in eventSourceInitDict.https) {
if (httpsOptions.indexOf(optName) === -1) {
continue
}
var option = eventSourceInitDict.https[optName]
if (option !== undefined) {
options[optName] = option
}
}
}
// Pass this on to the XHR
if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) {
options.withCredentials = eventSourceInitDict.withCredentials
}
req = (isSecure ? https : http).request(options, function (res) {
self.connectionInProgress = false
// Handle HTTP errors
if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) {
_emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}))
onConnectionClosed()
return
}
// Handle HTTP redirects
if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) {
var location = res.headers.location
if (!location) {
// Server sent redirect response without Location header.
_emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}))
return
}
var prevOrigin = original(url)
var nextOrigin = original(location)
hasNewOrigin = prevOrigin !== nextOrigin
if (res.statusCode === 307) reconnectUrl = url
url = location
process.nextTick(connect)
return
}
if (res.statusCode !== 200) {
_emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage}))
return self.close()
}
readyState = EventSource.OPEN
res.on('close', function () {
res.removeAllListeners('close')
res.removeAllListeners('end')
onConnectionClosed()
})
res.on('end', function () {
res.removeAllListeners('close')
res.removeAllListeners('end')
onConnectionClosed()
})
_emit('open', new Event('open'))
// text/event-stream parser adapted from webkit's
// Source/WebCore/page/EventSource.cpp
var isFirst = true
var buf
var startingPos = 0
var startingFieldLength = -1
res.on('data', function (chunk) {
buf = buf ? Buffer.concat([buf, chunk]) : chunk
if (isFirst && hasBom(buf)) {
buf = buf.slice(bom.length)
}
isFirst = false
var pos = 0
var length = buf.length
while (pos < length) {
if (discardTrailingNewline) {
if (buf[pos] === lineFeed) {
++pos
}
discardTrailingNewline = false
}
var lineLength = -1
var fieldLength = startingFieldLength
var c
for (var i = startingPos; lineLength < 0 && i < length; ++i) {
c = buf[i]
if (c === colon) {
if (fieldLength < 0) {
fieldLength = i - pos
}
} else if (c === carriageReturn) {
discardTrailingNewline = true
lineLength = i - pos
} else if (c === lineFeed) {
lineLength = i - pos
}
}
if (lineLength < 0) {
startingPos = length - pos
startingFieldLength = fieldLength
break
} else {
startingPos = 0
startingFieldLength = -1
}
parseEventStreamLine(buf, pos, fieldLength, lineLength)
pos += lineLength + 1
}
if (pos === length) {
buf = void 0
} else if (pos > 0) {
buf = buf.slice(pos)
}
})
})
req.on('error', function (err) {
self.connectionInProgress = false
onConnectionClosed(err.message)
})
if (req.setNoDelay) req.setNoDelay(true)
req.end()
}
connect()
function _emit () {
if (self.listeners(arguments[0]).length > 0) {
self.emit.apply(self, arguments)
}
}
this._close = function () {
if (readyState === EventSource.CLOSED) return
readyState = EventSource.CLOSED
if (req.abort) req.abort()
if (req.xhr && req.xhr.abort) req.xhr.abort()
}
function parseEventStreamLine (buf, pos, fieldLength, lineLength) {
if (lineLength === 0) {
if (data.length > 0) {
var type = eventName || 'message'
_emit(type, new MessageEvent(type, {
data: data.slice(0, -1), // remove trailing newline
lastEventId: lastEventId,
origin: original(url)
}))
data = ''
}
eventName = void 0
} else if (fieldLength > 0) {
var noValue = fieldLength < 0
var step = 0
var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString()
if (noValue) {
step = lineLength
} else if (buf[pos + fieldLength + 1] !== space) {
step = fieldLength + 1
} else {
step = fieldLength + 2
}
pos += step
var valueLength = lineLength - step
var value = buf.slice(pos, pos + valueLength).toString()
if (field === 'data') {
data += value + '\n'
} else if (field === 'event') {
eventName = value
} else if (field === 'id') {
lastEventId = value
} else if (field === 'retry') {
var retry = parseInt(value, 10)
if (!Number.isNaN(retry)) {
self.reconnectInterval = retry
}
}
}
}
}
module.exports = EventSource
util.inherits(EventSource, events.EventEmitter)
EventSource.prototype.constructor = EventSource; // make stacktraces readable
['open', 'error', 'message'].forEach(function (method) {
Object.defineProperty(EventSource.prototype, 'on' + method, {
/**
* Returns the current listener
*
* @return {Mixed} the set function or undefined
* @api private
*/
get: function get () {
var listener = this.listeners(method)[0]
return listener ? (listener._listener ? listener._listener : listener) : undefined
},
/**
* Start listening for events
*
* @param {Function} listener the listener
* @return {Mixed} the set function or undefined
* @api private
*/
set: function set (listener) {
this.removeAllListeners(method)
this.addEventListener(method, listener)
}
})
})
/**
* Ready states
*/
Object.defineProperty(EventSource, 'CONNECTING', {enumerable: true, value: 0})
Object.defineProperty(EventSource, 'OPEN', {enumerable: true, value: 1})
Object.defineProperty(EventSource, 'CLOSED', {enumerable: true, value: 2})
EventSource.prototype.CONNECTING = 0
EventSource.prototype.OPEN = 1
EventSource.prototype.CLOSED = 2
/**
* Closes the connection, if one is made, and sets the readyState attribute to 2 (closed)
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close
* @api public
*/
EventSource.prototype.close = function () {
this._close()
}
/**
* Emulates the W3C Browser based WebSocket interface using addEventListener.
*
* @param {String} type A string representing the event type to listen out for
* @param {Function} listener callback
* @see https://developer.mozilla.org/en/DOM/element.addEventListener
* @see http://dev.w3.org/html5/websockets/#the-websocket-interface
* @api public
*/
EventSource.prototype.addEventListener = function addEventListener (type, listener) {
if (typeof listener === 'function') {
// store a reference so we can return the original function again
listener._listener = listener
this.on(type, listener)
}
}
/**
* Emulates the W3C Browser based WebSocket interface using dispatchEvent.
*
* @param {Event} event An event to be dispatched
* @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
* @api public
*/
EventSource.prototype.dispatchEvent = function dispatchEvent (event) {
if (!event.type) {
throw new Error('UNSPECIFIED_EVENT_TYPE_ERR')
}
// if event is instance of an CustomEvent (or has 'details' property),
// send the detail object as the payload for the event
this.emit(event.type, event.detail)
}
/**
* Emulates the W3C Browser based WebSocket interface using removeEventListener.
*
* @param {String} type A string representing the event type to remove
* @param {Function} listener callback
* @see https://developer.mozilla.org/en/DOM/element.removeEventListener
* @see http://dev.w3.org/html5/websockets/#the-websocket-interface
* @api public
*/
EventSource.prototype.removeEventListener = function removeEventListener (type, listener) {
if (typeof listener === 'function') {
listener._listener = undefined
this.removeListener(type, listener)
}
}
/**
* W3C Event
*
* @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event
* @api private
*/
function Event (type, optionalProperties) {
Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true })
if (optionalProperties) {
for (var f in optionalProperties) {
if (optionalProperties.hasOwnProperty(f)) {
Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true })
}
}
}
}
/**
* W3C MessageEvent
*
* @see http://www.w3.org/TR/webmessaging/#event-definitions
* @api private
*/
function MessageEvent (type, eventInitDict) {
Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true })
for (var f in eventInitDict) {
if (eventInitDict.hasOwnProperty(f)) {
Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true })
}
}
}
/**
* Returns a new object of headers that does not include any authorization and cookie headers
*
* @param {Object} headers An object of headers ({[headerName]: headerValue})
* @return {Object} a new object of headers
* @api private
*/
function removeUnsafeHeaders (headers) {
var safe = {}
for (var key in headers) {
if (/^(cookie|authorization)$/i.test(key)) {
continue
}
safe[key] = headers[key]
}
return safe
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(13), __webpack_require__(1).Buffer))
/***/ }),
/* 165 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var ClientRequest = __webpack_require__(401)
var response = __webpack_require__(167)
var extend = __webpack_require__(410)
var statusCodes = __webpack_require__(411)
var url = __webpack_require__(92)
var http = exports
http.request = function (opts, cb) {
if (typeof opts === 'string')
opts = url.parse(opts)
else
opts = extend(opts)
// Normally, the page is loaded from http or https, so not specifying a protocol
// will result in a (valid) protocol-relative url. However, this won't work if
// the protocol is something else, like 'file:'
var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
var protocol = opts.protocol || defaultProtocol
var host = opts.hostname || opts.host
var port = opts.port
var path = opts.path || '/'
// Necessary for IPv6 addresses
if (host && host.indexOf(':') !== -1)
host = '[' + host + ']'
// This may be a relative url. The browser should always be able to interpret it correctly.
opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
opts.method = (opts.method || 'GET').toUpperCase()
opts.headers = opts.headers || {}
// Also valid opts.auth, opts.mode
var req = new ClientRequest(opts)
if (cb)
req.on('response', cb)
return req
}
http.get = function get (opts, cb) {
var req = http.request(opts, cb)
req.end()
return req
}
http.ClientRequest = ClientRequest
http.IncomingMessage = response.IncomingMessage
http.Agent = function () {}
http.Agent.defaultMaxSockets = 4
http.globalAgent = new http.Agent()
http.STATUS_CODES = statusCodes
http.METHODS = [
'CHECKOUT',
'CONNECT',
'COPY',
'DELETE',
'GET',
'HEAD',
'LOCK',
'M-SEARCH',
'MERGE',
'MKACTIVITY',
'MKCOL',
'MOVE',
'NOTIFY',
'OPTIONS',
'PATCH',
'POST',
'PROPFIND',
'PROPPATCH',
'PURGE',
'PUT',
'REPORT',
'SEARCH',
'SUBSCRIBE',
'TRACE',
'UNLOCK',
'UNSUBSCRIBE'
]
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5)))
/***/ }),
/* 166 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream)
exports.writableStream = isFunction(global.WritableStream)
exports.abortController = isFunction(global.AbortController)
exports.blobConstructor = false
try {
new Blob([new ArrayBuffer(1)])
exports.blobConstructor = true
} catch (e) {}
// The xhr request to example.com may violate some restrictive CSP configurations,
// so if we're running in a browser that supports `fetch`, avoid calling getXHR()
// and assume support for certain features below.
var xhr
function getXHR () {
// Cache the xhr value
if (xhr !== undefined) return xhr
if (global.XMLHttpRequest) {
xhr = new global.XMLHttpRequest()
// If XDomainRequest is available (ie only, where xhr might not work
// cross domain), use the page location. Otherwise use example.com
// Note: this doesn't actually make an http request.
try {
xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com')
} catch(e) {
xhr = null
}
} else {
// Service workers don't have XHR
xhr = null
}
return xhr
}
function checkTypeSupport (type) {
var xhr = getXHR()
if (!xhr) return false
try {
xhr.responseType = type
return xhr.responseType === type
} catch (e) {}
return false
}
// For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'.
// Safari 7.1 appears to have fixed this bug.
var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined'
var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice)
// If fetch is supported, then arraybuffer will be supported too. Skip calling
// checkTypeSupport(), since that calls getXHR().
exports.arraybuffer = exports.fetch || (haveArrayBuffer && checkTypeSupport('arraybuffer'))
// These next two tests unavoidably show warnings in Chrome. Since fetch will always
// be used if it's available, just return false for these to avoid the warnings.
exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream')
exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer &&
checkTypeSupport('moz-chunked-arraybuffer')
// If fetch is supported, then overrideMimeType will be supported too. Skip calling
// getXHR().
exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false)
exports.vbArray = isFunction(global.VBArray)
function isFunction (value) {
return typeof value === 'function'
}
xhr = null // Help gc
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5)))
/***/ }),
/* 167 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process, Buffer, global) {var capability = __webpack_require__(166)
var inherits = __webpack_require__(11)
var stream = __webpack_require__(168)
var rStates = exports.readyStates = {
UNSENT: 0,
OPENED: 1,
HEADERS_RECEIVED: 2,
LOADING: 3,
DONE: 4
}
var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, fetchTimer) {
var self = this
stream.Readable.call(self)
self._mode = mode
self.headers = {}
self.rawHeaders = []
self.trailers = {}
self.rawTrailers = []
// Fake the 'close' event, but only once 'end' fires
self.on('end', function () {
// The nextTick is necessary to prevent the 'request' module from causing an infinite loop
process.nextTick(function () {
self.emit('close')
})
})
if (mode === 'fetch') {
self._fetchResponse = response
self.url = response.url
self.statusCode = response.status
self.statusMessage = response.statusText
response.headers.forEach(function (header, key){
self.headers[key.toLowerCase()] = header
self.rawHeaders.push(key, header)
})
if (capability.writableStream) {
var writable = new WritableStream({
write: function (chunk) {
return new Promise(function (resolve, reject) {
if (self._destroyed) {
reject()
} else if(self.push(new Buffer(chunk))) {
resolve()
} else {
self._resumeFetch = resolve
}
})
},
close: function () {
global.clearTimeout(fetchTimer)
if (!self._destroyed)
self.push(null)
},
abort: function (err) {
if (!self._destroyed)
self.emit('error', err)
}
})
try {
response.body.pipeTo(writable).catch(function (err) {
global.clearTimeout(fetchTimer)
if (!self._destroyed)
self.emit('error', err)
})
return
} catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this
}
// fallback for when writableStream or pipeTo aren't available
var reader = response.body.getReader()
function read () {
reader.read().then(function (result) {
if (self._destroyed)
return
if (result.done) {
global.clearTimeout(fetchTimer)
self.push(null)
return
}
self.push(new Buffer(result.value))
read()
}).catch(function (err) {
global.clearTimeout(fetchTimer)
if (!self._destroyed)
self.emit('error', err)
})
}
read()
} else {
self._xhr = xhr
self._pos = 0
self.url = xhr.responseURL
self.statusCode = xhr.status
self.statusMessage = xhr.statusText
var headers = xhr.getAllResponseHeaders().split(/\r?\n/)
headers.forEach(function (header) {
var matches = header.match(/^([^:]+):\s*(.*)/)
if (matches) {
var key = matches[1].toLowerCase()
if (key === 'set-cookie') {
if (self.headers[key] === undefined) {
self.headers[key] = []
}
self.headers[key].push(matches[2])
} else if (self.headers[key] !== undefined) {
self.headers[key] += ', ' + matches[2]
} else {
self.headers[key] = matches[2]
}
self.rawHeaders.push(matches[1], matches[2])
}
})
self._charset = 'x-user-defined'
if (!capability.overrideMimeType) {
var mimeType = self.rawHeaders['mime-type']
if (mimeType) {
var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/)
if (charsetMatch) {
self._charset = charsetMatch[1].toLowerCase()
}
}
if (!self._charset)
self._charset = 'utf-8' // best guess
}
}
}
inherits(IncomingMessage, stream.Readable)
IncomingMessage.prototype._read = function () {
var self = this
var resolve = self._resumeFetch
if (resolve) {
self._resumeFetch = null
resolve()
}
}
IncomingMessage.prototype._onXHRProgress = function () {
var self = this
var xhr = self._xhr
var response = null
switch (self._mode) {
case 'text:vbarray': // For IE9
if (xhr.readyState !== rStates.DONE)
break
try {
// This fails in IE8
response = new global.VBArray(xhr.responseBody).toArray()
} catch (e) {}
if (response !== null) {
self.push(new Buffer(response))
break
}
// Falls through in IE8
case 'text':
try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4
response = xhr.responseText
} catch (e) {
self._mode = 'text:vbarray'
break
}
if (response.length > self._pos) {
var newData = response.substr(self._pos)
if (self._charset === 'x-user-defined') {
var buffer = new Buffer(newData.length)
for (var i = 0; i < newData.length; i++)
buffer[i] = newData.charCodeAt(i) & 0xff
self.push(buffer)
} else {
self.push(newData, self._charset)
}
self._pos = response.length
}
break
case 'arraybuffer':
if (xhr.readyState !== rStates.DONE || !xhr.response)
break
response = xhr.response
self.push(new Buffer(new Uint8Array(response)))
break
case 'moz-chunked-arraybuffer': // take whole
response = xhr.response
if (xhr.readyState !== rStates.LOADING || !response)
break
self.push(new Buffer(new Uint8Array(response)))
break
case 'ms-stream':
response = xhr.response
if (xhr.readyState !== rStates.LOADING)
break
var reader = new global.MSStreamReader()
reader.onprogress = function () {
if (reader.result.byteLength > self._pos) {
self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos))))
self._pos = reader.result.byteLength
}
}
reader.onload = function () {
self.push(null)
}
// reader.onerror = ??? // TODO: this
reader.readAsArrayBuffer(response)
break
}
// The ms-stream case handles end separately in reader.onload()
if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
self.push(null)
}
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(13), __webpack_require__(1).Buffer, __webpack_require__(5)))
/***/ }),
/* 168 */
/***/ (function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(169);
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = __webpack_require__(172);
exports.Duplex = __webpack_require__(38);
exports.Transform = __webpack_require__(174);
exports.PassThrough = __webpack_require__(408);
/***/ }),
/* 169 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global, process) {// 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.
/*<replacement>*/
var pna = __webpack_require__(64);
/*</replacement>*/
module.exports = Readable;
/*<replacement>*/
var isArray = __webpack_require__(99);
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Readable.ReadableState = ReadableState;
/*<replacement>*/
var EE = __webpack_require__(93).EventEmitter;
var EElistenerCount = function (emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
/*<replacement>*/
var Stream = __webpack_require__(170);
/*</replacement>*/
/*<replacement>*/
var Buffer = __webpack_require__(94).Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*</replacement>*/
/*<replacement>*/
var util = Object.create(__webpack_require__(45));
util.inherits = __webpack_require__(11);
/*</replacement>*/
/*<replacement>*/
var debugUtil = __webpack_require__(402);
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
var BufferList = __webpack_require__(403);
var destroyImpl = __webpack_require__(171);
var StringDecoder;
util.inherits(Readable, Stream);
var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
function prependListener(emitter, event, fn) {
// Sadly this is not cacheable as some libraries bundle their own
// event emitter implementation with them.
if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
// This is a hack to make sure that our error handler is attached before any
// userland ones. NEVER DO THIS. This is here only because this code needs
// to continue to work with older versions of Node.js that do not include
// the prependListener() method. The goal is to eventually remove this hack.
if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}
function ReadableState(options, stream) {
Duplex = Duplex || __webpack_require__(38);
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream.
// These options can be provided separately as readableXXX and writableXXX.
var isDuplex = stream instanceof Duplex;
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var readableHwm = options.readableHighWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// A linked list is used to store data chunks instead of an array because the
// linked list can remove elements from the beginning faster than
// array.shift()
this.buffer = new BufferList();
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the event 'readable'/'data' is emitted
// immediately, or on a later tick. We set this to true at first, because
// any actions that shouldn't happen until "later" should generally also
// not happen before the first read call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
this.resumeScheduled = false;
// has it been destroyed
this.destroyed = false;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder) StringDecoder = __webpack_require__(173).StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
Duplex = Duplex || __webpack_require__(38);
if (!(this instanceof Readable)) return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
if (options) {
if (typeof options.read === 'function') this._read = options.read;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
}
Stream.call(this);
}
Object.defineProperty(Readable.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined) {
return false;
}
return this._readableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._readableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
}
});
Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
this.push(null);
cb(err);
};
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
var state = this._readableState;
var skipChunkCheck;
if (!state.objectMode) {
if (typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = Buffer.from(chunk, encoding);
encoding = '';
}
skipChunkCheck = true;
}
} else {
skipChunkCheck = true;
}
return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
return readableAddChunk(this, chunk, null, true, false);
};
function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
var state = stream._readableState;
if (chunk === null) {
state.reading = false;
onEofChunk(stream, state);
} else {
var er;
if (!skipChunkCheck) er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (addToFront) {
if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
} else if (state.ended) {
stream.emit('error', new Error('stream.push() after EOF'));
} else {
state.reading = false;
if (state.decoder && !encoding) {
chunk = state.decoder.write(chunk);
if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
} else {
addChunk(stream, state, chunk, false);
}
}
} else if (!addToFront) {
state.reading = false;
}
}
return needMoreData(state);
}
function addChunk(stream, state, chunk, addToFront) {
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
if (state.needReadable) emitReadable(stream);
}
maybeReadMore(stream, state);
}
function chunkInvalid(state, chunk) {
var er;
if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}
Readable.prototype.isPaused = function () {
return this._readableState.flowing === false;
};
// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
if (!StringDecoder) StringDecoder = __webpack_require__(173).StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2 to prevent increasing hwm excessively in
// tiny amounts
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
n++;
}
return n;
}
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
if (n <= 0 || state.length === 0 && state.ended) return 0;
if (state.objectMode) return 1;
if (n !== n) {
// Only flow one buffer at a time
if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
}
// If we're asking for more than the current hwm, then raise the hwm.
if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
if (n <= state.length) return n;
// Don't have enough
if (!state.ended) {
state.needReadable = true;
return 0;
}
return state.length;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
debug('read', n);
n = parseInt(n, 10);
var state = this._readableState;
var nOrig = n;
if (n !== 0) state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0) endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
} else if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0) state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (!state.reading) n = howMuchToRead(nOrig, state);
}
var ret;
if (n > 0) ret = fromList(n, state);else ret = null;
if (ret === null) {
state.needReadable = true;
n = 0;
} else {
state.length -= n;
}
if (state.length === 0) {
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (!state.ended) state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended) endReadable(this);
}
if (ret !== null) this.emit('data', ret);
return ret;
};
function onEofChunk(stream, state) {
if (state.ended) return;
if (state.decoder) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
pna.nextTick(maybeReadMore_, stream, state);
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;else len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
this.emit('error', new Error('_read() is not implemented'));
};
Readable.prototype.pipe = function (dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
var endFn = doEnd ? onend : unpipe;
if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable, unpipeInfo) {
debug('onunpipe');
if (readable === src) {
if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
unpipeInfo.hasUnpiped = true;
cleanup();
}
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
var cleanedUp = false;
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', unpipe);
src.removeListener('data', ondata);
cleanedUp = true;
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
}
// If the user pushes more data while we're writing to dest then we'll end up
// in ondata again. However, we only want to increase awaitDrain once because
// dest will only emit one 'drain' event for the multiple writes.
// => Introduce a guard on increasing awaitDrain.
var increasedAwaitDrain = false;
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
increasedAwaitDrain = false;
var ret = dest.write(chunk);
if (false === ret && !increasedAwaitDrain) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
// => Check whether `dest` is still a piping destination.
if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
debug('false write response, pause', src._readableState.awaitDrain);
src._readableState.awaitDrain++;
increasedAwaitDrain = true;
}
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
}
// Make sure our error handler is attached before userland ones.
prependListener(dest, 'error', onerror);
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function () {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain) state.awaitDrain--;
if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function (dest) {
var state = this._readableState;
var unpipeInfo = { hasUnpiped: false };
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0) return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes) return this;
if (!dest) dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest) dest.emit('unpipe', this, unpipeInfo);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var i = 0; i < len; i++) {
dests[i].emit('unpipe', this, unpipeInfo);
}return this;
}
// try to find the right one.
var index = indexOf(state.pipes, dest);
if (index === -1) return this;
state.pipes.splice(index, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1) state.pipes = state.pipes[0];
dest.emit('unpipe', this, unpipeInfo);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
if (ev === 'data') {
// Start flowing on next tick if stream isn't explicitly paused
if (this._readableState.flowing !== false) this.resume();
} else if (ev === 'readable') {
var state = this._readableState;
if (!state.endEmitted && !state.readableListening) {
state.readableListening = state.needReadable = true;
state.emittedReadable = false;
if (!state.reading) {
pna.nextTick(nReadingNextTick, this);
} else if (state.length) {
emitReadable(this);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
function nReadingNextTick(self) {
debug('readable nexttick read 0');
self.read(0);
}
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
pna.nextTick(resume_, stream, state);
}
}
function resume_(stream, state) {
if (!state.reading) {
debug('resume read 0');
stream.read(0);
}
state.resumeScheduled = false;
state.awaitDrain = 0;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading) stream.read(0);
}
Readable.prototype.pause = function () {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
while (state.flowing && stream.read() !== null) {}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
var _this = this;
var state = this._readableState;
var paused = false;
stream.on('end', function () {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) _this.push(chunk);
}
_this.push(null);
});
stream.on('data', function (chunk) {
debug('wrapped data');
if (state.decoder) chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
var ret = _this.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function (method) {
return function () {
return stream[method].apply(stream, arguments);
};
}(i);
}
}
// proxy certain important events.
for (var n = 0; n < kProxyEvents.length; n++) {
stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
}
// when we try to consume some more bytes, simply unpause the
// underlying stream.
this._read = function (n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return this;
};
Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function () {
return this._readableState.highWaterMark;
}
});
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
// nothing buffered
if (state.length === 0) return null;
var ret;
if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the list
if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
state.buffer.clear();
} else {
// read part of list
ret = fromListPartial(n, state.buffer, state.decoder);
}
return ret;
}
// Extracts only enough buffered data to satisfy the amount requested.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromListPartial(n, list, hasStrings) {
var ret;
if (n < list.head.data.length) {
// slice is the same for buffers and strings
ret = list.head.data.slice(0, n);
list.head.data = list.head.data.slice(n);
} else if (n === list.head.data.length) {
// first chunk is a perfect match
ret = list.shift();
} else {
// result spans more than one buffer
ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
}
return ret;
}
// Copies a specified amount of characters from the list of buffered data
// chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBufferString(n, list) {
var p = list.head;
var c = 1;
var ret = p.data;
n -= ret.length;
while (p = p.next) {
var str = p.data;
var nb = n > str.length ? str.length : n;
if (nb === str.length) ret += str;else ret += str.slice(0, n);
n -= nb;
if (n === 0) {
if (nb === str.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = str.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
// Copies a specified amount of bytes from the list of buffered data chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBuffer(n, list) {
var ret = Buffer.allocUnsafe(n);
var p = list.head;
var c = 1;
p.data.copy(ret);
n -= p.data.length;
while (p = p.next) {
var buf = p.data;
var nb = n > buf.length ? buf.length : n;
buf.copy(ret, ret.length - n, 0, nb);
n -= nb;
if (n === 0) {
if (nb === buf.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = buf.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
pna.nextTick(endReadableNT, state, stream);
}
}
function endReadableNT(state, stream) {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
}
function indexOf(xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5), __webpack_require__(13)))
/***/ }),
/* 170 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(93).EventEmitter;
/***/ }),
/* 171 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*<replacement>*/
var pna = __webpack_require__(64);
/*</replacement>*/
// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
var _this = this;
var readableDestroyed = this._readableState && this._readableState.destroyed;
var writableDestroyed = this._writableState && this._writableState.destroyed;
if (readableDestroyed || writableDestroyed) {
if (cb) {
cb(err);
} else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
pna.nextTick(emitErrorNT, this, err);
}
return this;
}
// we set destroyed to true before firing error callbacks in order
// to make it re-entrance safe in case destroy() is called within callbacks
if (this._readableState) {
this._readableState.destroyed = true;
}
// if this is a duplex stream mark the writable part as destroyed as well
if (this._writableState) {
this._writableState.destroyed = true;
}
this._destroy(err || null, function (err) {
if (!cb && err) {
pna.nextTick(emitErrorNT, _this, err);
if (_this._writableState) {
_this._writableState.errorEmitted = true;
}
} else if (cb) {
cb(err);
}
});
return this;
}
function undestroy() {
if (this._readableState) {
this._readableState.destroyed = false;
this._readableState.reading = false;
this._readableState.ended = false;
this._readableState.endEmitted = false;
}
if (this._writableState) {
this._writableState.destroyed = false;
this._writableState.ended = false;
this._writableState.ending = false;
this._writableState.finished = false;
this._writableState.errorEmitted = false;
}
}
function emitErrorNT(self, err) {
self.emit('error', err);
}
module.exports = {
destroy: destroy,
undestroy: undestroy
};
/***/ }),
/* 172 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process, setImmediate, global) {// 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.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
/*<replacement>*/
var pna = __webpack_require__(64);
/*</replacement>*/
module.exports = Writable;
/* <replacement> */
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
this.next = null;
}
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
this.next = null;
this.entry = null;
this.finish = function () {
onCorkedFinish(_this, state);
};
}
/* </replacement> */
/*<replacement>*/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = Object.create(__webpack_require__(45));
util.inherits = __webpack_require__(11);
/*</replacement>*/
/*<replacement>*/
var internalUtil = {
deprecate: __webpack_require__(407)
};
/*</replacement>*/
/*<replacement>*/
var Stream = __webpack_require__(170);
/*</replacement>*/
/*<replacement>*/
var Buffer = __webpack_require__(94).Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*</replacement>*/
var destroyImpl = __webpack_require__(171);
util.inherits(Writable, Stream);
function nop() {}
function WritableState(options, stream) {
Duplex = Duplex || __webpack_require__(38);
options = options || {};
// Duplex streams are both readable and writable, but share
// the same options object.
// However, some cases require setting options to different
// values for the readable and the writable sides of the duplex stream.
// These options can be provided separately as readableXXX and writableXXX.
var isDuplex = stream instanceof Duplex;
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var writableHwm = options.writableHighWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// if _final has been called
this.finalCalled = false;
// drain event flag.
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// has it been destroyed
this.destroyed = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function (er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.bufferedRequest = null;
this.lastBufferedRequest = null;
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
// count buffered requests
this.bufferedRequestCount = 0;
// allocate the first CorkedRequest, there is always
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function getBuffer() {
var current = this.bufferedRequest;
var out = [];
while (current) {
out.push(current);
current = current.next;
}
return out;
};
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function () {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
});
} catch (_) {}
})();
// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
realHasInstance = Function.prototype[Symbol.hasInstance];
Object.defineProperty(Writable, Symbol.hasInstance, {
value: function (object) {
if (realHasInstance.call(this, object)) return true;
if (this !== Writable) return false;
return object && object._writableState instanceof WritableState;
}
});
} else {
realHasInstance = function (object) {
return object instanceof this;
};
}
function Writable(options) {
Duplex = Duplex || __webpack_require__(38);
// Writable ctor is applied to Duplexes, too.
// `realHasInstance` is necessary because using plain `instanceof`
// would return false, as no `_writableState` property is attached.
// Trying to use the custom `instanceof` for Writable here will also break the
// Node.js LazyTransform implementation, which has a non-trivial getter for
// `_writableState` that would lead to infinite recursion.
if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
return new Writable(options);
}
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
if (options) {
if (typeof options.write === 'function') this._write = options.write;
if (typeof options.writev === 'function') this._writev = options.writev;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
if (typeof options.final === 'function') this._final = options.final;
}
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
this.emit('error', new Error('Cannot pipe, not readable'));
};
function writeAfterEnd(stream, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
pna.nextTick(cb, er);
}
// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
var valid = true;
var er = false;
if (chunk === null) {
er = new TypeError('May not write null values to stream');
} else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
if (er) {
stream.emit('error', er);
pna.nextTick(cb, er);
valid = false;
}
return valid;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
var isBuf = !state.objectMode && _isUint8Array(chunk);
if (isBuf && !Buffer.isBuffer(chunk)) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
if (typeof cb !== 'function') cb = nop;
if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function () {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function () {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
this._writableState.defaultEncoding = encoding;
return this;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = Buffer.from(chunk, encoding);
}
return chunk;
}
Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
// making it explicit this property is not enumerable
// because otherwise some prototype manipulation in
// userland will fail
enumerable: false,
get: function () {
return this._writableState.highWaterMark;
}
});
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
if (!isBuf) {
var newChunk = decodeChunk(state, chunk, encoding);
if (chunk !== newChunk) {
isBuf = true;
encoding = 'buffer';
chunk = newChunk;
}
}
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = {
chunk: chunk,
encoding: encoding,
isBuf: isBuf,
callback: cb,
next: null
};
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
if (sync) {
// defer the callback if we are being called synchronously
// to avoid piling up things on the stack
pna.nextTick(cb, er);
// this can emit finish, and it will always happen
// after error
pna.nextTick(finishMaybe, stream, state);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
} else {
// the caller expect this to happen before if
// it is async
cb(er);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
// this can emit finish, but finish must
// always follow error
finishMaybe(stream, state);
}
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(state);
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
if (sync) {
/*<replacement>*/
asyncWrite(afterWrite, stream, state, finished, cb);
/*</replacement>*/
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
var count = 0;
var allBuffers = true;
while (entry) {
buffer[count] = entry;
if (!entry.isBuf) allBuffers = false;
entry = entry.next;
count += 1;
}
buffer.allBuffers = allBuffers;
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
// as the hot path ends with doWrite
state.pendingcb++;
state.lastBufferedRequest = null;
if (holder.next) {
state.corkedRequestsFree = holder.next;
holder.next = null;
} else {
state.corkedRequestsFree = new CorkedRequest(state);
}
state.bufferedRequestCount = 0;
} else {
// Slow case, write chunks one-by-one
while (entry) {
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
state.bufferedRequestCount--;
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
break;
}
}
if (entry === null) state.lastBufferedRequest = null;
}
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new Error('_write() is not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished) endWritable(this, state, cb);
};
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
stream._final(function (err) {
state.pendingcb--;
if (err) {
stream.emit('error', err);
}
state.prefinished = true;
stream.emit('prefinish');
finishMaybe(stream, state);
});
}
function prefinish(stream, state) {
if (!state.prefinished && !state.finalCalled) {
if (typeof stream._final === 'function') {
state.pendingcb++;
state.finalCalled = true;
pna.nextTick(callFinal, stream, state);
} else {
state.prefinished = true;
stream.emit('prefinish');
}
}
}
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
prefinish(stream, state);
if (state.pendingcb === 0) {
state.finished = true;
stream.emit('finish');
}
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
function onCorkedFinish(corkReq, state, err) {
var entry = corkReq.entry;
corkReq.entry = null;
while (entry) {
var cb = entry.callback;
state.pendingcb--;
cb(err);
entry = entry.next;
}
if (state.corkedRequestsFree) {
state.corkedRequestsFree.next = corkReq;
} else {
state.corkedRequestsFree = corkReq;
}
}
Object.defineProperty(Writable.prototype, 'destroyed', {
get: function () {
if (this._writableState === undefined) {
return false;
}
return this._writableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._writableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._writableState.destroyed = value;
}
});
Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
this.end();
cb(err);
};
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(13), __webpack_require__(405).setImmediate, __webpack_require__(5)))
/***/ }),
/* 173 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 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.
/*<replacement>*/
var Buffer = __webpack_require__(21).Buffer;
/*</replacement>*/
var isEncoding = Buffer.isEncoding || function (encoding) {
encoding = '' + 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 _normalizeEncoding(enc) {
if (!enc) return 'utf8';
var retried;
while (true) {
switch (enc) {
case 'utf8':
case 'utf-8':
return 'utf8';
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return 'utf16le';
case 'latin1':
case 'binary':
return 'latin1';
case 'base64':
case 'ascii':
case 'hex':
return enc;
default:
if (retried) return; // undefined
enc = ('' + enc).toLowerCase();
retried = true;
}
}
};
// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
var nenc = _normalizeEncoding(enc);
if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
return nenc || enc;
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
exports.StringDecoder = StringDecoder;
function StringDecoder(encoding) {
this.encoding = normalizeEncoding(encoding);
var nb;
switch (this.encoding) {
case 'utf16le':
this.text = utf16Text;
this.end = utf16End;
nb = 4;
break;
case 'utf8':
this.fillLast = utf8FillLast;
nb = 4;
break;
case 'base64':
this.text = base64Text;
this.end = base64End;
nb = 3;
break;
default:
this.write = simpleWrite;
this.end = simpleEnd;
return;
}
this.lastNeed = 0;
this.lastTotal = 0;
this.lastChar = Buffer.allocUnsafe(nb);
}
StringDecoder.prototype.write = function (buf) {
if (buf.length === 0) return '';
var r;
var i;
if (this.lastNeed) {
r = this.fillLast(buf);
if (r === undefined) return '';
i = this.lastNeed;
this.lastNeed = 0;
} else {
i = 0;
}
if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
return r || '';
};
StringDecoder.prototype.end = utf8End;
// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;
// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
this.lastNeed -= buf.length;
};
// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte. If an invalid byte is detected, -2 is returned.
function utf8CheckByte(byte) {
if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
return byte >> 6 === 0x02 ? -1 : -2;
}
// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
var j = buf.length - 1;
if (j < i) return 0;
var nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 1;
return nb;
}
if (--j < i || nb === -2) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 2;
return nb;
}
if (--j < i || nb === -2) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) {
if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
}
return nb;
}
return 0;
}
// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
if ((buf[0] & 0xC0) !== 0x80) {
self.lastNeed = 0;
return '\ufffd';
}
if (self.lastNeed > 1 && buf.length > 1) {
if ((buf[1] & 0xC0) !== 0x80) {
self.lastNeed = 1;
return '\ufffd';
}
if (self.lastNeed > 2 && buf.length > 2) {
if ((buf[2] & 0xC0) !== 0x80) {
self.lastNeed = 2;
return '\ufffd';
}
}
}
}
// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
var p = this.lastTotal - this.lastNeed;
var r = utf8CheckExtraBytes(this, buf, p);
if (r !== undefined) return r;
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, p, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, p, 0, buf.length);
this.lastNeed -= buf.length;
}
// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
var total = utf8CheckIncomplete(this, buf, i);
if (!this.lastNeed) return buf.toString('utf8', i);
this.lastTotal = total;
var end = buf.length - (total - this.lastNeed);
buf.copy(this.lastChar, 0, end);
return buf.toString('utf8', i, end);
}
// For UTF-8, a replacement character is added when ending on a partial
// character.
function utf8End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + '\ufffd';
return r;
}
// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
if ((buf.length - i) % 2 === 0) {
var r = buf.toString('utf16le', i);
if (r) {
var c = r.charCodeAt(r.length - 1);
if (c >= 0xD800 && c <= 0xDBFF) {
this.lastNeed = 2;
this.lastTotal = 4;
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
return r.slice(0, -1);
}
}
return r;
}
this.lastNeed = 1;
this.lastTotal = 2;
this.lastChar[0] = buf[buf.length - 1];
return buf.toString('utf16le', i, buf.length - 1);
}
// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) {
var end = this.lastTotal - this.lastNeed;
return r + this.lastChar.toString('utf16le', 0, end);
}
return r;
}
function base64Text(buf, i) {
var n = (buf.length - i) % 3;
if (n === 0) return buf.toString('base64', i);
this.lastNeed = 3 - n;
this.lastTotal = 3;
if (n === 1) {
this.lastChar[0] = buf[buf.length - 1];
} else {
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
}
return buf.toString('base64', i, buf.length - n);
}
function base64End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
return r;
}
// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
return buf.toString(this.encoding);
}
function simpleEnd(buf) {
return buf && buf.length ? this.write(buf) : '';
}
/***/ }),
/* 174 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 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.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
module.exports = Transform;
var Duplex = __webpack_require__(38);
/*<replacement>*/
var util = Object.create(__webpack_require__(45));
util.inherits = __webpack_require__(11);
/*</replacement>*/
util.inherits(Transform, Duplex);
function afterTransform(er, data) {
var ts = this._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb) {
return this.emit('error', new Error('write callback called multiple times'));
}
ts.writechunk = null;
ts.writecb = null;
if (data != null) // single equals check for both `null` and `undefined`
this.push(data);
cb(er);
var rs = this._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
this._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
Duplex.call(this, options);
this._transformState = {
afterTransform: afterTransform.bind(this),
needTransform: false,
transforming: false,
writecb: null,
writechunk: null,
writeencoding: null
};
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
if (typeof options.flush === 'function') this._flush = options.flush;
}
// When the writable side finishes, then flush out anything remaining.
this.on('prefinish', prefinish);
}
function prefinish() {
var _this = this;
if (typeof this._flush === 'function') {
this._flush(function (er, data) {
done(_this, er, data);
});
} else {
done(this, null, null);
}
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
throw new Error('_transform() is not implemented');
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
Transform.prototype._destroy = function (err, cb) {
var _this2 = this;
Duplex.prototype._destroy.call(this, err, function (err2) {
cb(err2);
_this2.emit('close');
});
};
function done(stream, er, data) {
if (er) return stream.emit('error', er);
if (data != null) // single equals check for both `null` and `undefined`
stream.push(data);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
return stream.push(null);
}
/***/ }),
/* 175 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StellarTomlResolver = exports.STELLAR_TOML_MAX_SIZE = void 0;
var tslib_1 = __webpack_require__(2);
var axios_1 = tslib_1.__importDefault(__webpack_require__(61));
var toml_1 = tslib_1.__importDefault(__webpack_require__(432));
var config_1 = __webpack_require__(60);
exports.STELLAR_TOML_MAX_SIZE = 100 * 1024;
var CancelToken = axios_1.default.CancelToken;
var StellarTomlResolver = (function () {
function StellarTomlResolver() {
}
StellarTomlResolver.resolve = function (domain, opts) {
if (opts === void 0) { opts = {}; }
return tslib_1.__awaiter(this, void 0, void 0, function () {
var allowHttp, timeout, protocol;
return tslib_1.__generator(this, function (_a) {
allowHttp = typeof opts.allowHttp === "undefined"
? config_1.Config.isAllowHttp()
: opts.allowHttp;
timeout = typeof opts.timeout === "undefined" ? config_1.Config.getTimeout() : opts.timeout;
protocol = allowHttp ? "http" : "https";
return [2, axios_1.default
.get(protocol + "://" + domain + "/.well-known/stellar.toml", {
maxContentLength: exports.STELLAR_TOML_MAX_SIZE,
cancelToken: timeout
? new CancelToken(function (cancel) {
return setTimeout(function () { return cancel("timeout of " + timeout + "ms exceeded"); }, timeout);
})
: undefined,
timeout: timeout,
})
.then(function (response) {
try {
var tomlObject = toml_1.default.parse(response.data);
return Promise.resolve(tomlObject);
}
catch (e) {
return Promise.reject(new Error("stellar.toml is invalid - Parsing error on line " + e.line + ", column " + e.column + ": " + e.message));
}
})
.catch(function (err) {
if (err.message.match(/^maxContentLength size/)) {
throw new Error("stellar.toml file exceeds allowed size of " + exports.STELLAR_TOML_MAX_SIZE);
}
else {
throw err;
}
})];
});
});
};
return StellarTomlResolver;
}());
exports.StellarTomlResolver = StellarTomlResolver;
/***/ }),
/* 176 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
module.exports = __webpack_require__(177);
module.exports.axios = __webpack_require__(61);
module.exports.StellarBase = __webpack_require__(29);
/***/ }),
/* 177 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.version = void 0;
var tslib_1 = __webpack_require__(2);
__webpack_require__(178).polyfill();
var version = __webpack_require__(65).version;
exports.version = version;
tslib_1.__exportStar(__webpack_require__(179), exports);
tslib_1.__exportStar(__webpack_require__(180), exports);
tslib_1.__exportStar(__webpack_require__(95), exports);
tslib_1.__exportStar(__webpack_require__(36), exports);
var config_1 = __webpack_require__(60);
Object.defineProperty(exports, "Config", { enumerable: true, get: function () { return config_1.Config; } });
var server_1 = __webpack_require__(364);
Object.defineProperty(exports, "Server", { enumerable: true, get: function () { return server_1.Server; } });
var federation_server_1 = __webpack_require__(431);
Object.defineProperty(exports, "FederationServer", { enumerable: true, get: function () { return federation_server_1.FederationServer; } });
Object.defineProperty(exports, "FEDERATION_RESPONSE_MAX_SIZE", { enumerable: true, get: function () { return federation_server_1.FEDERATION_RESPONSE_MAX_SIZE; } });
var stellar_toml_resolver_1 = __webpack_require__(175);
Object.defineProperty(exports, "StellarTomlResolver", { enumerable: true, get: function () { return stellar_toml_resolver_1.StellarTomlResolver; } });
Object.defineProperty(exports, "STELLAR_TOML_MAX_SIZE", { enumerable: true, get: function () { return stellar_toml_resolver_1.STELLAR_TOML_MAX_SIZE; } });
var horizon_axios_client_1 = __webpack_require__(91);
Object.defineProperty(exports, "HorizonAxiosClient", { enumerable: true, get: function () { return horizon_axios_client_1.default; } });
Object.defineProperty(exports, "SERVER_TIME_MAP", { enumerable: true, get: function () { return horizon_axios_client_1.SERVER_TIME_MAP; } });
Object.defineProperty(exports, "getCurrentServerTime", { enumerable: true, get: function () { return horizon_axios_client_1.getCurrentServerTime; } });
tslib_1.__exportStar(__webpack_require__(435), exports);
tslib_1.__exportStar(__webpack_require__(29), exports);
exports.default = module.exports;
/***/ }),
/* 178 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process, global) {/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* @version v4.2.8+1e68dce6
*/
(function (global, factory) {
true ? module.exports = factory() :
undefined;
}(this, (function () { 'use strict';
function objectOrFunction(x) {
var type = typeof x;
return x !== null && (type === 'object' || type === 'function');
}
function isFunction(x) {
return typeof x === 'function';
}
var _isArray = void 0;
if (Array.isArray) {
_isArray = Array.isArray;
} else {
_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
}
var isArray = _isArray;
var len = 0;
var vertxNext = void 0;
var customSchedulerFn = void 0;
var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
};
function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
function setAsap(asapFn) {
asap = asapFn;
}
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function () {
return process.nextTick(flush);
};
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function () {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function () {
node.data = iterations = ++iterations % 2;
};
}
// web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function () {
return channel.port2.postMessage(0);
};
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var globalSetTimeout = setTimeout;
return function () {
return globalSetTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
var vertx = Function('return this')().require('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
var scheduleFlush = void 0;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && "function" === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}
function then(onFulfillment, onRejection) {
var parent = this;
var child = new this.constructor(noop);
if (child[PROMISE_ID] === undefined) {
makePromise(child);
}
var _state = parent._state;
if (_state) {
var callback = arguments[_state - 1];
asap(function () {
return invokeCallback(_state, child, callback, parent._result);
});
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@static
@param {Any} value value that the returned promise will be resolved with
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve$1(object) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(noop);
resolve(promise, object);
return promise;
}
var PROMISE_ID = Math.random().toString(36).substring(2);
function noop() {}
var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
try {
then$$1.call(value, fulfillmentHandler, rejectionHandler);
} catch (e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then$$1) {
asap(function (promise) {
var sealed = false;
var error = tryThen(then$$1, thenable, function (value) {
if (sealed) {
return;
}
sealed = true;
if (thenable !== value) {
resolve(promise, value);
} else {
fulfill(promise, value);
}
}, function (reason) {
if (sealed) {
return;
}
sealed = true;
reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, function (value) {
return resolve(promise, value);
}, function (reason) {
return reject(promise, reason);
});
}
}
function handleMaybeThenable(promise, maybeThenable, then$$1) {
if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
handleOwnThenable(promise, maybeThenable);
} else {
if (then$$1 === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then$$1)) {
handleForeignThenable(promise, maybeThenable, then$$1);
} else {
fulfill(promise, maybeThenable);
}
}
}
function resolve(promise, value) {
if (promise === value) {
reject(promise, selfFulfillment());
} else if (objectOrFunction(value)) {
var then$$1 = void 0;
try {
then$$1 = value.then;
} catch (error) {
reject(promise, error);
return;
}
handleMaybeThenable(promise, value, then$$1);
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length !== 0) {
asap(publish, promise);
}
}
function reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
asap(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
var _subscribers = parent._subscribers;
var length = _subscribers.length;
parent._onerror = null;
_subscribers[length] = child;
_subscribers[length + FULFILLED] = onFulfillment;
_subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
asap(publish, parent);
}
}
function publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) {
return;
}
var child = void 0,
callback = void 0,
detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value = void 0,
error = void 0,
succeeded = true;
if (hasCallback) {
try {
value = callback(detail);
} catch (e) {
succeeded = false;
error = e;
}
if (promise === value) {
reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (succeeded === false) {
reject(promise, error);
} else if (settled === FULFILLED) {
fulfill(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
}
function initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value) {
resolve(promise, value);
}, function rejectPromise(reason) {
reject(promise, reason);
});
} catch (e) {
reject(promise, e);
}
}
var id = 0;
function nextId() {
return id++;
}
function makePromise(promise) {
promise[PROMISE_ID] = id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
function validationError() {
return new Error('Array Methods must be provided an Array');
}
var Enumerator = function () {
function Enumerator(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate(input);
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
reject(this.promise, validationError());
}
}
Enumerator.prototype._enumerate = function _enumerate(input) {
for (var i = 0; this._state === PENDING && i < input.length; i++) {
this._eachEntry(input[i], i);
}
};
Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
var c = this._instanceConstructor;
var resolve$$1 = c.resolve;
if (resolve$$1 === resolve$1) {
var _then = void 0;
var error = void 0;
var didError = false;
try {
_then = entry.then;
} catch (e) {
didError = true;
error = e;
}
if (_then === then && entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof _then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise$1) {
var promise = new c(noop);
if (didError) {
reject(promise, error);
} else {
handleMaybeThenable(promise, entry, _then);
}
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(function (resolve$$1) {
return resolve$$1(entry);
}), i);
}
} else {
this._willSettleAt(resolve$$1(entry), i);
}
};
Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
var promise = this.promise;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
};
Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
var enumerator = this;
subscribe(promise, undefined, function (value) {
return enumerator._settledAt(FULFILLED, i, value);
}, function (reason) {
return enumerator._settledAt(REJECTED, i, reason);
});
};
return Enumerator;
}();
/**
`Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@static
@param {Array} entries array of promises
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
function all(entries) {
return new Enumerator(this, entries).promise;
}
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@static
@param {Array} promises array of promises to observe
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
function race(entries) {
/*jshint validthis:true */
var Constructor = this;
if (!isArray(entries)) {
return new Constructor(function (_, reject) {
return reject(new TypeError('You must pass an array to race.'));
});
} else {
return new Constructor(function (resolve, reject) {
var length = entries.length;
for (var i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject$1(reason) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor(noop);
reject(promise, reason);
return promise;
}
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {Function} resolver
Useful for tooling.
@constructor
*/
var Promise$1 = function () {
function Promise(resolver) {
this[PROMISE_ID] = nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise ? initializePromise(this, resolver) : needsNew();
}
}
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
let result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
let author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
Promise.prototype.catch = function _catch(onRejection) {
return this.then(null, onRejection);
};
/**
`finally` will be invoked regardless of the promise's fate just as native
try/catch/finally behaves
Synchronous example:
```js
findAuthor() {
if (Math.random() > 0.5) {
throw new Error();
}
return new Author();
}
try {
return findAuthor(); // succeed or fail
} catch(error) {
return findOtherAuther();
} finally {
// always runs
// doesn't affect the return value
}
```
Asynchronous example:
```js
findAuthor().catch(function(reason){
return findOtherAuther();
}).finally(function(){
// author was either found, or not
});
```
@method finally
@param {Function} callback
@return {Promise}
*/
Promise.prototype.finally = function _finally(callback) {
var promise = this;
var constructor = promise.constructor;
if (isFunction(callback)) {
return promise.then(function (value) {
return constructor.resolve(callback()).then(function () {
return value;
});
}, function (reason) {
return constructor.resolve(callback()).then(function () {
throw reason;
});
});
}
return promise.then(callback, callback);
};
return Promise;
}();
Promise$1.prototype.then = then;
Promise$1.all = all;
Promise$1.race = race;
Promise$1.resolve = resolve$1;
Promise$1.reject = reject$1;
Promise$1._setScheduler = setScheduler;
Promise$1._setAsap = setAsap;
Promise$1._asap = asap;
/*global self*/
function polyfill() {
var local = void 0;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var P = local.Promise;
if (P) {
var promiseToString = null;
try {
promiseToString = Object.prototype.toString.call(P.resolve());
} catch (e) {
// silently ignored
}
if (promiseToString === '[object Promise]' && !P.cast) {
return;
}
}
local.Promise = Promise$1;
}
// Strange compat..
Promise$1.polyfill = polyfill;
Promise$1.Promise = Promise$1;
return Promise$1;
})));
//# sourceMappingURL=es6-promise.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(13), __webpack_require__(5)))
/***/ }),
/* 179 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Horizon = void 0;
var Horizon;
(function (Horizon) {
var LiquidityPoolType;
(function (LiquidityPoolType) {
LiquidityPoolType["constantProduct"] = "constant_product";
})(LiquidityPoolType = Horizon.LiquidityPoolType || (Horizon.LiquidityPoolType = {}));
var OperationResponseType;
(function (OperationResponseType) {
OperationResponseType["createAccount"] = "create_account";
OperationResponseType["payment"] = "payment";
OperationResponseType["pathPayment"] = "path_payment_strict_receive";
OperationResponseType["createPassiveOffer"] = "create_passive_sell_offer";
OperationResponseType["manageOffer"] = "manage_sell_offer";
OperationResponseType["setOptions"] = "set_options";
OperationResponseType["changeTrust"] = "change_trust";
OperationResponseType["allowTrust"] = "allow_trust";
OperationResponseType["accountMerge"] = "account_merge";
OperationResponseType["inflation"] = "inflation";
OperationResponseType["manageData"] = "manage_data";
OperationResponseType["bumpSequence"] = "bump_sequence";
OperationResponseType["manageBuyOffer"] = "manage_buy_offer";
OperationResponseType["pathPaymentStrictSend"] = "path_payment_strict_send";
OperationResponseType["createClaimableBalance"] = "create_claimable_balance";
OperationResponseType["claimClaimableBalance"] = "claim_claimable_balance";
OperationResponseType["beginSponsoringFutureReserves"] = "begin_sponsoring_future_reserves";
OperationResponseType["endSponsoringFutureReserves"] = "end_sponsoring_future_reserves";
OperationResponseType["revokeSponsorship"] = "revoke_sponsorship";
OperationResponseType["clawback"] = "clawback";
OperationResponseType["clawbackClaimableBalance"] = "clawback_claimable_balance";
OperationResponseType["setTrustLineFlags"] = "set_trust_line_flags";
OperationResponseType["liquidityPoolDeposit"] = "liquidity_pool_deposit";
OperationResponseType["liquidityPoolWithdraw"] = "liquidity_pool_withdraw";
})(OperationResponseType = Horizon.OperationResponseType || (Horizon.OperationResponseType = {}));
var OperationResponseTypeI;
(function (OperationResponseTypeI) {
OperationResponseTypeI[OperationResponseTypeI["createAccount"] = 0] = "createAccount";
OperationResponseTypeI[OperationResponseTypeI["payment"] = 1] = "payment";
OperationResponseTypeI[OperationResponseTypeI["pathPayment"] = 2] = "pathPayment";
OperationResponseTypeI[OperationResponseTypeI["createPassiveOffer"] = 3] = "createPassiveOffer";
OperationResponseTypeI[OperationResponseTypeI["manageOffer"] = 4] = "manageOffer";
OperationResponseTypeI[OperationResponseTypeI["setOptions"] = 5] = "setOptions";
OperationResponseTypeI[OperationResponseTypeI["changeTrust"] = 6] = "changeTrust";
OperationResponseTypeI[OperationResponseTypeI["allowTrust"] = 7] = "allowTrust";
OperationResponseTypeI[OperationResponseTypeI["accountMerge"] = 8] = "accountMerge";
OperationResponseTypeI[OperationResponseTypeI["inflation"] = 9] = "inflation";
OperationResponseTypeI[OperationResponseTypeI["manageData"] = 10] = "manageData";
OperationResponseTypeI[OperationResponseTypeI["bumpSequence"] = 11] = "bumpSequence";
OperationResponseTypeI[OperationResponseTypeI["manageBuyOffer"] = 12] = "manageBuyOffer";
OperationResponseTypeI[OperationResponseTypeI["pathPaymentStrictSend"] = 13] = "pathPaymentStrictSend";
OperationResponseTypeI[OperationResponseTypeI["createClaimableBalance"] = 14] = "createClaimableBalance";
OperationResponseTypeI[OperationResponseTypeI["claimClaimableBalance"] = 15] = "claimClaimableBalance";
OperationResponseTypeI[OperationResponseTypeI["beginSponsoringFutureReserves"] = 16] = "beginSponsoringFutureReserves";
OperationResponseTypeI[OperationResponseTypeI["endSponsoringFutureReserves"] = 17] = "endSponsoringFutureReserves";
OperationResponseTypeI[OperationResponseTypeI["revokeSponsorship"] = 18] = "revokeSponsorship";
OperationResponseTypeI[OperationResponseTypeI["clawback"] = 19] = "clawback";
OperationResponseTypeI[OperationResponseTypeI["clawbackClaimableBalance"] = 20] = "clawbackClaimableBalance";
OperationResponseTypeI[OperationResponseTypeI["setTrustLineFlags"] = 21] = "setTrustLineFlags";
OperationResponseTypeI[OperationResponseTypeI["liquidityPoolDeposit"] = 22] = "liquidityPoolDeposit";
OperationResponseTypeI[OperationResponseTypeI["liquidityPoolWithdraw"] = 23] = "liquidityPoolWithdraw";
})(OperationResponseTypeI = Horizon.OperationResponseTypeI || (Horizon.OperationResponseTypeI = {}));
var TransactionFailedResultCodes;
(function (TransactionFailedResultCodes) {
TransactionFailedResultCodes["TX_FAILED"] = "tx_failed";
TransactionFailedResultCodes["TX_BAD_SEQ"] = "tx_bad_seq";
TransactionFailedResultCodes["TX_BAD_AUTH"] = "tx_bad_auth";
TransactionFailedResultCodes["TX_BAD_AUTH_EXTRA"] = "tx_bad_auth_extra";
TransactionFailedResultCodes["TX_FEE_BUMP_INNER_SUCCESS"] = "tx_fee_bump_inner_success";
TransactionFailedResultCodes["TX_FEE_BUMP_INNER_FAILED"] = "tx_fee_bump_inner_failed";
TransactionFailedResultCodes["TX_NOT_SUPPORTED"] = "tx_not_supported";
TransactionFailedResultCodes["TX_SUCCESS"] = "tx_success";
TransactionFailedResultCodes["TX_TOO_EARLY"] = "tx_too_early";
TransactionFailedResultCodes["TX_TOO_LATE"] = "tx_too_late";
TransactionFailedResultCodes["TX_MISSING_OPERATION"] = "tx_missing_operation";
TransactionFailedResultCodes["TX_INSUFFICIENT_BALANCE"] = "tx_insufficient_balance";
TransactionFailedResultCodes["TX_NO_SOURCE_ACCOUNT"] = "tx_no_source_account";
TransactionFailedResultCodes["TX_INSUFFICIENT_FEE"] = "tx_insufficient_fee";
TransactionFailedResultCodes["TX_INTERNAL_ERROR"] = "tx_internal_error";
})(TransactionFailedResultCodes = Horizon.TransactionFailedResultCodes || (Horizon.TransactionFailedResultCodes = {}));
})(Horizon = exports.Horizon || (exports.Horizon = {}));
/***/ }),
/* 180 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServerApi = void 0;
var ServerApi;
(function (ServerApi) {
var TradeType;
(function (TradeType) {
TradeType["all"] = "all";
TradeType["liquidityPools"] = "liquidity_pool";
TradeType["orderbook"] = "orderbook";
})(TradeType = ServerApi.TradeType || (ServerApi.TradeType = {}));
})(ServerApi = exports.ServerApi || (exports.ServerApi = {}));
/***/ }),
/* 181 */
/***/ (function(module, exports, __webpack_require__) {
var baseFor = __webpack_require__(66),
castFunction = __webpack_require__(67),
keysIn = __webpack_require__(24);
/**
* Iterates over own and inherited enumerable string keyed properties of an
* object and invokes `iteratee` for each property. The iteratee is invoked
* with three arguments: (value, key, object). Iteratee functions may exit
* iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forInRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forIn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
*/
function forIn(object, iteratee) {
return object == null
? object
: baseFor(object, castFunction(iteratee), keysIn);
}
module.exports = forIn;
/***/ }),
/* 182 */
/***/ (function(module, exports) {
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
module.exports = createBaseFor;
/***/ }),
/* 183 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(20),
isObjectLike = __webpack_require__(12);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
module.exports = baseIsArguments;
/***/ }),
/* 184 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(39);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Built-in value references. */
var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
module.exports = getRawTag;
/***/ }),
/* 185 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
module.exports = objectToString;
/***/ }),
/* 186 */
/***/ (function(module, exports) {
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
module.exports = stubFalse;
/***/ }),
/* 187 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(20),
isLength = __webpack_require__(69),
isObjectLike = __webpack_require__(12);
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
module.exports = baseIsTypedArray;
/***/ }),
/* 188 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(18),
isPrototype = __webpack_require__(49),
nativeKeysIn = __webpack_require__(189);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject(object)) {
return nativeKeysIn(object);
}
var isProto = isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
module.exports = baseKeysIn;
/***/ }),
/* 189 */
/***/ (function(module, exports) {
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
module.exports = nativeKeysIn;
/***/ }),
/* 190 */
/***/ (function(module, exports, __webpack_require__) {
var exports = module.exports = function SHA (algorithm) {
algorithm = algorithm.toLowerCase()
var Algorithm = exports[algorithm]
if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
return new Algorithm()
}
exports.sha = __webpack_require__(191)
exports.sha1 = __webpack_require__(194)
exports.sha224 = __webpack_require__(195)
exports.sha256 = __webpack_require__(100)
exports.sha384 = __webpack_require__(196)
exports.sha512 = __webpack_require__(101)
/***/ }),
/* 191 */
/***/ (function(module, exports, __webpack_require__) {
/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
* in FIPS PUB 180-1
* This source code is derived from sha1.js of the same repository.
* The difference between SHA-0 and SHA-1 is just a bitwise rotate left
* operation was added.
*/
var inherits = __webpack_require__(11)
var Hash = __webpack_require__(31)
var Buffer = __webpack_require__(21).Buffer
var K = [
0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
]
var W = new Array(80)
function Sha () {
this.init()
this._w = W
Hash.call(this, 64, 56)
}
inherits(Sha, Hash)
Sha.prototype.init = function () {
this._a = 0x67452301
this._b = 0xefcdab89
this._c = 0x98badcfe
this._d = 0x10325476
this._e = 0xc3d2e1f0
return this
}
function rotl5 (num) {
return (num << 5) | (num >>> 27)
}
function rotl30 (num) {
return (num << 30) | (num >>> 2)
}
function ft (s, b, c, d) {
if (s === 0) return (b & c) | ((~b) & d)
if (s === 2) return (b & c) | (b & d) | (c & d)
return b ^ c ^ d
}
Sha.prototype._update = function (M) {
var W = this._w
var a = this._a | 0
var b = this._b | 0
var c = this._c | 0
var d = this._d | 0
var e = this._e | 0
for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
for (var j = 0; j < 80; ++j) {
var s = ~~(j / 20)
var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
e = d
d = c
c = rotl30(b)
b = a
a = t
}
this._a = (a + this._a) | 0
this._b = (b + this._b) | 0
this._c = (c + this._c) | 0
this._d = (d + this._d) | 0
this._e = (e + this._e) | 0
}
Sha.prototype._hash = function () {
var H = Buffer.allocUnsafe(20)
H.writeInt32BE(this._a | 0, 0)
H.writeInt32BE(this._b | 0, 4)
H.writeInt32BE(this._c | 0, 8)
H.writeInt32BE(this._d | 0, 12)
H.writeInt32BE(this._e | 0, 16)
return H
}
module.exports = Sha
/***/ }),
/* 192 */
/***/ (function(module, exports, __webpack_require__) {
"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
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
var i
for (i = 0; i < len; 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[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = 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) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
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 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]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}
/***/ }),
/* 193 */
/***/ (function(module, exports) {
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = ((value * c) - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
/***/ }),
/* 194 */
/***/ (function(module, exports, __webpack_require__) {
/*
* A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
* in FIPS PUB 180-1
* Version 2.1a Copyright Paul Johnston 2000 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for details.
*/
var inherits = __webpack_require__(11)
var Hash = __webpack_require__(31)
var Buffer = __webpack_require__(21).Buffer
var K = [
0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
]
var W = new Array(80)
function Sha1 () {
this.init()
this._w = W
Hash.call(this, 64, 56)
}
inherits(Sha1, Hash)
Sha1.prototype.init = function () {
this._a = 0x67452301
this._b = 0xefcdab89
this._c = 0x98badcfe
this._d = 0x10325476
this._e = 0xc3d2e1f0
return this
}
function rotl1 (num) {
return (num << 1) | (num >>> 31)
}
function rotl5 (num) {
return (num << 5) | (num >>> 27)
}
function rotl30 (num) {
return (num << 30) | (num >>> 2)
}
function ft (s, b, c, d) {
if (s === 0) return (b & c) | ((~b) & d)
if (s === 2) return (b & c) | (b & d) | (c & d)
return b ^ c ^ d
}
Sha1.prototype._update = function (M) {
var W = this._w
var a = this._a | 0
var b = this._b | 0
var c = this._c | 0
var d = this._d | 0
var e = this._e | 0
for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
for (var j = 0; j < 80; ++j) {
var s = ~~(j / 20)
var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
e = d
d = c
c = rotl30(b)
b = a
a = t
}
this._a = (a + this._a) | 0
this._b = (b + this._b) | 0
this._c = (c + this._c) | 0
this._d = (d + this._d) | 0
this._e = (e + this._e) | 0
}
Sha1.prototype._hash = function () {
var H = Buffer.allocUnsafe(20)
H.writeInt32BE(this._a | 0, 0)
H.writeInt32BE(this._b | 0, 4)
H.writeInt32BE(this._c | 0, 8)
H.writeInt32BE(this._d | 0, 12)
H.writeInt32BE(this._e | 0, 16)
return H
}
module.exports = Sha1
/***/ }),
/* 195 */
/***/ (function(module, exports, __webpack_require__) {
/**
* A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
* in FIPS 180-2
* Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
*
*/
var inherits = __webpack_require__(11)
var Sha256 = __webpack_require__(100)
var Hash = __webpack_require__(31)
var Buffer = __webpack_require__(21).Buffer
var W = new Array(64)
function Sha224 () {
this.init()
this._w = W // new Array(64)
Hash.call(this, 64, 56)
}
inherits(Sha224, Sha256)
Sha224.prototype.init = function () {
this._a = 0xc1059ed8
this._b = 0x367cd507
this._c = 0x3070dd17
this._d = 0xf70e5939
this._e = 0xffc00b31
this._f = 0x68581511
this._g = 0x64f98fa7
this._h = 0xbefa4fa4
return this
}
Sha224.prototype._hash = function () {
var H = Buffer.allocUnsafe(28)
H.writeInt32BE(this._a, 0)
H.writeInt32BE(this._b, 4)
H.writeInt32BE(this._c, 8)
H.writeInt32BE(this._d, 12)
H.writeInt32BE(this._e, 16)
H.writeInt32BE(this._f, 20)
H.writeInt32BE(this._g, 24)
return H
}
module.exports = Sha224
/***/ }),
/* 196 */
/***/ (function(module, exports, __webpack_require__) {
var inherits = __webpack_require__(11)
var SHA512 = __webpack_require__(101)
var Hash = __webpack_require__(31)
var Buffer = __webpack_require__(21).Buffer
var W = new Array(160)
function Sha384 () {
this.init()
this._w = W
Hash.call(this, 128, 112)
}
inherits(Sha384, SHA512)
Sha384.prototype.init = function () {
this._ah = 0xcbbb9d5d
this._bh = 0x629a292a
this._ch = 0x9159015a
this._dh = 0x152fecd8
this._eh = 0x67332667
this._fh = 0x8eb44a87
this._gh = 0xdb0c2e0d
this._hh = 0x47b5481d
this._al = 0xc1059ed8
this._bl = 0x367cd507
this._cl = 0x3070dd17
this._dl = 0xf70e5939
this._el = 0xffc00b31
this._fl = 0x68581511
this._gl = 0x64f98fa7
this._hl = 0xbefa4fa4
return this
}
Sha384.prototype._hash = function () {
var H = Buffer.allocUnsafe(48)
function writeInt64BE (h, l, offset) {
H.writeInt32BE(h, offset)
H.writeInt32BE(l, offset + 4)
}
writeInt64BE(this._ah, this._al, 0)
writeInt64BE(this._bh, this._bl, 8)
writeInt64BE(this._ch, this._cl, 16)
writeInt64BE(this._dh, this._dl, 24)
writeInt64BE(this._eh, this._el, 32)
writeInt64BE(this._fh, this._fl, 40)
return H
}
module.exports = Sha384
/***/ }),
/* 197 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 198 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 199 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jsXdr = __webpack_require__(22);
var XDR = _interopRequireWildcard(_jsXdr);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
var types = XDR.config(function (xdr) {
// === xdr source ============================================================
//
// typedef opaque Value<>;
//
// ===========================================================================
xdr.typedef("Value", xdr.varOpaque());
// === xdr source ============================================================
//
// struct SCPBallot
// {
// uint32 counter; // n
// Value value; // x
// };
//
// ===========================================================================
xdr.struct("ScpBallot", [["counter", xdr.lookup("Uint32")], ["value", xdr.lookup("Value")]]);
// === xdr source ============================================================
//
// enum SCPStatementType
// {
// SCP_ST_PREPARE = 0,
// SCP_ST_CONFIRM = 1,
// SCP_ST_EXTERNALIZE = 2,
// SCP_ST_NOMINATE = 3
// };
//
// ===========================================================================
xdr.enum("ScpStatementType", {
scpStPrepare: 0,
scpStConfirm: 1,
scpStExternalize: 2,
scpStNominate: 3
});
// === xdr source ============================================================
//
// struct SCPNomination
// {
// Hash quorumSetHash; // D
// Value votes<>; // X
// Value accepted<>; // Y
// };
//
// ===========================================================================
xdr.struct("ScpNomination", [["quorumSetHash", xdr.lookup("Hash")], ["votes", xdr.varArray(xdr.lookup("Value"), 2147483647)], ["accepted", xdr.varArray(xdr.lookup("Value"), 2147483647)]]);
// === xdr source ============================================================
//
// struct
// {
// Hash quorumSetHash; // D
// SCPBallot ballot; // b
// SCPBallot* prepared; // p
// SCPBallot* preparedPrime; // p'
// uint32 nC; // c.n
// uint32 nH; // h.n
// }
//
// ===========================================================================
xdr.struct("ScpStatementPrepare", [["quorumSetHash", xdr.lookup("Hash")], ["ballot", xdr.lookup("ScpBallot")], ["prepared", xdr.option(xdr.lookup("ScpBallot"))], ["preparedPrime", xdr.option(xdr.lookup("ScpBallot"))], ["nC", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")]]);
// === xdr source ============================================================
//
// struct
// {
// SCPBallot ballot; // b
// uint32 nPrepared; // p.n
// uint32 nCommit; // c.n
// uint32 nH; // h.n
// Hash quorumSetHash; // D
// }
//
// ===========================================================================
xdr.struct("ScpStatementConfirm", [["ballot", xdr.lookup("ScpBallot")], ["nPrepared", xdr.lookup("Uint32")], ["nCommit", xdr.lookup("Uint32")], ["nH", xdr.lookup("Uint32")], ["quorumSetHash", xdr.lookup("Hash")]]);
// === xdr source ============================================================
//
// struct
// {
// SCPBallot commit; // c
// uint32 nH; // h.n
// Hash commitQuorumSetHash; // D used before EXTERNALIZE
// }
//
// ===========================================================================
xdr.struct("ScpStatementExternalize", [["commit", xdr.lookup("ScpBallot")], ["nH", xdr.lookup("Uint32")], ["commitQuorumSetHash", xdr.lookup("Hash")]]);
// === xdr source ============================================================
//
// union switch (SCPStatementType type)
// {
// case SCP_ST_PREPARE:
// struct
// {
// Hash quorumSetHash; // D
// SCPBallot ballot; // b
// SCPBallot* prepared; // p
// SCPBallot* preparedPrime; // p'
// uint32 nC; // c.n
// uint32 nH; // h.n
// } prepare;
// case SCP_ST_CONFIRM:
// struct
// {
// SCPBallot ballot; // b
// uint32 nPrepared; // p.n
// uint32 nCommit; // c.n
// uint32 nH; // h.n
// Hash quorumSetHash; // D
// } confirm;
// case SCP_ST_EXTERNALIZE:
// struct
// {
// SCPBallot commit; // c
// uint32 nH; // h.n
// Hash commitQuorumSetHash; // D used before EXTERNALIZE
// } externalize;
// case SCP_ST_NOMINATE:
// SCPNomination nominate;
// }
//
// ===========================================================================
xdr.union("ScpStatementPledges", {
switchOn: xdr.lookup("ScpStatementType"),
switchName: "type",
switches: [["scpStPrepare", "prepare"], ["scpStConfirm", "confirm"], ["scpStExternalize", "externalize"], ["scpStNominate", "nominate"]],
arms: {
prepare: xdr.lookup("ScpStatementPrepare"),
confirm: xdr.lookup("ScpStatementConfirm"),
externalize: xdr.lookup("ScpStatementExternalize"),
nominate: xdr.lookup("ScpNomination")
}
});
// === xdr source ============================================================
//
// struct SCPStatement
// {
// NodeID nodeID; // v
// uint64 slotIndex; // i
//
// union switch (SCPStatementType type)
// {
// case SCP_ST_PREPARE:
// struct
// {
// Hash quorumSetHash; // D
// SCPBallot ballot; // b
// SCPBallot* prepared; // p
// SCPBallot* preparedPrime; // p'
// uint32 nC; // c.n
// uint32 nH; // h.n
// } prepare;
// case SCP_ST_CONFIRM:
// struct
// {
// SCPBallot ballot; // b
// uint32 nPrepared; // p.n
// uint32 nCommit; // c.n
// uint32 nH; // h.n
// Hash quorumSetHash; // D
// } confirm;
// case SCP_ST_EXTERNALIZE:
// struct
// {
// SCPBallot commit; // c
// uint32 nH; // h.n
// Hash commitQuorumSetHash; // D used before EXTERNALIZE
// } externalize;
// case SCP_ST_NOMINATE:
// SCPNomination nominate;
// }
// pledges;
// };
//
// ===========================================================================
xdr.struct("ScpStatement", [["nodeId", xdr.lookup("NodeId")], ["slotIndex", xdr.lookup("Uint64")], ["pledges", xdr.lookup("ScpStatementPledges")]]);
// === xdr source ============================================================
//
// struct SCPEnvelope
// {
// SCPStatement statement;
// Signature signature;
// };
//
// ===========================================================================
xdr.struct("ScpEnvelope", [["statement", xdr.lookup("ScpStatement")], ["signature", xdr.lookup("Signature")]]);
// === xdr source ============================================================
//
// struct SCPQuorumSet
// {
// uint32 threshold;
// NodeID validators<>;
// SCPQuorumSet innerSets<>;
// };
//
// ===========================================================================
xdr.struct("ScpQuorumSet", [["threshold", xdr.lookup("Uint32")], ["validators", xdr.varArray(xdr.lookup("NodeId"), 2147483647)], ["innerSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)]]);
// === xdr source ============================================================
//
// typedef PublicKey AccountID;
//
// ===========================================================================
xdr.typedef("AccountId", xdr.lookup("PublicKey"));
// === xdr source ============================================================
//
// typedef opaque Thresholds[4];
//
// ===========================================================================
xdr.typedef("Thresholds", xdr.opaque(4));
// === xdr source ============================================================
//
// typedef string string32<32>;
//
// ===========================================================================
xdr.typedef("String32", xdr.string(32));
// === xdr source ============================================================
//
// typedef string string64<64>;
//
// ===========================================================================
xdr.typedef("String64", xdr.string(64));
// === xdr source ============================================================
//
// typedef int64 SequenceNumber;
//
// ===========================================================================
xdr.typedef("SequenceNumber", xdr.lookup("Int64"));
// === xdr source ============================================================
//
// typedef uint64 TimePoint;
//
// ===========================================================================
xdr.typedef("TimePoint", xdr.lookup("Uint64"));
// === xdr source ============================================================
//
// typedef uint64 Duration;
//
// ===========================================================================
xdr.typedef("Duration", xdr.lookup("Uint64"));
// === xdr source ============================================================
//
// typedef opaque DataValue<64>;
//
// ===========================================================================
xdr.typedef("DataValue", xdr.varOpaque(64));
// === xdr source ============================================================
//
// typedef Hash PoolID;
//
// ===========================================================================
xdr.typedef("PoolId", xdr.lookup("Hash"));
// === xdr source ============================================================
//
// typedef opaque AssetCode4[4];
//
// ===========================================================================
xdr.typedef("AssetCode4", xdr.opaque(4));
// === xdr source ============================================================
//
// typedef opaque AssetCode12[12];
//
// ===========================================================================
xdr.typedef("AssetCode12", xdr.opaque(12));
// === xdr source ============================================================
//
// enum AssetType
// {
// ASSET_TYPE_NATIVE = 0,
// ASSET_TYPE_CREDIT_ALPHANUM4 = 1,
// ASSET_TYPE_CREDIT_ALPHANUM12 = 2,
// ASSET_TYPE_POOL_SHARE = 3
// };
//
// ===========================================================================
xdr.enum("AssetType", {
assetTypeNative: 0,
assetTypeCreditAlphanum4: 1,
assetTypeCreditAlphanum12: 2,
assetTypePoolShare: 3
});
// === xdr source ============================================================
//
// union AssetCode switch (AssetType type)
// {
// case ASSET_TYPE_CREDIT_ALPHANUM4:
// AssetCode4 assetCode4;
//
// case ASSET_TYPE_CREDIT_ALPHANUM12:
// AssetCode12 assetCode12;
//
// // add other asset types here in the future
// };
//
// ===========================================================================
xdr.union("AssetCode", {
switchOn: xdr.lookup("AssetType"),
switchName: "type",
switches: [["assetTypeCreditAlphanum4", "assetCode4"], ["assetTypeCreditAlphanum12", "assetCode12"]],
arms: {
assetCode4: xdr.lookup("AssetCode4"),
assetCode12: xdr.lookup("AssetCode12")
}
});
// === xdr source ============================================================
//
// struct AlphaNum4
// {
// AssetCode4 assetCode;
// AccountID issuer;
// };
//
// ===========================================================================
xdr.struct("AlphaNum4", [["assetCode", xdr.lookup("AssetCode4")], ["issuer", xdr.lookup("AccountId")]]);
// === xdr source ============================================================
//
// struct AlphaNum12
// {
// AssetCode12 assetCode;
// AccountID issuer;
// };
//
// ===========================================================================
xdr.struct("AlphaNum12", [["assetCode", xdr.lookup("AssetCode12")], ["issuer", xdr.lookup("AccountId")]]);
// === xdr source ============================================================
//
// union Asset switch (AssetType type)
// {
// case ASSET_TYPE_NATIVE: // Not credit
// void;
//
// case ASSET_TYPE_CREDIT_ALPHANUM4:
// AlphaNum4 alphaNum4;
//
// case ASSET_TYPE_CREDIT_ALPHANUM12:
// AlphaNum12 alphaNum12;
//
// // add other asset types here in the future
// };
//
// ===========================================================================
xdr.union("Asset", {
switchOn: xdr.lookup("AssetType"),
switchName: "type",
switches: [["assetTypeNative", xdr.void()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"]],
arms: {
alphaNum4: xdr.lookup("AlphaNum4"),
alphaNum12: xdr.lookup("AlphaNum12")
}
});
// === xdr source ============================================================
//
// struct Price
// {
// int32 n; // numerator
// int32 d; // denominator
// };
//
// ===========================================================================
xdr.struct("Price", [["n", xdr.lookup("Int32")], ["d", xdr.lookup("Int32")]]);
// === xdr source ============================================================
//
// struct Liabilities
// {
// int64 buying;
// int64 selling;
// };
//
// ===========================================================================
xdr.struct("Liabilities", [["buying", xdr.lookup("Int64")], ["selling", xdr.lookup("Int64")]]);
// === xdr source ============================================================
//
// enum ThresholdIndexes
// {
// THRESHOLD_MASTER_WEIGHT = 0,
// THRESHOLD_LOW = 1,
// THRESHOLD_MED = 2,
// THRESHOLD_HIGH = 3
// };
//
// ===========================================================================
xdr.enum("ThresholdIndices", {
thresholdMasterWeight: 0,
thresholdLow: 1,
thresholdMed: 2,
thresholdHigh: 3
});
// === xdr source ============================================================
//
// enum LedgerEntryType
// {
// ACCOUNT = 0,
// TRUSTLINE = 1,
// OFFER = 2,
// DATA = 3,
// CLAIMABLE_BALANCE = 4,
// LIQUIDITY_POOL = 5
// };
//
// ===========================================================================
xdr.enum("LedgerEntryType", {
account: 0,
trustline: 1,
offer: 2,
data: 3,
claimableBalance: 4,
liquidityPool: 5
});
// === xdr source ============================================================
//
// struct Signer
// {
// SignerKey key;
// uint32 weight; // really only need 1 byte
// };
//
// ===========================================================================
xdr.struct("Signer", [["key", xdr.lookup("SignerKey")], ["weight", xdr.lookup("Uint32")]]);
// === xdr source ============================================================
//
// enum AccountFlags
// { // masks for each flag
//
// // Flags set on issuer accounts
// // TrustLines are created with authorized set to "false" requiring
// // the issuer to set it for each TrustLine
// AUTH_REQUIRED_FLAG = 0x1,
// // If set, the authorized flag in TrustLines can be cleared
// // otherwise, authorization cannot be revoked
// AUTH_REVOCABLE_FLAG = 0x2,
// // Once set, causes all AUTH_* flags to be read-only
// AUTH_IMMUTABLE_FLAG = 0x4,
// // Trustlines are created with clawback enabled set to "true",
// // and claimable balances created from those trustlines are created
// // with clawback enabled set to "true"
// AUTH_CLAWBACK_ENABLED_FLAG = 0x8
// };
//
// ===========================================================================
xdr.enum("AccountFlags", {
authRequiredFlag: 1,
authRevocableFlag: 2,
authImmutableFlag: 4,
authClawbackEnabledFlag: 8
});
// === xdr source ============================================================
//
// const MASK_ACCOUNT_FLAGS = 0x7;
//
// ===========================================================================
xdr.const("MASK_ACCOUNT_FLAGS", 0x7);
// === xdr source ============================================================
//
// const MASK_ACCOUNT_FLAGS_V17 = 0xF;
//
// ===========================================================================
xdr.const("MASK_ACCOUNT_FLAGS_V17", 0xF);
// === xdr source ============================================================
//
// const MAX_SIGNERS = 20;
//
// ===========================================================================
xdr.const("MAX_SIGNERS", 20);
// === xdr source ============================================================
//
// typedef AccountID* SponsorshipDescriptor;
//
// ===========================================================================
xdr.typedef("SponsorshipDescriptor", xdr.option(xdr.lookup("AccountId")));
// === xdr source ============================================================
//
// struct AccountEntryExtensionV3
// {
// // We can use this to add more fields, or because it is first, to
// // change AccountEntryExtensionV3 into a union.
// ExtensionPoint ext;
//
// // Ledger number at which `seqNum` took on its present value.
// uint32 seqLedger;
//
// // Time at which `seqNum` took on its present value.
// TimePoint seqTime;
// };
//
// ===========================================================================
xdr.struct("AccountEntryExtensionV3", [["ext", xdr.lookup("ExtensionPoint")], ["seqLedger", xdr.lookup("Uint32")], ["seqTime", xdr.lookup("TimePoint")]]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 3:
// AccountEntryExtensionV3 v3;
// }
//
// ===========================================================================
xdr.union("AccountEntryExtensionV2Ext", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()], [3, "v3"]],
arms: {
v3: xdr.lookup("AccountEntryExtensionV3")
}
});
// === xdr source ============================================================
//
// struct AccountEntryExtensionV2
// {
// uint32 numSponsored;
// uint32 numSponsoring;
// SponsorshipDescriptor signerSponsoringIDs<MAX_SIGNERS>;
//
// union switch (int v)
// {
// case 0:
// void;
// case 3:
// AccountEntryExtensionV3 v3;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("AccountEntryExtensionV2", [["numSponsored", xdr.lookup("Uint32")], ["numSponsoring", xdr.lookup("Uint32")], ["signerSponsoringIDs", xdr.varArray(xdr.lookup("SponsorshipDescriptor"), xdr.lookup("MAX_SIGNERS"))], ["ext", xdr.lookup("AccountEntryExtensionV2Ext")]]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 2:
// AccountEntryExtensionV2 v2;
// }
//
// ===========================================================================
xdr.union("AccountEntryExtensionV1Ext", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()], [2, "v2"]],
arms: {
v2: xdr.lookup("AccountEntryExtensionV2")
}
});
// === xdr source ============================================================
//
// struct AccountEntryExtensionV1
// {
// Liabilities liabilities;
//
// union switch (int v)
// {
// case 0:
// void;
// case 2:
// AccountEntryExtensionV2 v2;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("AccountEntryExtensionV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("AccountEntryExtensionV1Ext")]]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// AccountEntryExtensionV1 v1;
// }
//
// ===========================================================================
xdr.union("AccountEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()], [1, "v1"]],
arms: {
v1: xdr.lookup("AccountEntryExtensionV1")
}
});
// === xdr source ============================================================
//
// struct AccountEntry
// {
// AccountID accountID; // master public key for this account
// int64 balance; // in stroops
// SequenceNumber seqNum; // last sequence number used for this account
// uint32 numSubEntries; // number of sub-entries this account has
// // drives the reserve
// AccountID* inflationDest; // Account to vote for during inflation
// uint32 flags; // see AccountFlags
//
// string32 homeDomain; // can be used for reverse federation and memo lookup
//
// // fields used for signatures
// // thresholds stores unsigned bytes: [weight of master|low|medium|high]
// Thresholds thresholds;
//
// Signer signers<MAX_SIGNERS>; // possible signers for this account
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// AccountEntryExtensionV1 v1;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("AccountEntry", [["accountId", xdr.lookup("AccountId")], ["balance", xdr.lookup("Int64")], ["seqNum", xdr.lookup("SequenceNumber")], ["numSubEntries", xdr.lookup("Uint32")], ["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["flags", xdr.lookup("Uint32")], ["homeDomain", xdr.lookup("String32")], ["thresholds", xdr.lookup("Thresholds")], ["signers", xdr.varArray(xdr.lookup("Signer"), xdr.lookup("MAX_SIGNERS"))], ["ext", xdr.lookup("AccountEntryExt")]]);
// === xdr source ============================================================
//
// enum TrustLineFlags
// {
// // issuer has authorized account to perform transactions with its credit
// AUTHORIZED_FLAG = 1,
// // issuer has authorized account to maintain and reduce liabilities for its
// // credit
// AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG = 2,
// // issuer has specified that it may clawback its credit, and that claimable
// // balances created with its credit may also be clawed back
// TRUSTLINE_CLAWBACK_ENABLED_FLAG = 4
// };
//
// ===========================================================================
xdr.enum("TrustLineFlags", {
authorizedFlag: 1,
authorizedToMaintainLiabilitiesFlag: 2,
trustlineClawbackEnabledFlag: 4
});
// === xdr source ============================================================
//
// const MASK_TRUSTLINE_FLAGS = 1;
//
// ===========================================================================
xdr.const("MASK_TRUSTLINE_FLAGS", 1);
// === xdr source ============================================================
//
// const MASK_TRUSTLINE_FLAGS_V13 = 3;
//
// ===========================================================================
xdr.const("MASK_TRUSTLINE_FLAGS_V13", 3);
// === xdr source ============================================================
//
// const MASK_TRUSTLINE_FLAGS_V17 = 7;
//
// ===========================================================================
xdr.const("MASK_TRUSTLINE_FLAGS_V17", 7);
// === xdr source ============================================================
//
// enum LiquidityPoolType
// {
// LIQUIDITY_POOL_CONSTANT_PRODUCT = 0
// };
//
// ===========================================================================
xdr.enum("LiquidityPoolType", {
liquidityPoolConstantProduct: 0
});
// === xdr source ============================================================
//
// union TrustLineAsset switch (AssetType type)
// {
// case ASSET_TYPE_NATIVE: // Not credit
// void;
//
// case ASSET_TYPE_CREDIT_ALPHANUM4:
// AlphaNum4 alphaNum4;
//
// case ASSET_TYPE_CREDIT_ALPHANUM12:
// AlphaNum12 alphaNum12;
//
// case ASSET_TYPE_POOL_SHARE:
// PoolID liquidityPoolID;
//
// // add other asset types here in the future
// };
//
// ===========================================================================
xdr.union("TrustLineAsset", {
switchOn: xdr.lookup("AssetType"),
switchName: "type",
switches: [["assetTypeNative", xdr.void()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"], ["assetTypePoolShare", "liquidityPoolId"]],
arms: {
alphaNum4: xdr.lookup("AlphaNum4"),
alphaNum12: xdr.lookup("AlphaNum12"),
liquidityPoolId: xdr.lookup("PoolId")
}
});
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("TrustLineEntryExtensionV2Ext", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// struct TrustLineEntryExtensionV2
// {
// int32 liquidityPoolUseCount;
//
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("TrustLineEntryExtensionV2", [["liquidityPoolUseCount", xdr.lookup("Int32")], ["ext", xdr.lookup("TrustLineEntryExtensionV2Ext")]]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 2:
// TrustLineEntryExtensionV2 v2;
// }
//
// ===========================================================================
xdr.union("TrustLineEntryV1Ext", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()], [2, "v2"]],
arms: {
v2: xdr.lookup("TrustLineEntryExtensionV2")
}
});
// === xdr source ============================================================
//
// struct
// {
// Liabilities liabilities;
//
// union switch (int v)
// {
// case 0:
// void;
// case 2:
// TrustLineEntryExtensionV2 v2;
// }
// ext;
// }
//
// ===========================================================================
xdr.struct("TrustLineEntryV1", [["liabilities", xdr.lookup("Liabilities")], ["ext", xdr.lookup("TrustLineEntryV1Ext")]]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// struct
// {
// Liabilities liabilities;
//
// union switch (int v)
// {
// case 0:
// void;
// case 2:
// TrustLineEntryExtensionV2 v2;
// }
// ext;
// } v1;
// }
//
// ===========================================================================
xdr.union("TrustLineEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()], [1, "v1"]],
arms: {
v1: xdr.lookup("TrustLineEntryV1")
}
});
// === xdr source ============================================================
//
// struct TrustLineEntry
// {
// AccountID accountID; // account this trustline belongs to
// TrustLineAsset asset; // type of asset (with issuer)
// int64 balance; // how much of this asset the user has.
// // Asset defines the unit for this;
//
// int64 limit; // balance cannot be above this
// uint32 flags; // see TrustLineFlags
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// struct
// {
// Liabilities liabilities;
//
// union switch (int v)
// {
// case 0:
// void;
// case 2:
// TrustLineEntryExtensionV2 v2;
// }
// ext;
// } v1;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("TrustLineEntry", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("TrustLineAsset")], ["balance", xdr.lookup("Int64")], ["limit", xdr.lookup("Int64")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("TrustLineEntryExt")]]);
// === xdr source ============================================================
//
// enum OfferEntryFlags
// {
// // an offer with this flag will not act on and take a reverse offer of equal
// // price
// PASSIVE_FLAG = 1
// };
//
// ===========================================================================
xdr.enum("OfferEntryFlags", {
passiveFlag: 1
});
// === xdr source ============================================================
//
// const MASK_OFFERENTRY_FLAGS = 1;
//
// ===========================================================================
xdr.const("MASK_OFFERENTRY_FLAGS", 1);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("OfferEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// struct OfferEntry
// {
// AccountID sellerID;
// int64 offerID;
// Asset selling; // A
// Asset buying; // B
// int64 amount; // amount of A
//
// /* price for this offer:
// price of A in terms of B
// price=AmountB/AmountA=priceNumerator/priceDenominator
// price is after fees
// */
// Price price;
// uint32 flags; // see OfferEntryFlags
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("OfferEntry", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")], ["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("OfferEntryExt")]]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("DataEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// struct DataEntry
// {
// AccountID accountID; // account this data belongs to
// string64 dataName;
// DataValue dataValue;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("DataEntry", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")], ["dataValue", xdr.lookup("DataValue")], ["ext", xdr.lookup("DataEntryExt")]]);
// === xdr source ============================================================
//
// enum ClaimPredicateType
// {
// CLAIM_PREDICATE_UNCONDITIONAL = 0,
// CLAIM_PREDICATE_AND = 1,
// CLAIM_PREDICATE_OR = 2,
// CLAIM_PREDICATE_NOT = 3,
// CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME = 4,
// CLAIM_PREDICATE_BEFORE_RELATIVE_TIME = 5
// };
//
// ===========================================================================
xdr.enum("ClaimPredicateType", {
claimPredicateUnconditional: 0,
claimPredicateAnd: 1,
claimPredicateOr: 2,
claimPredicateNot: 3,
claimPredicateBeforeAbsoluteTime: 4,
claimPredicateBeforeRelativeTime: 5
});
// === xdr source ============================================================
//
// union ClaimPredicate switch (ClaimPredicateType type)
// {
// case CLAIM_PREDICATE_UNCONDITIONAL:
// void;
// case CLAIM_PREDICATE_AND:
// ClaimPredicate andPredicates<2>;
// case CLAIM_PREDICATE_OR:
// ClaimPredicate orPredicates<2>;
// case CLAIM_PREDICATE_NOT:
// ClaimPredicate* notPredicate;
// case CLAIM_PREDICATE_BEFORE_ABSOLUTE_TIME:
// int64 absBefore; // Predicate will be true if closeTime < absBefore
// case CLAIM_PREDICATE_BEFORE_RELATIVE_TIME:
// int64 relBefore; // Seconds since closeTime of the ledger in which the
// // ClaimableBalanceEntry was created
// };
//
// ===========================================================================
xdr.union("ClaimPredicate", {
switchOn: xdr.lookup("ClaimPredicateType"),
switchName: "type",
switches: [["claimPredicateUnconditional", xdr.void()], ["claimPredicateAnd", "andPredicates"], ["claimPredicateOr", "orPredicates"], ["claimPredicateNot", "notPredicate"], ["claimPredicateBeforeAbsoluteTime", "absBefore"], ["claimPredicateBeforeRelativeTime", "relBefore"]],
arms: {
andPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2),
orPredicates: xdr.varArray(xdr.lookup("ClaimPredicate"), 2),
notPredicate: xdr.option(xdr.lookup("ClaimPredicate")),
absBefore: xdr.lookup("Int64"),
relBefore: xdr.lookup("Int64")
}
});
// === xdr source ============================================================
//
// enum ClaimantType
// {
// CLAIMANT_TYPE_V0 = 0
// };
//
// ===========================================================================
xdr.enum("ClaimantType", {
claimantTypeV0: 0
});
// === xdr source ============================================================
//
// struct
// {
// AccountID destination; // The account that can use this condition
// ClaimPredicate predicate; // Claimable if predicate is true
// }
//
// ===========================================================================
xdr.struct("ClaimantV0", [["destination", xdr.lookup("AccountId")], ["predicate", xdr.lookup("ClaimPredicate")]]);
// === xdr source ============================================================
//
// union Claimant switch (ClaimantType type)
// {
// case CLAIMANT_TYPE_V0:
// struct
// {
// AccountID destination; // The account that can use this condition
// ClaimPredicate predicate; // Claimable if predicate is true
// } v0;
// };
//
// ===========================================================================
xdr.union("Claimant", {
switchOn: xdr.lookup("ClaimantType"),
switchName: "type",
switches: [["claimantTypeV0", "v0"]],
arms: {
v0: xdr.lookup("ClaimantV0")
}
});
// === xdr source ============================================================
//
// enum ClaimableBalanceIDType
// {
// CLAIMABLE_BALANCE_ID_TYPE_V0 = 0
// };
//
// ===========================================================================
xdr.enum("ClaimableBalanceIdType", {
claimableBalanceIdTypeV0: 0
});
// === xdr source ============================================================
//
// union ClaimableBalanceID switch (ClaimableBalanceIDType type)
// {
// case CLAIMABLE_BALANCE_ID_TYPE_V0:
// Hash v0;
// };
//
// ===========================================================================
xdr.union("ClaimableBalanceId", {
switchOn: xdr.lookup("ClaimableBalanceIdType"),
switchName: "type",
switches: [["claimableBalanceIdTypeV0", "v0"]],
arms: {
v0: xdr.lookup("Hash")
}
});
// === xdr source ============================================================
//
// enum ClaimableBalanceFlags
// {
// // If set, the issuer account of the asset held by the claimable balance may
// // clawback the claimable balance
// CLAIMABLE_BALANCE_CLAWBACK_ENABLED_FLAG = 0x1
// };
//
// ===========================================================================
xdr.enum("ClaimableBalanceFlags", {
claimableBalanceClawbackEnabledFlag: 1
});
// === xdr source ============================================================
//
// const MASK_CLAIMABLE_BALANCE_FLAGS = 0x1;
//
// ===========================================================================
xdr.const("MASK_CLAIMABLE_BALANCE_FLAGS", 0x1);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("ClaimableBalanceEntryExtensionV1Ext", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// struct ClaimableBalanceEntryExtensionV1
// {
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
//
// uint32 flags; // see ClaimableBalanceFlags
// };
//
// ===========================================================================
xdr.struct("ClaimableBalanceEntryExtensionV1", [["ext", xdr.lookup("ClaimableBalanceEntryExtensionV1Ext")], ["flags", xdr.lookup("Uint32")]]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// ClaimableBalanceEntryExtensionV1 v1;
// }
//
// ===========================================================================
xdr.union("ClaimableBalanceEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()], [1, "v1"]],
arms: {
v1: xdr.lookup("ClaimableBalanceEntryExtensionV1")
}
});
// === xdr source ============================================================
//
// struct ClaimableBalanceEntry
// {
// // Unique identifier for this ClaimableBalanceEntry
// ClaimableBalanceID balanceID;
//
// // List of claimants with associated predicate
// Claimant claimants<10>;
//
// // Any asset including native
// Asset asset;
//
// // Amount of asset
// int64 amount;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// ClaimableBalanceEntryExtensionV1 v1;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("ClaimableBalanceEntry", [["balanceId", xdr.lookup("ClaimableBalanceId")], ["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["ext", xdr.lookup("ClaimableBalanceEntryExt")]]);
// === xdr source ============================================================
//
// struct LiquidityPoolConstantProductParameters
// {
// Asset assetA; // assetA < assetB
// Asset assetB;
// int32 fee; // Fee is in basis points, so the actual rate is (fee/100)%
// };
//
// ===========================================================================
xdr.struct("LiquidityPoolConstantProductParameters", [["assetA", xdr.lookup("Asset")], ["assetB", xdr.lookup("Asset")], ["fee", xdr.lookup("Int32")]]);
// === xdr source ============================================================
//
// struct
// {
// LiquidityPoolConstantProductParameters params;
//
// int64 reserveA; // amount of A in the pool
// int64 reserveB; // amount of B in the pool
// int64 totalPoolShares; // total number of pool shares issued
// int64 poolSharesTrustLineCount; // number of trust lines for the
// // associated pool shares
// }
//
// ===========================================================================
xdr.struct("LiquidityPoolEntryConstantProduct", [["params", xdr.lookup("LiquidityPoolConstantProductParameters")], ["reserveA", xdr.lookup("Int64")], ["reserveB", xdr.lookup("Int64")], ["totalPoolShares", xdr.lookup("Int64")], ["poolSharesTrustLineCount", xdr.lookup("Int64")]]);
// === xdr source ============================================================
//
// union switch (LiquidityPoolType type)
// {
// case LIQUIDITY_POOL_CONSTANT_PRODUCT:
// struct
// {
// LiquidityPoolConstantProductParameters params;
//
// int64 reserveA; // amount of A in the pool
// int64 reserveB; // amount of B in the pool
// int64 totalPoolShares; // total number of pool shares issued
// int64 poolSharesTrustLineCount; // number of trust lines for the
// // associated pool shares
// } constantProduct;
// }
//
// ===========================================================================
xdr.union("LiquidityPoolEntryBody", {
switchOn: xdr.lookup("LiquidityPoolType"),
switchName: "type",
switches: [["liquidityPoolConstantProduct", "constantProduct"]],
arms: {
constantProduct: xdr.lookup("LiquidityPoolEntryConstantProduct")
}
});
// === xdr source ============================================================
//
// struct LiquidityPoolEntry
// {
// PoolID liquidityPoolID;
//
// union switch (LiquidityPoolType type)
// {
// case LIQUIDITY_POOL_CONSTANT_PRODUCT:
// struct
// {
// LiquidityPoolConstantProductParameters params;
//
// int64 reserveA; // amount of A in the pool
// int64 reserveB; // amount of B in the pool
// int64 totalPoolShares; // total number of pool shares issued
// int64 poolSharesTrustLineCount; // number of trust lines for the
// // associated pool shares
// } constantProduct;
// }
// body;
// };
//
// ===========================================================================
xdr.struct("LiquidityPoolEntry", [["liquidityPoolId", xdr.lookup("PoolId")], ["body", xdr.lookup("LiquidityPoolEntryBody")]]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("LedgerEntryExtensionV1Ext", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// struct LedgerEntryExtensionV1
// {
// SponsorshipDescriptor sponsoringID;
//
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("LedgerEntryExtensionV1", [["sponsoringId", xdr.lookup("SponsorshipDescriptor")], ["ext", xdr.lookup("LedgerEntryExtensionV1Ext")]]);
// === xdr source ============================================================
//
// union switch (LedgerEntryType type)
// {
// case ACCOUNT:
// AccountEntry account;
// case TRUSTLINE:
// TrustLineEntry trustLine;
// case OFFER:
// OfferEntry offer;
// case DATA:
// DataEntry data;
// case CLAIMABLE_BALANCE:
// ClaimableBalanceEntry claimableBalance;
// case LIQUIDITY_POOL:
// LiquidityPoolEntry liquidityPool;
// }
//
// ===========================================================================
xdr.union("LedgerEntryData", {
switchOn: xdr.lookup("LedgerEntryType"),
switchName: "type",
switches: [["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["data", "data"], ["claimableBalance", "claimableBalance"], ["liquidityPool", "liquidityPool"]],
arms: {
account: xdr.lookup("AccountEntry"),
trustLine: xdr.lookup("TrustLineEntry"),
offer: xdr.lookup("OfferEntry"),
data: xdr.lookup("DataEntry"),
claimableBalance: xdr.lookup("ClaimableBalanceEntry"),
liquidityPool: xdr.lookup("LiquidityPoolEntry")
}
});
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// LedgerEntryExtensionV1 v1;
// }
//
// ===========================================================================
xdr.union("LedgerEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()], [1, "v1"]],
arms: {
v1: xdr.lookup("LedgerEntryExtensionV1")
}
});
// === xdr source ============================================================
//
// struct LedgerEntry
// {
// uint32 lastModifiedLedgerSeq; // ledger the LedgerEntry was last changed
//
// union switch (LedgerEntryType type)
// {
// case ACCOUNT:
// AccountEntry account;
// case TRUSTLINE:
// TrustLineEntry trustLine;
// case OFFER:
// OfferEntry offer;
// case DATA:
// DataEntry data;
// case CLAIMABLE_BALANCE:
// ClaimableBalanceEntry claimableBalance;
// case LIQUIDITY_POOL:
// LiquidityPoolEntry liquidityPool;
// }
// data;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// LedgerEntryExtensionV1 v1;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("LedgerEntry", [["lastModifiedLedgerSeq", xdr.lookup("Uint32")], ["data", xdr.lookup("LedgerEntryData")], ["ext", xdr.lookup("LedgerEntryExt")]]);
// === xdr source ============================================================
//
// struct
// {
// AccountID accountID;
// }
//
// ===========================================================================
xdr.struct("LedgerKeyAccount", [["accountId", xdr.lookup("AccountId")]]);
// === xdr source ============================================================
//
// struct
// {
// AccountID accountID;
// TrustLineAsset asset;
// }
//
// ===========================================================================
xdr.struct("LedgerKeyTrustLine", [["accountId", xdr.lookup("AccountId")], ["asset", xdr.lookup("TrustLineAsset")]]);
// === xdr source ============================================================
//
// struct
// {
// AccountID sellerID;
// int64 offerID;
// }
//
// ===========================================================================
xdr.struct("LedgerKeyOffer", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")]]);
// === xdr source ============================================================
//
// struct
// {
// AccountID accountID;
// string64 dataName;
// }
//
// ===========================================================================
xdr.struct("LedgerKeyData", [["accountId", xdr.lookup("AccountId")], ["dataName", xdr.lookup("String64")]]);
// === xdr source ============================================================
//
// struct
// {
// ClaimableBalanceID balanceID;
// }
//
// ===========================================================================
xdr.struct("LedgerKeyClaimableBalance", [["balanceId", xdr.lookup("ClaimableBalanceId")]]);
// === xdr source ============================================================
//
// struct
// {
// PoolID liquidityPoolID;
// }
//
// ===========================================================================
xdr.struct("LedgerKeyLiquidityPool", [["liquidityPoolId", xdr.lookup("PoolId")]]);
// === xdr source ============================================================
//
// union LedgerKey switch (LedgerEntryType type)
// {
// case ACCOUNT:
// struct
// {
// AccountID accountID;
// } account;
//
// case TRUSTLINE:
// struct
// {
// AccountID accountID;
// TrustLineAsset asset;
// } trustLine;
//
// case OFFER:
// struct
// {
// AccountID sellerID;
// int64 offerID;
// } offer;
//
// case DATA:
// struct
// {
// AccountID accountID;
// string64 dataName;
// } data;
//
// case CLAIMABLE_BALANCE:
// struct
// {
// ClaimableBalanceID balanceID;
// } claimableBalance;
//
// case LIQUIDITY_POOL:
// struct
// {
// PoolID liquidityPoolID;
// } liquidityPool;
// };
//
// ===========================================================================
xdr.union("LedgerKey", {
switchOn: xdr.lookup("LedgerEntryType"),
switchName: "type",
switches: [["account", "account"], ["trustline", "trustLine"], ["offer", "offer"], ["data", "data"], ["claimableBalance", "claimableBalance"], ["liquidityPool", "liquidityPool"]],
arms: {
account: xdr.lookup("LedgerKeyAccount"),
trustLine: xdr.lookup("LedgerKeyTrustLine"),
offer: xdr.lookup("LedgerKeyOffer"),
data: xdr.lookup("LedgerKeyData"),
claimableBalance: xdr.lookup("LedgerKeyClaimableBalance"),
liquidityPool: xdr.lookup("LedgerKeyLiquidityPool")
}
});
// === xdr source ============================================================
//
// enum EnvelopeType
// {
// ENVELOPE_TYPE_TX_V0 = 0,
// ENVELOPE_TYPE_SCP = 1,
// ENVELOPE_TYPE_TX = 2,
// ENVELOPE_TYPE_AUTH = 3,
// ENVELOPE_TYPE_SCPVALUE = 4,
// ENVELOPE_TYPE_TX_FEE_BUMP = 5,
// ENVELOPE_TYPE_OP_ID = 6,
// ENVELOPE_TYPE_POOL_REVOKE_OP_ID = 7
// };
//
// ===========================================================================
xdr.enum("EnvelopeType", {
envelopeTypeTxV0: 0,
envelopeTypeScp: 1,
envelopeTypeTx: 2,
envelopeTypeAuth: 3,
envelopeTypeScpvalue: 4,
envelopeTypeTxFeeBump: 5,
envelopeTypeOpId: 6,
envelopeTypePoolRevokeOpId: 7
});
// === xdr source ============================================================
//
// typedef opaque UpgradeType<128>;
//
// ===========================================================================
xdr.typedef("UpgradeType", xdr.varOpaque(128));
// === xdr source ============================================================
//
// enum StellarValueType
// {
// STELLAR_VALUE_BASIC = 0,
// STELLAR_VALUE_SIGNED = 1
// };
//
// ===========================================================================
xdr.enum("StellarValueType", {
stellarValueBasic: 0,
stellarValueSigned: 1
});
// === xdr source ============================================================
//
// struct LedgerCloseValueSignature
// {
// NodeID nodeID; // which node introduced the value
// Signature signature; // nodeID's signature
// };
//
// ===========================================================================
xdr.struct("LedgerCloseValueSignature", [["nodeId", xdr.lookup("NodeId")], ["signature", xdr.lookup("Signature")]]);
// === xdr source ============================================================
//
// union switch (StellarValueType v)
// {
// case STELLAR_VALUE_BASIC:
// void;
// case STELLAR_VALUE_SIGNED:
// LedgerCloseValueSignature lcValueSignature;
// }
//
// ===========================================================================
xdr.union("StellarValueExt", {
switchOn: xdr.lookup("StellarValueType"),
switchName: "v",
switches: [["stellarValueBasic", xdr.void()], ["stellarValueSigned", "lcValueSignature"]],
arms: {
lcValueSignature: xdr.lookup("LedgerCloseValueSignature")
}
});
// === xdr source ============================================================
//
// struct StellarValue
// {
// Hash txSetHash; // transaction set to apply to previous ledger
// TimePoint closeTime; // network close time
//
// // upgrades to apply to the previous ledger (usually empty)
// // this is a vector of encoded 'LedgerUpgrade' so that nodes can drop
// // unknown steps during consensus if needed.
// // see notes below on 'LedgerUpgrade' for more detail
// // max size is dictated by number of upgrade types (+ room for future)
// UpgradeType upgrades<6>;
//
// // reserved for future use
// union switch (StellarValueType v)
// {
// case STELLAR_VALUE_BASIC:
// void;
// case STELLAR_VALUE_SIGNED:
// LedgerCloseValueSignature lcValueSignature;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("StellarValue", [["txSetHash", xdr.lookup("Hash")], ["closeTime", xdr.lookup("TimePoint")], ["upgrades", xdr.varArray(xdr.lookup("UpgradeType"), 6)], ["ext", xdr.lookup("StellarValueExt")]]);
// === xdr source ============================================================
//
// const MASK_LEDGER_HEADER_FLAGS = 0x7;
//
// ===========================================================================
xdr.const("MASK_LEDGER_HEADER_FLAGS", 0x7);
// === xdr source ============================================================
//
// enum LedgerHeaderFlags
// {
// DISABLE_LIQUIDITY_POOL_TRADING_FLAG = 0x1,
// DISABLE_LIQUIDITY_POOL_DEPOSIT_FLAG = 0x2,
// DISABLE_LIQUIDITY_POOL_WITHDRAWAL_FLAG = 0x4
// };
//
// ===========================================================================
xdr.enum("LedgerHeaderFlags", {
disableLiquidityPoolTradingFlag: 1,
disableLiquidityPoolDepositFlag: 2,
disableLiquidityPoolWithdrawalFlag: 4
});
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("LedgerHeaderExtensionV1Ext", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// struct LedgerHeaderExtensionV1
// {
// uint32 flags; // LedgerHeaderFlags
//
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("LedgerHeaderExtensionV1", [["flags", xdr.lookup("Uint32")], ["ext", xdr.lookup("LedgerHeaderExtensionV1Ext")]]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// LedgerHeaderExtensionV1 v1;
// }
//
// ===========================================================================
xdr.union("LedgerHeaderExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()], [1, "v1"]],
arms: {
v1: xdr.lookup("LedgerHeaderExtensionV1")
}
});
// === xdr source ============================================================
//
// struct LedgerHeader
// {
// uint32 ledgerVersion; // the protocol version of the ledger
// Hash previousLedgerHash; // hash of the previous ledger header
// StellarValue scpValue; // what consensus agreed to
// Hash txSetResultHash; // the TransactionResultSet that led to this ledger
// Hash bucketListHash; // hash of the ledger state
//
// uint32 ledgerSeq; // sequence number of this ledger
//
// int64 totalCoins; // total number of stroops in existence.
// // 10,000,000 stroops in 1 XLM
//
// int64 feePool; // fees burned since last inflation run
// uint32 inflationSeq; // inflation sequence number
//
// uint64 idPool; // last used global ID, used for generating objects
//
// uint32 baseFee; // base fee per operation in stroops
// uint32 baseReserve; // account base reserve in stroops
//
// uint32 maxTxSetSize; // maximum size a transaction set can be
//
// Hash skipList[4]; // hashes of ledgers in the past. allows you to jump back
// // in time without walking the chain back ledger by ledger
// // each slot contains the oldest ledger that is mod of
// // either 50 5000 50000 or 500000 depending on index
// // skipList[0] mod(50), skipList[1] mod(5000), etc
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// LedgerHeaderExtensionV1 v1;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("LedgerHeader", [["ledgerVersion", xdr.lookup("Uint32")], ["previousLedgerHash", xdr.lookup("Hash")], ["scpValue", xdr.lookup("StellarValue")], ["txSetResultHash", xdr.lookup("Hash")], ["bucketListHash", xdr.lookup("Hash")], ["ledgerSeq", xdr.lookup("Uint32")], ["totalCoins", xdr.lookup("Int64")], ["feePool", xdr.lookup("Int64")], ["inflationSeq", xdr.lookup("Uint32")], ["idPool", xdr.lookup("Uint64")], ["baseFee", xdr.lookup("Uint32")], ["baseReserve", xdr.lookup("Uint32")], ["maxTxSetSize", xdr.lookup("Uint32")], ["skipList", xdr.array(xdr.lookup("Hash"), 4)], ["ext", xdr.lookup("LedgerHeaderExt")]]);
// === xdr source ============================================================
//
// enum LedgerUpgradeType
// {
// LEDGER_UPGRADE_VERSION = 1,
// LEDGER_UPGRADE_BASE_FEE = 2,
// LEDGER_UPGRADE_MAX_TX_SET_SIZE = 3,
// LEDGER_UPGRADE_BASE_RESERVE = 4,
// LEDGER_UPGRADE_FLAGS = 5
// };
//
// ===========================================================================
xdr.enum("LedgerUpgradeType", {
ledgerUpgradeVersion: 1,
ledgerUpgradeBaseFee: 2,
ledgerUpgradeMaxTxSetSize: 3,
ledgerUpgradeBaseReserve: 4,
ledgerUpgradeFlags: 5
});
// === xdr source ============================================================
//
// union LedgerUpgrade switch (LedgerUpgradeType type)
// {
// case LEDGER_UPGRADE_VERSION:
// uint32 newLedgerVersion; // update ledgerVersion
// case LEDGER_UPGRADE_BASE_FEE:
// uint32 newBaseFee; // update baseFee
// case LEDGER_UPGRADE_MAX_TX_SET_SIZE:
// uint32 newMaxTxSetSize; // update maxTxSetSize
// case LEDGER_UPGRADE_BASE_RESERVE:
// uint32 newBaseReserve; // update baseReserve
// case LEDGER_UPGRADE_FLAGS:
// uint32 newFlags; // update flags
// };
//
// ===========================================================================
xdr.union("LedgerUpgrade", {
switchOn: xdr.lookup("LedgerUpgradeType"),
switchName: "type",
switches: [["ledgerUpgradeVersion", "newLedgerVersion"], ["ledgerUpgradeBaseFee", "newBaseFee"], ["ledgerUpgradeMaxTxSetSize", "newMaxTxSetSize"], ["ledgerUpgradeBaseReserve", "newBaseReserve"], ["ledgerUpgradeFlags", "newFlags"]],
arms: {
newLedgerVersion: xdr.lookup("Uint32"),
newBaseFee: xdr.lookup("Uint32"),
newMaxTxSetSize: xdr.lookup("Uint32"),
newBaseReserve: xdr.lookup("Uint32"),
newFlags: xdr.lookup("Uint32")
}
});
// === xdr source ============================================================
//
// enum BucketEntryType
// {
// METAENTRY =
// -1, // At-and-after protocol 11: bucket metadata, should come first.
// LIVEENTRY = 0, // Before protocol 11: created-or-updated;
// // At-and-after protocol 11: only updated.
// DEADENTRY = 1,
// INITENTRY = 2 // At-and-after protocol 11: only created.
// };
//
// ===========================================================================
xdr.enum("BucketEntryType", {
metaentry: -1,
liveentry: 0,
deadentry: 1,
initentry: 2
});
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("BucketMetadataExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// struct BucketMetadata
// {
// // Indicates the protocol version used to create / merge this bucket.
// uint32 ledgerVersion;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("BucketMetadata", [["ledgerVersion", xdr.lookup("Uint32")], ["ext", xdr.lookup("BucketMetadataExt")]]);
// === xdr source ============================================================
//
// union BucketEntry switch (BucketEntryType type)
// {
// case LIVEENTRY:
// case INITENTRY:
// LedgerEntry liveEntry;
//
// case DEADENTRY:
// LedgerKey deadEntry;
// case METAENTRY:
// BucketMetadata metaEntry;
// };
//
// ===========================================================================
xdr.union("BucketEntry", {
switchOn: xdr.lookup("BucketEntryType"),
switchName: "type",
switches: [["liveentry", "liveEntry"], ["initentry", "liveEntry"], ["deadentry", "deadEntry"], ["metaentry", "metaEntry"]],
arms: {
liveEntry: xdr.lookup("LedgerEntry"),
deadEntry: xdr.lookup("LedgerKey"),
metaEntry: xdr.lookup("BucketMetadata")
}
});
// === xdr source ============================================================
//
// enum TxSetComponentType
// {
// // txs with effective fee <= bid derived from a base fee (if any).
// // If base fee is not specified, no discount is applied.
// TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE = 0
// };
//
// ===========================================================================
xdr.enum("TxSetComponentType", {
txsetCompTxsMaybeDiscountedFee: 0
});
// === xdr source ============================================================
//
// struct
// {
// int64* baseFee;
// TransactionEnvelope txs<>;
// }
//
// ===========================================================================
xdr.struct("TxSetComponentTxsMaybeDiscountedFee", [["baseFee", xdr.option(xdr.lookup("Int64"))], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]);
// === xdr source ============================================================
//
// union TxSetComponent switch (TxSetComponentType type)
// {
// case TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE:
// struct
// {
// int64* baseFee;
// TransactionEnvelope txs<>;
// } txsMaybeDiscountedFee;
// };
//
// ===========================================================================
xdr.union("TxSetComponent", {
switchOn: xdr.lookup("TxSetComponentType"),
switchName: "type",
switches: [["txsetCompTxsMaybeDiscountedFee", "txsMaybeDiscountedFee"]],
arms: {
txsMaybeDiscountedFee: xdr.lookup("TxSetComponentTxsMaybeDiscountedFee")
}
});
// === xdr source ============================================================
//
// union TransactionPhase switch (int v)
// {
// case 0:
// TxSetComponent v0Components<>;
// };
//
// ===========================================================================
xdr.union("TransactionPhase", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, "v0Components"]],
arms: {
v0Components: xdr.varArray(xdr.lookup("TxSetComponent"), 2147483647)
}
});
// === xdr source ============================================================
//
// struct TransactionSet
// {
// Hash previousLedgerHash;
// TransactionEnvelope txs<>;
// };
//
// ===========================================================================
xdr.struct("TransactionSet", [["previousLedgerHash", xdr.lookup("Hash")], ["txes", xdr.varArray(xdr.lookup("TransactionEnvelope"), 2147483647)]]);
// === xdr source ============================================================
//
// struct TransactionSetV1
// {
// Hash previousLedgerHash;
// TransactionPhase phases<>;
// };
//
// ===========================================================================
xdr.struct("TransactionSetV1", [["previousLedgerHash", xdr.lookup("Hash")], ["phases", xdr.varArray(xdr.lookup("TransactionPhase"), 2147483647)]]);
// === xdr source ============================================================
//
// union GeneralizedTransactionSet switch (int v)
// {
// // We consider the legacy TransactionSet to be v0.
// case 1:
// TransactionSetV1 v1TxSet;
// };
//
// ===========================================================================
xdr.union("GeneralizedTransactionSet", {
switchOn: xdr.int(),
switchName: "v",
switches: [[1, "v1TxSet"]],
arms: {
v1TxSet: xdr.lookup("TransactionSetV1")
}
});
// === xdr source ============================================================
//
// struct TransactionResultPair
// {
// Hash transactionHash;
// TransactionResult result; // result for the transaction
// };
//
// ===========================================================================
xdr.struct("TransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("TransactionResult")]]);
// === xdr source ============================================================
//
// struct TransactionResultSet
// {
// TransactionResultPair results<>;
// };
//
// ===========================================================================
xdr.struct("TransactionResultSet", [["results", xdr.varArray(xdr.lookup("TransactionResultPair"), 2147483647)]]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// GeneralizedTransactionSet generalizedTxSet;
// }
//
// ===========================================================================
xdr.union("TransactionHistoryEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()], [1, "generalizedTxSet"]],
arms: {
generalizedTxSet: xdr.lookup("GeneralizedTransactionSet")
}
});
// === xdr source ============================================================
//
// struct TransactionHistoryEntry
// {
// uint32 ledgerSeq;
// TransactionSet txSet;
//
// // when v != 0, txSet must be empty
// union switch (int v)
// {
// case 0:
// void;
// case 1:
// GeneralizedTransactionSet generalizedTxSet;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("TransactionHistoryEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txSet", xdr.lookup("TransactionSet")], ["ext", xdr.lookup("TransactionHistoryEntryExt")]]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("TransactionHistoryResultEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// struct TransactionHistoryResultEntry
// {
// uint32 ledgerSeq;
// TransactionResultSet txResultSet;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("TransactionHistoryResultEntry", [["ledgerSeq", xdr.lookup("Uint32")], ["txResultSet", xdr.lookup("TransactionResultSet")], ["ext", xdr.lookup("TransactionHistoryResultEntryExt")]]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("LedgerHeaderHistoryEntryExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// struct LedgerHeaderHistoryEntry
// {
// Hash hash;
// LedgerHeader header;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("LedgerHeaderHistoryEntry", [["hash", xdr.lookup("Hash")], ["header", xdr.lookup("LedgerHeader")], ["ext", xdr.lookup("LedgerHeaderHistoryEntryExt")]]);
// === xdr source ============================================================
//
// struct LedgerSCPMessages
// {
// uint32 ledgerSeq;
// SCPEnvelope messages<>;
// };
//
// ===========================================================================
xdr.struct("LedgerScpMessages", [["ledgerSeq", xdr.lookup("Uint32")], ["messages", xdr.varArray(xdr.lookup("ScpEnvelope"), 2147483647)]]);
// === xdr source ============================================================
//
// struct SCPHistoryEntryV0
// {
// SCPQuorumSet quorumSets<>; // additional quorum sets used by ledgerMessages
// LedgerSCPMessages ledgerMessages;
// };
//
// ===========================================================================
xdr.struct("ScpHistoryEntryV0", [["quorumSets", xdr.varArray(xdr.lookup("ScpQuorumSet"), 2147483647)], ["ledgerMessages", xdr.lookup("LedgerScpMessages")]]);
// === xdr source ============================================================
//
// union SCPHistoryEntry switch (int v)
// {
// case 0:
// SCPHistoryEntryV0 v0;
// };
//
// ===========================================================================
xdr.union("ScpHistoryEntry", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, "v0"]],
arms: {
v0: xdr.lookup("ScpHistoryEntryV0")
}
});
// === xdr source ============================================================
//
// enum LedgerEntryChangeType
// {
// LEDGER_ENTRY_CREATED = 0, // entry was added to the ledger
// LEDGER_ENTRY_UPDATED = 1, // entry was modified in the ledger
// LEDGER_ENTRY_REMOVED = 2, // entry was removed from the ledger
// LEDGER_ENTRY_STATE = 3 // value of the entry
// };
//
// ===========================================================================
xdr.enum("LedgerEntryChangeType", {
ledgerEntryCreated: 0,
ledgerEntryUpdated: 1,
ledgerEntryRemoved: 2,
ledgerEntryState: 3
});
// === xdr source ============================================================
//
// union LedgerEntryChange switch (LedgerEntryChangeType type)
// {
// case LEDGER_ENTRY_CREATED:
// LedgerEntry created;
// case LEDGER_ENTRY_UPDATED:
// LedgerEntry updated;
// case LEDGER_ENTRY_REMOVED:
// LedgerKey removed;
// case LEDGER_ENTRY_STATE:
// LedgerEntry state;
// };
//
// ===========================================================================
xdr.union("LedgerEntryChange", {
switchOn: xdr.lookup("LedgerEntryChangeType"),
switchName: "type",
switches: [["ledgerEntryCreated", "created"], ["ledgerEntryUpdated", "updated"], ["ledgerEntryRemoved", "removed"], ["ledgerEntryState", "state"]],
arms: {
created: xdr.lookup("LedgerEntry"),
updated: xdr.lookup("LedgerEntry"),
removed: xdr.lookup("LedgerKey"),
state: xdr.lookup("LedgerEntry")
}
});
// === xdr source ============================================================
//
// typedef LedgerEntryChange LedgerEntryChanges<>;
//
// ===========================================================================
xdr.typedef("LedgerEntryChanges", xdr.varArray(xdr.lookup("LedgerEntryChange"), 2147483647));
// === xdr source ============================================================
//
// struct OperationMeta
// {
// LedgerEntryChanges changes;
// };
//
// ===========================================================================
xdr.struct("OperationMeta", [["changes", xdr.lookup("LedgerEntryChanges")]]);
// === xdr source ============================================================
//
// struct TransactionMetaV1
// {
// LedgerEntryChanges txChanges; // tx level changes if any
// OperationMeta operations<>; // meta for each operation
// };
//
// ===========================================================================
xdr.struct("TransactionMetaV1", [["txChanges", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)]]);
// === xdr source ============================================================
//
// struct TransactionMetaV2
// {
// LedgerEntryChanges txChangesBefore; // tx level changes before operations
// // are applied if any
// OperationMeta operations<>; // meta for each operation
// LedgerEntryChanges txChangesAfter; // tx level changes after operations are
// // applied if any
// };
//
// ===========================================================================
xdr.struct("TransactionMetaV2", [["txChangesBefore", xdr.lookup("LedgerEntryChanges")], ["operations", xdr.varArray(xdr.lookup("OperationMeta"), 2147483647)], ["txChangesAfter", xdr.lookup("LedgerEntryChanges")]]);
// === xdr source ============================================================
//
// union TransactionMeta switch (int v)
// {
// case 0:
// OperationMeta operations<>;
// case 1:
// TransactionMetaV1 v1;
// case 2:
// TransactionMetaV2 v2;
// };
//
// ===========================================================================
xdr.union("TransactionMeta", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, "operations"], [1, "v1"], [2, "v2"]],
arms: {
operations: xdr.varArray(xdr.lookup("OperationMeta"), 2147483647),
v1: xdr.lookup("TransactionMetaV1"),
v2: xdr.lookup("TransactionMetaV2")
}
});
// === xdr source ============================================================
//
// struct TransactionResultMeta
// {
// TransactionResultPair result;
// LedgerEntryChanges feeProcessing;
// TransactionMeta txApplyProcessing;
// };
//
// ===========================================================================
xdr.struct("TransactionResultMeta", [["result", xdr.lookup("TransactionResultPair")], ["feeProcessing", xdr.lookup("LedgerEntryChanges")], ["txApplyProcessing", xdr.lookup("TransactionMeta")]]);
// === xdr source ============================================================
//
// struct UpgradeEntryMeta
// {
// LedgerUpgrade upgrade;
// LedgerEntryChanges changes;
// };
//
// ===========================================================================
xdr.struct("UpgradeEntryMeta", [["upgrade", xdr.lookup("LedgerUpgrade")], ["changes", xdr.lookup("LedgerEntryChanges")]]);
// === xdr source ============================================================
//
// struct LedgerCloseMetaV0
// {
// LedgerHeaderHistoryEntry ledgerHeader;
// // NB: txSet is sorted in "Hash order"
// TransactionSet txSet;
//
// // NB: transactions are sorted in apply order here
// // fees for all transactions are processed first
// // followed by applying transactions
// TransactionResultMeta txProcessing<>;
//
// // upgrades are applied last
// UpgradeEntryMeta upgradesProcessing<>;
//
// // other misc information attached to the ledger close
// SCPHistoryEntry scpInfo<>;
// };
//
// ===========================================================================
xdr.struct("LedgerCloseMetaV0", [["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")], ["txSet", xdr.lookup("TransactionSet")], ["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)], ["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)], ["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)]]);
// === xdr source ============================================================
//
// struct LedgerCloseMetaV1
// {
// LedgerHeaderHistoryEntry ledgerHeader;
//
// GeneralizedTransactionSet txSet;
//
// // NB: transactions are sorted in apply order here
// // fees for all transactions are processed first
// // followed by applying transactions
// TransactionResultMeta txProcessing<>;
//
// // upgrades are applied last
// UpgradeEntryMeta upgradesProcessing<>;
//
// // other misc information attached to the ledger close
// SCPHistoryEntry scpInfo<>;
// };
//
// ===========================================================================
xdr.struct("LedgerCloseMetaV1", [["ledgerHeader", xdr.lookup("LedgerHeaderHistoryEntry")], ["txSet", xdr.lookup("GeneralizedTransactionSet")], ["txProcessing", xdr.varArray(xdr.lookup("TransactionResultMeta"), 2147483647)], ["upgradesProcessing", xdr.varArray(xdr.lookup("UpgradeEntryMeta"), 2147483647)], ["scpInfo", xdr.varArray(xdr.lookup("ScpHistoryEntry"), 2147483647)]]);
// === xdr source ============================================================
//
// union LedgerCloseMeta switch (int v)
// {
// case 0:
// LedgerCloseMetaV0 v0;
// case 1:
// LedgerCloseMetaV1 v1;
// };
//
// ===========================================================================
xdr.union("LedgerCloseMeta", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, "v0"], [1, "v1"]],
arms: {
v0: xdr.lookup("LedgerCloseMetaV0"),
v1: xdr.lookup("LedgerCloseMetaV1")
}
});
// === xdr source ============================================================
//
// enum ErrorCode
// {
// ERR_MISC = 0, // Unspecific error
// ERR_DATA = 1, // Malformed data
// ERR_CONF = 2, // Misconfiguration error
// ERR_AUTH = 3, // Authentication failure
// ERR_LOAD = 4 // System overloaded
// };
//
// ===========================================================================
xdr.enum("ErrorCode", {
errMisc: 0,
errData: 1,
errConf: 2,
errAuth: 3,
errLoad: 4
});
// === xdr source ============================================================
//
// struct Error
// {
// ErrorCode code;
// string msg<100>;
// };
//
// ===========================================================================
xdr.struct("Error", [["code", xdr.lookup("ErrorCode")], ["msg", xdr.string(100)]]);
// === xdr source ============================================================
//
// struct SendMore
// {
// uint32 numMessages;
// };
//
// ===========================================================================
xdr.struct("SendMore", [["numMessages", xdr.lookup("Uint32")]]);
// === xdr source ============================================================
//
// struct AuthCert
// {
// Curve25519Public pubkey;
// uint64 expiration;
// Signature sig;
// };
//
// ===========================================================================
xdr.struct("AuthCert", [["pubkey", xdr.lookup("Curve25519Public")], ["expiration", xdr.lookup("Uint64")], ["sig", xdr.lookup("Signature")]]);
// === xdr source ============================================================
//
// struct Hello
// {
// uint32 ledgerVersion;
// uint32 overlayVersion;
// uint32 overlayMinVersion;
// Hash networkID;
// string versionStr<100>;
// int listeningPort;
// NodeID peerID;
// AuthCert cert;
// uint256 nonce;
// };
//
// ===========================================================================
xdr.struct("Hello", [["ledgerVersion", xdr.lookup("Uint32")], ["overlayVersion", xdr.lookup("Uint32")], ["overlayMinVersion", xdr.lookup("Uint32")], ["networkId", xdr.lookup("Hash")], ["versionStr", xdr.string(100)], ["listeningPort", xdr.int()], ["peerId", xdr.lookup("NodeId")], ["cert", xdr.lookup("AuthCert")], ["nonce", xdr.lookup("Uint256")]]);
// === xdr source ============================================================
//
// struct Auth
// {
// // Empty message, just to confirm
// // establishment of MAC keys.
// int unused;
// };
//
// ===========================================================================
xdr.struct("Auth", [["unused", xdr.int()]]);
// === xdr source ============================================================
//
// enum IPAddrType
// {
// IPv4 = 0,
// IPv6 = 1
// };
//
// ===========================================================================
xdr.enum("IpAddrType", {
iPv4: 0,
iPv6: 1
});
// === xdr source ============================================================
//
// union switch (IPAddrType type)
// {
// case IPv4:
// opaque ipv4[4];
// case IPv6:
// opaque ipv6[16];
// }
//
// ===========================================================================
xdr.union("PeerAddressIp", {
switchOn: xdr.lookup("IpAddrType"),
switchName: "type",
switches: [["iPv4", "ipv4"], ["iPv6", "ipv6"]],
arms: {
ipv4: xdr.opaque(4),
ipv6: xdr.opaque(16)
}
});
// === xdr source ============================================================
//
// struct PeerAddress
// {
// union switch (IPAddrType type)
// {
// case IPv4:
// opaque ipv4[4];
// case IPv6:
// opaque ipv6[16];
// }
// ip;
// uint32 port;
// uint32 numFailures;
// };
//
// ===========================================================================
xdr.struct("PeerAddress", [["ip", xdr.lookup("PeerAddressIp")], ["port", xdr.lookup("Uint32")], ["numFailures", xdr.lookup("Uint32")]]);
// === xdr source ============================================================
//
// enum MessageType
// {
// ERROR_MSG = 0,
// AUTH = 2,
// DONT_HAVE = 3,
//
// GET_PEERS = 4, // gets a list of peers this guy knows about
// PEERS = 5,
//
// GET_TX_SET = 6, // gets a particular txset by hash
// TX_SET = 7,
// GENERALIZED_TX_SET = 17,
//
// TRANSACTION = 8, // pass on a tx you have heard about
//
// // SCP
// GET_SCP_QUORUMSET = 9,
// SCP_QUORUMSET = 10,
// SCP_MESSAGE = 11,
// GET_SCP_STATE = 12,
//
// // new messages
// HELLO = 13,
//
// SURVEY_REQUEST = 14,
// SURVEY_RESPONSE = 15,
//
// SEND_MORE = 16
// };
//
// ===========================================================================
xdr.enum("MessageType", {
errorMsg: 0,
auth: 2,
dontHave: 3,
getPeers: 4,
peers: 5,
getTxSet: 6,
txSet: 7,
generalizedTxSet: 17,
transaction: 8,
getScpQuorumset: 9,
scpQuorumset: 10,
scpMessage: 11,
getScpState: 12,
hello: 13,
surveyRequest: 14,
surveyResponse: 15,
sendMore: 16
});
// === xdr source ============================================================
//
// struct DontHave
// {
// MessageType type;
// uint256 reqHash;
// };
//
// ===========================================================================
xdr.struct("DontHave", [["type", xdr.lookup("MessageType")], ["reqHash", xdr.lookup("Uint256")]]);
// === xdr source ============================================================
//
// enum SurveyMessageCommandType
// {
// SURVEY_TOPOLOGY = 0
// };
//
// ===========================================================================
xdr.enum("SurveyMessageCommandType", {
surveyTopology: 0
});
// === xdr source ============================================================
//
// struct SurveyRequestMessage
// {
// NodeID surveyorPeerID;
// NodeID surveyedPeerID;
// uint32 ledgerNum;
// Curve25519Public encryptionKey;
// SurveyMessageCommandType commandType;
// };
//
// ===========================================================================
xdr.struct("SurveyRequestMessage", [["surveyorPeerId", xdr.lookup("NodeId")], ["surveyedPeerId", xdr.lookup("NodeId")], ["ledgerNum", xdr.lookup("Uint32")], ["encryptionKey", xdr.lookup("Curve25519Public")], ["commandType", xdr.lookup("SurveyMessageCommandType")]]);
// === xdr source ============================================================
//
// struct SignedSurveyRequestMessage
// {
// Signature requestSignature;
// SurveyRequestMessage request;
// };
//
// ===========================================================================
xdr.struct("SignedSurveyRequestMessage", [["requestSignature", xdr.lookup("Signature")], ["request", xdr.lookup("SurveyRequestMessage")]]);
// === xdr source ============================================================
//
// typedef opaque EncryptedBody<64000>;
//
// ===========================================================================
xdr.typedef("EncryptedBody", xdr.varOpaque(64000));
// === xdr source ============================================================
//
// struct SurveyResponseMessage
// {
// NodeID surveyorPeerID;
// NodeID surveyedPeerID;
// uint32 ledgerNum;
// SurveyMessageCommandType commandType;
// EncryptedBody encryptedBody;
// };
//
// ===========================================================================
xdr.struct("SurveyResponseMessage", [["surveyorPeerId", xdr.lookup("NodeId")], ["surveyedPeerId", xdr.lookup("NodeId")], ["ledgerNum", xdr.lookup("Uint32")], ["commandType", xdr.lookup("SurveyMessageCommandType")], ["encryptedBody", xdr.lookup("EncryptedBody")]]);
// === xdr source ============================================================
//
// struct SignedSurveyResponseMessage
// {
// Signature responseSignature;
// SurveyResponseMessage response;
// };
//
// ===========================================================================
xdr.struct("SignedSurveyResponseMessage", [["responseSignature", xdr.lookup("Signature")], ["response", xdr.lookup("SurveyResponseMessage")]]);
// === xdr source ============================================================
//
// struct PeerStats
// {
// NodeID id;
// string versionStr<100>;
// uint64 messagesRead;
// uint64 messagesWritten;
// uint64 bytesRead;
// uint64 bytesWritten;
// uint64 secondsConnected;
//
// uint64 uniqueFloodBytesRecv;
// uint64 duplicateFloodBytesRecv;
// uint64 uniqueFetchBytesRecv;
// uint64 duplicateFetchBytesRecv;
//
// uint64 uniqueFloodMessageRecv;
// uint64 duplicateFloodMessageRecv;
// uint64 uniqueFetchMessageRecv;
// uint64 duplicateFetchMessageRecv;
// };
//
// ===========================================================================
xdr.struct("PeerStats", [["id", xdr.lookup("NodeId")], ["versionStr", xdr.string(100)], ["messagesRead", xdr.lookup("Uint64")], ["messagesWritten", xdr.lookup("Uint64")], ["bytesRead", xdr.lookup("Uint64")], ["bytesWritten", xdr.lookup("Uint64")], ["secondsConnected", xdr.lookup("Uint64")], ["uniqueFloodBytesRecv", xdr.lookup("Uint64")], ["duplicateFloodBytesRecv", xdr.lookup("Uint64")], ["uniqueFetchBytesRecv", xdr.lookup("Uint64")], ["duplicateFetchBytesRecv", xdr.lookup("Uint64")], ["uniqueFloodMessageRecv", xdr.lookup("Uint64")], ["duplicateFloodMessageRecv", xdr.lookup("Uint64")], ["uniqueFetchMessageRecv", xdr.lookup("Uint64")], ["duplicateFetchMessageRecv", xdr.lookup("Uint64")]]);
// === xdr source ============================================================
//
// typedef PeerStats PeerStatList<25>;
//
// ===========================================================================
xdr.typedef("PeerStatList", xdr.varArray(xdr.lookup("PeerStats"), 25));
// === xdr source ============================================================
//
// struct TopologyResponseBody
// {
// PeerStatList inboundPeers;
// PeerStatList outboundPeers;
//
// uint32 totalInboundPeerCount;
// uint32 totalOutboundPeerCount;
// };
//
// ===========================================================================
xdr.struct("TopologyResponseBody", [["inboundPeers", xdr.lookup("PeerStatList")], ["outboundPeers", xdr.lookup("PeerStatList")], ["totalInboundPeerCount", xdr.lookup("Uint32")], ["totalOutboundPeerCount", xdr.lookup("Uint32")]]);
// === xdr source ============================================================
//
// union SurveyResponseBody switch (SurveyMessageCommandType type)
// {
// case SURVEY_TOPOLOGY:
// TopologyResponseBody topologyResponseBody;
// };
//
// ===========================================================================
xdr.union("SurveyResponseBody", {
switchOn: xdr.lookup("SurveyMessageCommandType"),
switchName: "type",
switches: [["surveyTopology", "topologyResponseBody"]],
arms: {
topologyResponseBody: xdr.lookup("TopologyResponseBody")
}
});
// === xdr source ============================================================
//
// union StellarMessage switch (MessageType type)
// {
// case ERROR_MSG:
// Error error;
// case HELLO:
// Hello hello;
// case AUTH:
// Auth auth;
// case DONT_HAVE:
// DontHave dontHave;
// case GET_PEERS:
// void;
// case PEERS:
// PeerAddress peers<100>;
//
// case GET_TX_SET:
// uint256 txSetHash;
// case TX_SET:
// TransactionSet txSet;
// case GENERALIZED_TX_SET:
// GeneralizedTransactionSet generalizedTxSet;
//
// case TRANSACTION:
// TransactionEnvelope transaction;
//
// case SURVEY_REQUEST:
// SignedSurveyRequestMessage signedSurveyRequestMessage;
//
// case SURVEY_RESPONSE:
// SignedSurveyResponseMessage signedSurveyResponseMessage;
//
// // SCP
// case GET_SCP_QUORUMSET:
// uint256 qSetHash;
// case SCP_QUORUMSET:
// SCPQuorumSet qSet;
// case SCP_MESSAGE:
// SCPEnvelope envelope;
// case GET_SCP_STATE:
// uint32 getSCPLedgerSeq; // ledger seq requested ; if 0, requests the latest
// case SEND_MORE:
// SendMore sendMoreMessage;
// };
//
// ===========================================================================
xdr.union("StellarMessage", {
switchOn: xdr.lookup("MessageType"),
switchName: "type",
switches: [["errorMsg", "error"], ["hello", "hello"], ["auth", "auth"], ["dontHave", "dontHave"], ["getPeers", xdr.void()], ["peers", "peers"], ["getTxSet", "txSetHash"], ["txSet", "txSet"], ["generalizedTxSet", "generalizedTxSet"], ["transaction", "transaction"], ["surveyRequest", "signedSurveyRequestMessage"], ["surveyResponse", "signedSurveyResponseMessage"], ["getScpQuorumset", "qSetHash"], ["scpQuorumset", "qSet"], ["scpMessage", "envelope"], ["getScpState", "getScpLedgerSeq"], ["sendMore", "sendMoreMessage"]],
arms: {
error: xdr.lookup("Error"),
hello: xdr.lookup("Hello"),
auth: xdr.lookup("Auth"),
dontHave: xdr.lookup("DontHave"),
peers: xdr.varArray(xdr.lookup("PeerAddress"), 100),
txSetHash: xdr.lookup("Uint256"),
txSet: xdr.lookup("TransactionSet"),
generalizedTxSet: xdr.lookup("GeneralizedTransactionSet"),
transaction: xdr.lookup("TransactionEnvelope"),
signedSurveyRequestMessage: xdr.lookup("SignedSurveyRequestMessage"),
signedSurveyResponseMessage: xdr.lookup("SignedSurveyResponseMessage"),
qSetHash: xdr.lookup("Uint256"),
qSet: xdr.lookup("ScpQuorumSet"),
envelope: xdr.lookup("ScpEnvelope"),
getScpLedgerSeq: xdr.lookup("Uint32"),
sendMoreMessage: xdr.lookup("SendMore")
}
});
// === xdr source ============================================================
//
// struct
// {
// uint64 sequence;
// StellarMessage message;
// HmacSha256Mac mac;
// }
//
// ===========================================================================
xdr.struct("AuthenticatedMessageV0", [["sequence", xdr.lookup("Uint64")], ["message", xdr.lookup("StellarMessage")], ["mac", xdr.lookup("HmacSha256Mac")]]);
// === xdr source ============================================================
//
// union AuthenticatedMessage switch (uint32 v)
// {
// case 0:
// struct
// {
// uint64 sequence;
// StellarMessage message;
// HmacSha256Mac mac;
// } v0;
// };
//
// ===========================================================================
xdr.union("AuthenticatedMessage", {
switchOn: xdr.lookup("Uint32"),
switchName: "v",
switches: [[0, "v0"]],
arms: {
v0: xdr.lookup("AuthenticatedMessageV0")
}
});
// === xdr source ============================================================
//
// union LiquidityPoolParameters switch (LiquidityPoolType type)
// {
// case LIQUIDITY_POOL_CONSTANT_PRODUCT:
// LiquidityPoolConstantProductParameters constantProduct;
// };
//
// ===========================================================================
xdr.union("LiquidityPoolParameters", {
switchOn: xdr.lookup("LiquidityPoolType"),
switchName: "type",
switches: [["liquidityPoolConstantProduct", "constantProduct"]],
arms: {
constantProduct: xdr.lookup("LiquidityPoolConstantProductParameters")
}
});
// === xdr source ============================================================
//
// struct
// {
// uint64 id;
// uint256 ed25519;
// }
//
// ===========================================================================
xdr.struct("MuxedAccountMed25519", [["id", xdr.lookup("Uint64")], ["ed25519", xdr.lookup("Uint256")]]);
// === xdr source ============================================================
//
// union MuxedAccount switch (CryptoKeyType type)
// {
// case KEY_TYPE_ED25519:
// uint256 ed25519;
// case KEY_TYPE_MUXED_ED25519:
// struct
// {
// uint64 id;
// uint256 ed25519;
// } med25519;
// };
//
// ===========================================================================
xdr.union("MuxedAccount", {
switchOn: xdr.lookup("CryptoKeyType"),
switchName: "type",
switches: [["keyTypeEd25519", "ed25519"], ["keyTypeMuxedEd25519", "med25519"]],
arms: {
ed25519: xdr.lookup("Uint256"),
med25519: xdr.lookup("MuxedAccountMed25519")
}
});
// === xdr source ============================================================
//
// struct DecoratedSignature
// {
// SignatureHint hint; // last 4 bytes of the public key, used as a hint
// Signature signature; // actual signature
// };
//
// ===========================================================================
xdr.struct("DecoratedSignature", [["hint", xdr.lookup("SignatureHint")], ["signature", xdr.lookup("Signature")]]);
// === xdr source ============================================================
//
// enum OperationType
// {
// CREATE_ACCOUNT = 0,
// PAYMENT = 1,
// PATH_PAYMENT_STRICT_RECEIVE = 2,
// MANAGE_SELL_OFFER = 3,
// CREATE_PASSIVE_SELL_OFFER = 4,
// SET_OPTIONS = 5,
// CHANGE_TRUST = 6,
// ALLOW_TRUST = 7,
// ACCOUNT_MERGE = 8,
// INFLATION = 9,
// MANAGE_DATA = 10,
// BUMP_SEQUENCE = 11,
// MANAGE_BUY_OFFER = 12,
// PATH_PAYMENT_STRICT_SEND = 13,
// CREATE_CLAIMABLE_BALANCE = 14,
// CLAIM_CLAIMABLE_BALANCE = 15,
// BEGIN_SPONSORING_FUTURE_RESERVES = 16,
// END_SPONSORING_FUTURE_RESERVES = 17,
// REVOKE_SPONSORSHIP = 18,
// CLAWBACK = 19,
// CLAWBACK_CLAIMABLE_BALANCE = 20,
// SET_TRUST_LINE_FLAGS = 21,
// LIQUIDITY_POOL_DEPOSIT = 22,
// LIQUIDITY_POOL_WITHDRAW = 23
// };
//
// ===========================================================================
xdr.enum("OperationType", {
createAccount: 0,
payment: 1,
pathPaymentStrictReceive: 2,
manageSellOffer: 3,
createPassiveSellOffer: 4,
setOptions: 5,
changeTrust: 6,
allowTrust: 7,
accountMerge: 8,
inflation: 9,
manageData: 10,
bumpSequence: 11,
manageBuyOffer: 12,
pathPaymentStrictSend: 13,
createClaimableBalance: 14,
claimClaimableBalance: 15,
beginSponsoringFutureReserves: 16,
endSponsoringFutureReserves: 17,
revokeSponsorship: 18,
clawback: 19,
clawbackClaimableBalance: 20,
setTrustLineFlags: 21,
liquidityPoolDeposit: 22,
liquidityPoolWithdraw: 23
});
// === xdr source ============================================================
//
// struct CreateAccountOp
// {
// AccountID destination; // account to create
// int64 startingBalance; // amount they end up with
// };
//
// ===========================================================================
xdr.struct("CreateAccountOp", [["destination", xdr.lookup("AccountId")], ["startingBalance", xdr.lookup("Int64")]]);
// === xdr source ============================================================
//
// struct PaymentOp
// {
// MuxedAccount destination; // recipient of the payment
// Asset asset; // what they end up with
// int64 amount; // amount they end up with
// };
//
// ===========================================================================
xdr.struct("PaymentOp", [["destination", xdr.lookup("MuxedAccount")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]);
// === xdr source ============================================================
//
// struct PathPaymentStrictReceiveOp
// {
// Asset sendAsset; // asset we pay with
// int64 sendMax; // the maximum amount of sendAsset to
// // send (excluding fees).
// // The operation will fail if can't be met
//
// MuxedAccount destination; // recipient of the payment
// Asset destAsset; // what they end up with
// int64 destAmount; // amount they end up with
//
// Asset path<5>; // additional hops it must go through to get there
// };
//
// ===========================================================================
xdr.struct("PathPaymentStrictReceiveOp", [["sendAsset", xdr.lookup("Asset")], ["sendMax", xdr.lookup("Int64")], ["destination", xdr.lookup("MuxedAccount")], ["destAsset", xdr.lookup("Asset")], ["destAmount", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]);
// === xdr source ============================================================
//
// struct PathPaymentStrictSendOp
// {
// Asset sendAsset; // asset we pay with
// int64 sendAmount; // amount of sendAsset to send (excluding fees)
//
// MuxedAccount destination; // recipient of the payment
// Asset destAsset; // what they end up with
// int64 destMin; // the minimum amount of dest asset to
// // be received
// // The operation will fail if it can't be met
//
// Asset path<5>; // additional hops it must go through to get there
// };
//
// ===========================================================================
xdr.struct("PathPaymentStrictSendOp", [["sendAsset", xdr.lookup("Asset")], ["sendAmount", xdr.lookup("Int64")], ["destination", xdr.lookup("MuxedAccount")], ["destAsset", xdr.lookup("Asset")], ["destMin", xdr.lookup("Int64")], ["path", xdr.varArray(xdr.lookup("Asset"), 5)]]);
// === xdr source ============================================================
//
// struct ManageSellOfferOp
// {
// Asset selling;
// Asset buying;
// int64 amount; // amount being sold. if set to 0, delete the offer
// Price price; // price of thing being sold in terms of what you are buying
//
// // 0=create a new offer, otherwise edit an existing offer
// int64 offerID;
// };
//
// ===========================================================================
xdr.struct("ManageSellOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Int64")]]);
// === xdr source ============================================================
//
// struct ManageBuyOfferOp
// {
// Asset selling;
// Asset buying;
// int64 buyAmount; // amount being bought. if set to 0, delete the offer
// Price price; // price of thing being bought in terms of what you are
// // selling
//
// // 0=create a new offer, otherwise edit an existing offer
// int64 offerID;
// };
//
// ===========================================================================
xdr.struct("ManageBuyOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["buyAmount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")], ["offerId", xdr.lookup("Int64")]]);
// === xdr source ============================================================
//
// struct CreatePassiveSellOfferOp
// {
// Asset selling; // A
// Asset buying; // B
// int64 amount; // amount taker gets
// Price price; // cost of A in terms of B
// };
//
// ===========================================================================
xdr.struct("CreatePassiveSellOfferOp", [["selling", xdr.lookup("Asset")], ["buying", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["price", xdr.lookup("Price")]]);
// === xdr source ============================================================
//
// struct SetOptionsOp
// {
// AccountID* inflationDest; // sets the inflation destination
//
// uint32* clearFlags; // which flags to clear
// uint32* setFlags; // which flags to set
//
// // account threshold manipulation
// uint32* masterWeight; // weight of the master account
// uint32* lowThreshold;
// uint32* medThreshold;
// uint32* highThreshold;
//
// string32* homeDomain; // sets the home domain
//
// // Add, update or remove a signer for the account
// // signer is deleted if the weight is 0
// Signer* signer;
// };
//
// ===========================================================================
xdr.struct("SetOptionsOp", [["inflationDest", xdr.option(xdr.lookup("AccountId"))], ["clearFlags", xdr.option(xdr.lookup("Uint32"))], ["setFlags", xdr.option(xdr.lookup("Uint32"))], ["masterWeight", xdr.option(xdr.lookup("Uint32"))], ["lowThreshold", xdr.option(xdr.lookup("Uint32"))], ["medThreshold", xdr.option(xdr.lookup("Uint32"))], ["highThreshold", xdr.option(xdr.lookup("Uint32"))], ["homeDomain", xdr.option(xdr.lookup("String32"))], ["signer", xdr.option(xdr.lookup("Signer"))]]);
// === xdr source ============================================================
//
// union ChangeTrustAsset switch (AssetType type)
// {
// case ASSET_TYPE_NATIVE: // Not credit
// void;
//
// case ASSET_TYPE_CREDIT_ALPHANUM4:
// AlphaNum4 alphaNum4;
//
// case ASSET_TYPE_CREDIT_ALPHANUM12:
// AlphaNum12 alphaNum12;
//
// case ASSET_TYPE_POOL_SHARE:
// LiquidityPoolParameters liquidityPool;
//
// // add other asset types here in the future
// };
//
// ===========================================================================
xdr.union("ChangeTrustAsset", {
switchOn: xdr.lookup("AssetType"),
switchName: "type",
switches: [["assetTypeNative", xdr.void()], ["assetTypeCreditAlphanum4", "alphaNum4"], ["assetTypeCreditAlphanum12", "alphaNum12"], ["assetTypePoolShare", "liquidityPool"]],
arms: {
alphaNum4: xdr.lookup("AlphaNum4"),
alphaNum12: xdr.lookup("AlphaNum12"),
liquidityPool: xdr.lookup("LiquidityPoolParameters")
}
});
// === xdr source ============================================================
//
// struct ChangeTrustOp
// {
// ChangeTrustAsset line;
//
// // if limit is set to 0, deletes the trust line
// int64 limit;
// };
//
// ===========================================================================
xdr.struct("ChangeTrustOp", [["line", xdr.lookup("ChangeTrustAsset")], ["limit", xdr.lookup("Int64")]]);
// === xdr source ============================================================
//
// struct AllowTrustOp
// {
// AccountID trustor;
// AssetCode asset;
//
// // One of 0, AUTHORIZED_FLAG, or AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG
// uint32 authorize;
// };
//
// ===========================================================================
xdr.struct("AllowTrustOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("AssetCode")], ["authorize", xdr.lookup("Uint32")]]);
// === xdr source ============================================================
//
// struct ManageDataOp
// {
// string64 dataName;
// DataValue* dataValue; // set to null to clear
// };
//
// ===========================================================================
xdr.struct("ManageDataOp", [["dataName", xdr.lookup("String64")], ["dataValue", xdr.option(xdr.lookup("DataValue"))]]);
// === xdr source ============================================================
//
// struct BumpSequenceOp
// {
// SequenceNumber bumpTo;
// };
//
// ===========================================================================
xdr.struct("BumpSequenceOp", [["bumpTo", xdr.lookup("SequenceNumber")]]);
// === xdr source ============================================================
//
// struct CreateClaimableBalanceOp
// {
// Asset asset;
// int64 amount;
// Claimant claimants<10>;
// };
//
// ===========================================================================
xdr.struct("CreateClaimableBalanceOp", [["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")], ["claimants", xdr.varArray(xdr.lookup("Claimant"), 10)]]);
// === xdr source ============================================================
//
// struct ClaimClaimableBalanceOp
// {
// ClaimableBalanceID balanceID;
// };
//
// ===========================================================================
xdr.struct("ClaimClaimableBalanceOp", [["balanceId", xdr.lookup("ClaimableBalanceId")]]);
// === xdr source ============================================================
//
// struct BeginSponsoringFutureReservesOp
// {
// AccountID sponsoredID;
// };
//
// ===========================================================================
xdr.struct("BeginSponsoringFutureReservesOp", [["sponsoredId", xdr.lookup("AccountId")]]);
// === xdr source ============================================================
//
// enum RevokeSponsorshipType
// {
// REVOKE_SPONSORSHIP_LEDGER_ENTRY = 0,
// REVOKE_SPONSORSHIP_SIGNER = 1
// };
//
// ===========================================================================
xdr.enum("RevokeSponsorshipType", {
revokeSponsorshipLedgerEntry: 0,
revokeSponsorshipSigner: 1
});
// === xdr source ============================================================
//
// struct
// {
// AccountID accountID;
// SignerKey signerKey;
// }
//
// ===========================================================================
xdr.struct("RevokeSponsorshipOpSigner", [["accountId", xdr.lookup("AccountId")], ["signerKey", xdr.lookup("SignerKey")]]);
// === xdr source ============================================================
//
// union RevokeSponsorshipOp switch (RevokeSponsorshipType type)
// {
// case REVOKE_SPONSORSHIP_LEDGER_ENTRY:
// LedgerKey ledgerKey;
// case REVOKE_SPONSORSHIP_SIGNER:
// struct
// {
// AccountID accountID;
// SignerKey signerKey;
// } signer;
// };
//
// ===========================================================================
xdr.union("RevokeSponsorshipOp", {
switchOn: xdr.lookup("RevokeSponsorshipType"),
switchName: "type",
switches: [["revokeSponsorshipLedgerEntry", "ledgerKey"], ["revokeSponsorshipSigner", "signer"]],
arms: {
ledgerKey: xdr.lookup("LedgerKey"),
signer: xdr.lookup("RevokeSponsorshipOpSigner")
}
});
// === xdr source ============================================================
//
// struct ClawbackOp
// {
// Asset asset;
// MuxedAccount from;
// int64 amount;
// };
//
// ===========================================================================
xdr.struct("ClawbackOp", [["asset", xdr.lookup("Asset")], ["from", xdr.lookup("MuxedAccount")], ["amount", xdr.lookup("Int64")]]);
// === xdr source ============================================================
//
// struct ClawbackClaimableBalanceOp
// {
// ClaimableBalanceID balanceID;
// };
//
// ===========================================================================
xdr.struct("ClawbackClaimableBalanceOp", [["balanceId", xdr.lookup("ClaimableBalanceId")]]);
// === xdr source ============================================================
//
// struct SetTrustLineFlagsOp
// {
// AccountID trustor;
// Asset asset;
//
// uint32 clearFlags; // which flags to clear
// uint32 setFlags; // which flags to set
// };
//
// ===========================================================================
xdr.struct("SetTrustLineFlagsOp", [["trustor", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["clearFlags", xdr.lookup("Uint32")], ["setFlags", xdr.lookup("Uint32")]]);
// === xdr source ============================================================
//
// const LIQUIDITY_POOL_FEE_V18 = 30;
//
// ===========================================================================
xdr.const("LIQUIDITY_POOL_FEE_V18", 30);
// === xdr source ============================================================
//
// struct LiquidityPoolDepositOp
// {
// PoolID liquidityPoolID;
// int64 maxAmountA; // maximum amount of first asset to deposit
// int64 maxAmountB; // maximum amount of second asset to deposit
// Price minPrice; // minimum depositA/depositB
// Price maxPrice; // maximum depositA/depositB
// };
//
// ===========================================================================
xdr.struct("LiquidityPoolDepositOp", [["liquidityPoolId", xdr.lookup("PoolId")], ["maxAmountA", xdr.lookup("Int64")], ["maxAmountB", xdr.lookup("Int64")], ["minPrice", xdr.lookup("Price")], ["maxPrice", xdr.lookup("Price")]]);
// === xdr source ============================================================
//
// struct LiquidityPoolWithdrawOp
// {
// PoolID liquidityPoolID;
// int64 amount; // amount of pool shares to withdraw
// int64 minAmountA; // minimum amount of first asset to withdraw
// int64 minAmountB; // minimum amount of second asset to withdraw
// };
//
// ===========================================================================
xdr.struct("LiquidityPoolWithdrawOp", [["liquidityPoolId", xdr.lookup("PoolId")], ["amount", xdr.lookup("Int64")], ["minAmountA", xdr.lookup("Int64")], ["minAmountB", xdr.lookup("Int64")]]);
// === xdr source ============================================================
//
// union switch (OperationType type)
// {
// case CREATE_ACCOUNT:
// CreateAccountOp createAccountOp;
// case PAYMENT:
// PaymentOp paymentOp;
// case PATH_PAYMENT_STRICT_RECEIVE:
// PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp;
// case MANAGE_SELL_OFFER:
// ManageSellOfferOp manageSellOfferOp;
// case CREATE_PASSIVE_SELL_OFFER:
// CreatePassiveSellOfferOp createPassiveSellOfferOp;
// case SET_OPTIONS:
// SetOptionsOp setOptionsOp;
// case CHANGE_TRUST:
// ChangeTrustOp changeTrustOp;
// case ALLOW_TRUST:
// AllowTrustOp allowTrustOp;
// case ACCOUNT_MERGE:
// MuxedAccount destination;
// case INFLATION:
// void;
// case MANAGE_DATA:
// ManageDataOp manageDataOp;
// case BUMP_SEQUENCE:
// BumpSequenceOp bumpSequenceOp;
// case MANAGE_BUY_OFFER:
// ManageBuyOfferOp manageBuyOfferOp;
// case PATH_PAYMENT_STRICT_SEND:
// PathPaymentStrictSendOp pathPaymentStrictSendOp;
// case CREATE_CLAIMABLE_BALANCE:
// CreateClaimableBalanceOp createClaimableBalanceOp;
// case CLAIM_CLAIMABLE_BALANCE:
// ClaimClaimableBalanceOp claimClaimableBalanceOp;
// case BEGIN_SPONSORING_FUTURE_RESERVES:
// BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp;
// case END_SPONSORING_FUTURE_RESERVES:
// void;
// case REVOKE_SPONSORSHIP:
// RevokeSponsorshipOp revokeSponsorshipOp;
// case CLAWBACK:
// ClawbackOp clawbackOp;
// case CLAWBACK_CLAIMABLE_BALANCE:
// ClawbackClaimableBalanceOp clawbackClaimableBalanceOp;
// case SET_TRUST_LINE_FLAGS:
// SetTrustLineFlagsOp setTrustLineFlagsOp;
// case LIQUIDITY_POOL_DEPOSIT:
// LiquidityPoolDepositOp liquidityPoolDepositOp;
// case LIQUIDITY_POOL_WITHDRAW:
// LiquidityPoolWithdrawOp liquidityPoolWithdrawOp;
// }
//
// ===========================================================================
xdr.union("OperationBody", {
switchOn: xdr.lookup("OperationType"),
switchName: "type",
switches: [["createAccount", "createAccountOp"], ["payment", "paymentOp"], ["pathPaymentStrictReceive", "pathPaymentStrictReceiveOp"], ["manageSellOffer", "manageSellOfferOp"], ["createPassiveSellOffer", "createPassiveSellOfferOp"], ["setOptions", "setOptionsOp"], ["changeTrust", "changeTrustOp"], ["allowTrust", "allowTrustOp"], ["accountMerge", "destination"], ["inflation", xdr.void()], ["manageData", "manageDataOp"], ["bumpSequence", "bumpSequenceOp"], ["manageBuyOffer", "manageBuyOfferOp"], ["pathPaymentStrictSend", "pathPaymentStrictSendOp"], ["createClaimableBalance", "createClaimableBalanceOp"], ["claimClaimableBalance", "claimClaimableBalanceOp"], ["beginSponsoringFutureReserves", "beginSponsoringFutureReservesOp"], ["endSponsoringFutureReserves", xdr.void()], ["revokeSponsorship", "revokeSponsorshipOp"], ["clawback", "clawbackOp"], ["clawbackClaimableBalance", "clawbackClaimableBalanceOp"], ["setTrustLineFlags", "setTrustLineFlagsOp"], ["liquidityPoolDeposit", "liquidityPoolDepositOp"], ["liquidityPoolWithdraw", "liquidityPoolWithdrawOp"]],
arms: {
createAccountOp: xdr.lookup("CreateAccountOp"),
paymentOp: xdr.lookup("PaymentOp"),
pathPaymentStrictReceiveOp: xdr.lookup("PathPaymentStrictReceiveOp"),
manageSellOfferOp: xdr.lookup("ManageSellOfferOp"),
createPassiveSellOfferOp: xdr.lookup("CreatePassiveSellOfferOp"),
setOptionsOp: xdr.lookup("SetOptionsOp"),
changeTrustOp: xdr.lookup("ChangeTrustOp"),
allowTrustOp: xdr.lookup("AllowTrustOp"),
destination: xdr.lookup("MuxedAccount"),
manageDataOp: xdr.lookup("ManageDataOp"),
bumpSequenceOp: xdr.lookup("BumpSequenceOp"),
manageBuyOfferOp: xdr.lookup("ManageBuyOfferOp"),
pathPaymentStrictSendOp: xdr.lookup("PathPaymentStrictSendOp"),
createClaimableBalanceOp: xdr.lookup("CreateClaimableBalanceOp"),
claimClaimableBalanceOp: xdr.lookup("ClaimClaimableBalanceOp"),
beginSponsoringFutureReservesOp: xdr.lookup("BeginSponsoringFutureReservesOp"),
revokeSponsorshipOp: xdr.lookup("RevokeSponsorshipOp"),
clawbackOp: xdr.lookup("ClawbackOp"),
clawbackClaimableBalanceOp: xdr.lookup("ClawbackClaimableBalanceOp"),
setTrustLineFlagsOp: xdr.lookup("SetTrustLineFlagsOp"),
liquidityPoolDepositOp: xdr.lookup("LiquidityPoolDepositOp"),
liquidityPoolWithdrawOp: xdr.lookup("LiquidityPoolWithdrawOp")
}
});
// === xdr source ============================================================
//
// struct Operation
// {
// // sourceAccount is the account used to run the operation
// // if not set, the runtime defaults to "sourceAccount" specified at
// // the transaction level
// MuxedAccount* sourceAccount;
//
// union switch (OperationType type)
// {
// case CREATE_ACCOUNT:
// CreateAccountOp createAccountOp;
// case PAYMENT:
// PaymentOp paymentOp;
// case PATH_PAYMENT_STRICT_RECEIVE:
// PathPaymentStrictReceiveOp pathPaymentStrictReceiveOp;
// case MANAGE_SELL_OFFER:
// ManageSellOfferOp manageSellOfferOp;
// case CREATE_PASSIVE_SELL_OFFER:
// CreatePassiveSellOfferOp createPassiveSellOfferOp;
// case SET_OPTIONS:
// SetOptionsOp setOptionsOp;
// case CHANGE_TRUST:
// ChangeTrustOp changeTrustOp;
// case ALLOW_TRUST:
// AllowTrustOp allowTrustOp;
// case ACCOUNT_MERGE:
// MuxedAccount destination;
// case INFLATION:
// void;
// case MANAGE_DATA:
// ManageDataOp manageDataOp;
// case BUMP_SEQUENCE:
// BumpSequenceOp bumpSequenceOp;
// case MANAGE_BUY_OFFER:
// ManageBuyOfferOp manageBuyOfferOp;
// case PATH_PAYMENT_STRICT_SEND:
// PathPaymentStrictSendOp pathPaymentStrictSendOp;
// case CREATE_CLAIMABLE_BALANCE:
// CreateClaimableBalanceOp createClaimableBalanceOp;
// case CLAIM_CLAIMABLE_BALANCE:
// ClaimClaimableBalanceOp claimClaimableBalanceOp;
// case BEGIN_SPONSORING_FUTURE_RESERVES:
// BeginSponsoringFutureReservesOp beginSponsoringFutureReservesOp;
// case END_SPONSORING_FUTURE_RESERVES:
// void;
// case REVOKE_SPONSORSHIP:
// RevokeSponsorshipOp revokeSponsorshipOp;
// case CLAWBACK:
// ClawbackOp clawbackOp;
// case CLAWBACK_CLAIMABLE_BALANCE:
// ClawbackClaimableBalanceOp clawbackClaimableBalanceOp;
// case SET_TRUST_LINE_FLAGS:
// SetTrustLineFlagsOp setTrustLineFlagsOp;
// case LIQUIDITY_POOL_DEPOSIT:
// LiquidityPoolDepositOp liquidityPoolDepositOp;
// case LIQUIDITY_POOL_WITHDRAW:
// LiquidityPoolWithdrawOp liquidityPoolWithdrawOp;
// }
// body;
// };
//
// ===========================================================================
xdr.struct("Operation", [["sourceAccount", xdr.option(xdr.lookup("MuxedAccount"))], ["body", xdr.lookup("OperationBody")]]);
// === xdr source ============================================================
//
// struct
// {
// AccountID sourceAccount;
// SequenceNumber seqNum;
// uint32 opNum;
// }
//
// ===========================================================================
xdr.struct("HashIdPreimageOperationId", [["sourceAccount", xdr.lookup("AccountId")], ["seqNum", xdr.lookup("SequenceNumber")], ["opNum", xdr.lookup("Uint32")]]);
// === xdr source ============================================================
//
// struct
// {
// AccountID sourceAccount;
// SequenceNumber seqNum;
// uint32 opNum;
// PoolID liquidityPoolID;
// Asset asset;
// }
//
// ===========================================================================
xdr.struct("HashIdPreimageRevokeId", [["sourceAccount", xdr.lookup("AccountId")], ["seqNum", xdr.lookup("SequenceNumber")], ["opNum", xdr.lookup("Uint32")], ["liquidityPoolId", xdr.lookup("PoolId")], ["asset", xdr.lookup("Asset")]]);
// === xdr source ============================================================
//
// union HashIDPreimage switch (EnvelopeType type)
// {
// case ENVELOPE_TYPE_OP_ID:
// struct
// {
// AccountID sourceAccount;
// SequenceNumber seqNum;
// uint32 opNum;
// } operationID;
// case ENVELOPE_TYPE_POOL_REVOKE_OP_ID:
// struct
// {
// AccountID sourceAccount;
// SequenceNumber seqNum;
// uint32 opNum;
// PoolID liquidityPoolID;
// Asset asset;
// } revokeID;
// };
//
// ===========================================================================
xdr.union("HashIdPreimage", {
switchOn: xdr.lookup("EnvelopeType"),
switchName: "type",
switches: [["envelopeTypeOpId", "operationId"], ["envelopeTypePoolRevokeOpId", "revokeId"]],
arms: {
operationId: xdr.lookup("HashIdPreimageOperationId"),
revokeId: xdr.lookup("HashIdPreimageRevokeId")
}
});
// === xdr source ============================================================
//
// enum MemoType
// {
// MEMO_NONE = 0,
// MEMO_TEXT = 1,
// MEMO_ID = 2,
// MEMO_HASH = 3,
// MEMO_RETURN = 4
// };
//
// ===========================================================================
xdr.enum("MemoType", {
memoNone: 0,
memoText: 1,
memoId: 2,
memoHash: 3,
memoReturn: 4
});
// === xdr source ============================================================
//
// union Memo switch (MemoType type)
// {
// case MEMO_NONE:
// void;
// case MEMO_TEXT:
// string text<28>;
// case MEMO_ID:
// uint64 id;
// case MEMO_HASH:
// Hash hash; // the hash of what to pull from the content server
// case MEMO_RETURN:
// Hash retHash; // the hash of the tx you are rejecting
// };
//
// ===========================================================================
xdr.union("Memo", {
switchOn: xdr.lookup("MemoType"),
switchName: "type",
switches: [["memoNone", xdr.void()], ["memoText", "text"], ["memoId", "id"], ["memoHash", "hash"], ["memoReturn", "retHash"]],
arms: {
text: xdr.string(28),
id: xdr.lookup("Uint64"),
hash: xdr.lookup("Hash"),
retHash: xdr.lookup("Hash")
}
});
// === xdr source ============================================================
//
// struct TimeBounds
// {
// TimePoint minTime;
// TimePoint maxTime; // 0 here means no maxTime
// };
//
// ===========================================================================
xdr.struct("TimeBounds", [["minTime", xdr.lookup("TimePoint")], ["maxTime", xdr.lookup("TimePoint")]]);
// === xdr source ============================================================
//
// struct LedgerBounds
// {
// uint32 minLedger;
// uint32 maxLedger; // 0 here means no maxLedger
// };
//
// ===========================================================================
xdr.struct("LedgerBounds", [["minLedger", xdr.lookup("Uint32")], ["maxLedger", xdr.lookup("Uint32")]]);
// === xdr source ============================================================
//
// struct PreconditionsV2
// {
// TimeBounds* timeBounds;
//
// // Transaction only valid for ledger numbers n such that
// // minLedger <= n < maxLedger (if maxLedger == 0, then
// // only minLedger is checked)
// LedgerBounds* ledgerBounds;
//
// // If NULL, only valid when sourceAccount's sequence number
// // is seqNum - 1. Otherwise, valid when sourceAccount's
// // sequence number n satisfies minSeqNum <= n < tx.seqNum.
// // Note that after execution the account's sequence number
// // is always raised to tx.seqNum, and a transaction is not
// // valid if tx.seqNum is too high to ensure replay protection.
// SequenceNumber* minSeqNum;
//
// // For the transaction to be valid, the current ledger time must
// // be at least minSeqAge greater than sourceAccount's seqTime.
// Duration minSeqAge;
//
// // For the transaction to be valid, the current ledger number
// // must be at least minSeqLedgerGap greater than sourceAccount's
// // seqLedger.
// uint32 minSeqLedgerGap;
//
// // For the transaction to be valid, there must be a signature
// // corresponding to every Signer in this array, even if the
// // signature is not otherwise required by the sourceAccount or
// // operations.
// SignerKey extraSigners<2>;
// };
//
// ===========================================================================
xdr.struct("PreconditionsV2", [["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["ledgerBounds", xdr.option(xdr.lookup("LedgerBounds"))], ["minSeqNum", xdr.option(xdr.lookup("SequenceNumber"))], ["minSeqAge", xdr.lookup("Duration")], ["minSeqLedgerGap", xdr.lookup("Uint32")], ["extraSigners", xdr.varArray(xdr.lookup("SignerKey"), 2)]]);
// === xdr source ============================================================
//
// enum PreconditionType
// {
// PRECOND_NONE = 0,
// PRECOND_TIME = 1,
// PRECOND_V2 = 2
// };
//
// ===========================================================================
xdr.enum("PreconditionType", {
precondNone: 0,
precondTime: 1,
precondV2: 2
});
// === xdr source ============================================================
//
// union Preconditions switch (PreconditionType type)
// {
// case PRECOND_NONE:
// void;
// case PRECOND_TIME:
// TimeBounds timeBounds;
// case PRECOND_V2:
// PreconditionsV2 v2;
// };
//
// ===========================================================================
xdr.union("Preconditions", {
switchOn: xdr.lookup("PreconditionType"),
switchName: "type",
switches: [["precondNone", xdr.void()], ["precondTime", "timeBounds"], ["precondV2", "v2"]],
arms: {
timeBounds: xdr.lookup("TimeBounds"),
v2: xdr.lookup("PreconditionsV2")
}
});
// === xdr source ============================================================
//
// const MAX_OPS_PER_TX = 100;
//
// ===========================================================================
xdr.const("MAX_OPS_PER_TX", 100);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("TransactionV0Ext", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// struct TransactionV0
// {
// uint256 sourceAccountEd25519;
// uint32 fee;
// SequenceNumber seqNum;
// TimeBounds* timeBounds;
// Memo memo;
// Operation operations<MAX_OPS_PER_TX>;
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("TransactionV0", [["sourceAccountEd25519", xdr.lookup("Uint256")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["timeBounds", xdr.option(xdr.lookup("TimeBounds"))], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))], ["ext", xdr.lookup("TransactionV0Ext")]]);
// === xdr source ============================================================
//
// struct TransactionV0Envelope
// {
// TransactionV0 tx;
// /* Each decorated signature is a signature over the SHA256 hash of
// * a TransactionSignaturePayload */
// DecoratedSignature signatures<20>;
// };
//
// ===========================================================================
xdr.struct("TransactionV0Envelope", [["tx", xdr.lookup("TransactionV0")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]);
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("TransactionExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// struct Transaction
// {
// // account used to run the transaction
// MuxedAccount sourceAccount;
//
// // the fee the sourceAccount will pay
// uint32 fee;
//
// // sequence number to consume in the account
// SequenceNumber seqNum;
//
// // validity conditions
// Preconditions cond;
//
// Memo memo;
//
// Operation operations<MAX_OPS_PER_TX>;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("Transaction", [["sourceAccount", xdr.lookup("MuxedAccount")], ["fee", xdr.lookup("Uint32")], ["seqNum", xdr.lookup("SequenceNumber")], ["cond", xdr.lookup("Preconditions")], ["memo", xdr.lookup("Memo")], ["operations", xdr.varArray(xdr.lookup("Operation"), xdr.lookup("MAX_OPS_PER_TX"))], ["ext", xdr.lookup("TransactionExt")]]);
// === xdr source ============================================================
//
// struct TransactionV1Envelope
// {
// Transaction tx;
// /* Each decorated signature is a signature over the SHA256 hash of
// * a TransactionSignaturePayload */
// DecoratedSignature signatures<20>;
// };
//
// ===========================================================================
xdr.struct("TransactionV1Envelope", [["tx", xdr.lookup("Transaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]);
// === xdr source ============================================================
//
// union switch (EnvelopeType type)
// {
// case ENVELOPE_TYPE_TX:
// TransactionV1Envelope v1;
// }
//
// ===========================================================================
xdr.union("FeeBumpTransactionInnerTx", {
switchOn: xdr.lookup("EnvelopeType"),
switchName: "type",
switches: [["envelopeTypeTx", "v1"]],
arms: {
v1: xdr.lookup("TransactionV1Envelope")
}
});
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("FeeBumpTransactionExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// struct FeeBumpTransaction
// {
// MuxedAccount feeSource;
// int64 fee;
// union switch (EnvelopeType type)
// {
// case ENVELOPE_TYPE_TX:
// TransactionV1Envelope v1;
// }
// innerTx;
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("FeeBumpTransaction", [["feeSource", xdr.lookup("MuxedAccount")], ["fee", xdr.lookup("Int64")], ["innerTx", xdr.lookup("FeeBumpTransactionInnerTx")], ["ext", xdr.lookup("FeeBumpTransactionExt")]]);
// === xdr source ============================================================
//
// struct FeeBumpTransactionEnvelope
// {
// FeeBumpTransaction tx;
// /* Each decorated signature is a signature over the SHA256 hash of
// * a TransactionSignaturePayload */
// DecoratedSignature signatures<20>;
// };
//
// ===========================================================================
xdr.struct("FeeBumpTransactionEnvelope", [["tx", xdr.lookup("FeeBumpTransaction")], ["signatures", xdr.varArray(xdr.lookup("DecoratedSignature"), 20)]]);
// === xdr source ============================================================
//
// union TransactionEnvelope switch (EnvelopeType type)
// {
// case ENVELOPE_TYPE_TX_V0:
// TransactionV0Envelope v0;
// case ENVELOPE_TYPE_TX:
// TransactionV1Envelope v1;
// case ENVELOPE_TYPE_TX_FEE_BUMP:
// FeeBumpTransactionEnvelope feeBump;
// };
//
// ===========================================================================
xdr.union("TransactionEnvelope", {
switchOn: xdr.lookup("EnvelopeType"),
switchName: "type",
switches: [["envelopeTypeTxV0", "v0"], ["envelopeTypeTx", "v1"], ["envelopeTypeTxFeeBump", "feeBump"]],
arms: {
v0: xdr.lookup("TransactionV0Envelope"),
v1: xdr.lookup("TransactionV1Envelope"),
feeBump: xdr.lookup("FeeBumpTransactionEnvelope")
}
});
// === xdr source ============================================================
//
// union switch (EnvelopeType type)
// {
// // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0
// case ENVELOPE_TYPE_TX:
// Transaction tx;
// case ENVELOPE_TYPE_TX_FEE_BUMP:
// FeeBumpTransaction feeBump;
// }
//
// ===========================================================================
xdr.union("TransactionSignaturePayloadTaggedTransaction", {
switchOn: xdr.lookup("EnvelopeType"),
switchName: "type",
switches: [["envelopeTypeTx", "tx"], ["envelopeTypeTxFeeBump", "feeBump"]],
arms: {
tx: xdr.lookup("Transaction"),
feeBump: xdr.lookup("FeeBumpTransaction")
}
});
// === xdr source ============================================================
//
// struct TransactionSignaturePayload
// {
// Hash networkId;
// union switch (EnvelopeType type)
// {
// // Backwards Compatibility: Use ENVELOPE_TYPE_TX to sign ENVELOPE_TYPE_TX_V0
// case ENVELOPE_TYPE_TX:
// Transaction tx;
// case ENVELOPE_TYPE_TX_FEE_BUMP:
// FeeBumpTransaction feeBump;
// }
// taggedTransaction;
// };
//
// ===========================================================================
xdr.struct("TransactionSignaturePayload", [["networkId", xdr.lookup("Hash")], ["taggedTransaction", xdr.lookup("TransactionSignaturePayloadTaggedTransaction")]]);
// === xdr source ============================================================
//
// enum ClaimAtomType
// {
// CLAIM_ATOM_TYPE_V0 = 0,
// CLAIM_ATOM_TYPE_ORDER_BOOK = 1,
// CLAIM_ATOM_TYPE_LIQUIDITY_POOL = 2
// };
//
// ===========================================================================
xdr.enum("ClaimAtomType", {
claimAtomTypeV0: 0,
claimAtomTypeOrderBook: 1,
claimAtomTypeLiquidityPool: 2
});
// === xdr source ============================================================
//
// struct ClaimOfferAtomV0
// {
// // emitted to identify the offer
// uint256 sellerEd25519; // Account that owns the offer
// int64 offerID;
//
// // amount and asset taken from the owner
// Asset assetSold;
// int64 amountSold;
//
// // amount and asset sent to the owner
// Asset assetBought;
// int64 amountBought;
// };
//
// ===========================================================================
xdr.struct("ClaimOfferAtomV0", [["sellerEd25519", xdr.lookup("Uint256")], ["offerId", xdr.lookup("Int64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]);
// === xdr source ============================================================
//
// struct ClaimOfferAtom
// {
// // emitted to identify the offer
// AccountID sellerID; // Account that owns the offer
// int64 offerID;
//
// // amount and asset taken from the owner
// Asset assetSold;
// int64 amountSold;
//
// // amount and asset sent to the owner
// Asset assetBought;
// int64 amountBought;
// };
//
// ===========================================================================
xdr.struct("ClaimOfferAtom", [["sellerId", xdr.lookup("AccountId")], ["offerId", xdr.lookup("Int64")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]);
// === xdr source ============================================================
//
// struct ClaimLiquidityAtom
// {
// PoolID liquidityPoolID;
//
// // amount and asset taken from the pool
// Asset assetSold;
// int64 amountSold;
//
// // amount and asset sent to the pool
// Asset assetBought;
// int64 amountBought;
// };
//
// ===========================================================================
xdr.struct("ClaimLiquidityAtom", [["liquidityPoolId", xdr.lookup("PoolId")], ["assetSold", xdr.lookup("Asset")], ["amountSold", xdr.lookup("Int64")], ["assetBought", xdr.lookup("Asset")], ["amountBought", xdr.lookup("Int64")]]);
// === xdr source ============================================================
//
// union ClaimAtom switch (ClaimAtomType type)
// {
// case CLAIM_ATOM_TYPE_V0:
// ClaimOfferAtomV0 v0;
// case CLAIM_ATOM_TYPE_ORDER_BOOK:
// ClaimOfferAtom orderBook;
// case CLAIM_ATOM_TYPE_LIQUIDITY_POOL:
// ClaimLiquidityAtom liquidityPool;
// };
//
// ===========================================================================
xdr.union("ClaimAtom", {
switchOn: xdr.lookup("ClaimAtomType"),
switchName: "type",
switches: [["claimAtomTypeV0", "v0"], ["claimAtomTypeOrderBook", "orderBook"], ["claimAtomTypeLiquidityPool", "liquidityPool"]],
arms: {
v0: xdr.lookup("ClaimOfferAtomV0"),
orderBook: xdr.lookup("ClaimOfferAtom"),
liquidityPool: xdr.lookup("ClaimLiquidityAtom")
}
});
// === xdr source ============================================================
//
// enum CreateAccountResultCode
// {
// // codes considered as "success" for the operation
// CREATE_ACCOUNT_SUCCESS = 0, // account was created
//
// // codes considered as "failure" for the operation
// CREATE_ACCOUNT_MALFORMED = -1, // invalid destination
// CREATE_ACCOUNT_UNDERFUNDED = -2, // not enough funds in source account
// CREATE_ACCOUNT_LOW_RESERVE =
// -3, // would create an account below the min reserve
// CREATE_ACCOUNT_ALREADY_EXIST = -4 // account already exists
// };
//
// ===========================================================================
xdr.enum("CreateAccountResultCode", {
createAccountSuccess: 0,
createAccountMalformed: -1,
createAccountUnderfunded: -2,
createAccountLowReserve: -3,
createAccountAlreadyExist: -4
});
// === xdr source ============================================================
//
// union CreateAccountResult switch (CreateAccountResultCode code)
// {
// case CREATE_ACCOUNT_SUCCESS:
// void;
// case CREATE_ACCOUNT_MALFORMED:
// case CREATE_ACCOUNT_UNDERFUNDED:
// case CREATE_ACCOUNT_LOW_RESERVE:
// case CREATE_ACCOUNT_ALREADY_EXIST:
// void;
// };
//
// ===========================================================================
xdr.union("CreateAccountResult", {
switchOn: xdr.lookup("CreateAccountResultCode"),
switchName: "code",
switches: [["createAccountSuccess", xdr.void()], ["createAccountMalformed", xdr.void()], ["createAccountUnderfunded", xdr.void()], ["createAccountLowReserve", xdr.void()], ["createAccountAlreadyExist", xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum PaymentResultCode
// {
// // codes considered as "success" for the operation
// PAYMENT_SUCCESS = 0, // payment successfully completed
//
// // codes considered as "failure" for the operation
// PAYMENT_MALFORMED = -1, // bad input
// PAYMENT_UNDERFUNDED = -2, // not enough funds in source account
// PAYMENT_SRC_NO_TRUST = -3, // no trust line on source account
// PAYMENT_SRC_NOT_AUTHORIZED = -4, // source not authorized to transfer
// PAYMENT_NO_DESTINATION = -5, // destination account does not exist
// PAYMENT_NO_TRUST = -6, // destination missing a trust line for asset
// PAYMENT_NOT_AUTHORIZED = -7, // destination not authorized to hold asset
// PAYMENT_LINE_FULL = -8, // destination would go above their limit
// PAYMENT_NO_ISSUER = -9 // missing issuer on asset
// };
//
// ===========================================================================
xdr.enum("PaymentResultCode", {
paymentSuccess: 0,
paymentMalformed: -1,
paymentUnderfunded: -2,
paymentSrcNoTrust: -3,
paymentSrcNotAuthorized: -4,
paymentNoDestination: -5,
paymentNoTrust: -6,
paymentNotAuthorized: -7,
paymentLineFull: -8,
paymentNoIssuer: -9
});
// === xdr source ============================================================
//
// union PaymentResult switch (PaymentResultCode code)
// {
// case PAYMENT_SUCCESS:
// void;
// case PAYMENT_MALFORMED:
// case PAYMENT_UNDERFUNDED:
// case PAYMENT_SRC_NO_TRUST:
// case PAYMENT_SRC_NOT_AUTHORIZED:
// case PAYMENT_NO_DESTINATION:
// case PAYMENT_NO_TRUST:
// case PAYMENT_NOT_AUTHORIZED:
// case PAYMENT_LINE_FULL:
// case PAYMENT_NO_ISSUER:
// void;
// };
//
// ===========================================================================
xdr.union("PaymentResult", {
switchOn: xdr.lookup("PaymentResultCode"),
switchName: "code",
switches: [["paymentSuccess", xdr.void()], ["paymentMalformed", xdr.void()], ["paymentUnderfunded", xdr.void()], ["paymentSrcNoTrust", xdr.void()], ["paymentSrcNotAuthorized", xdr.void()], ["paymentNoDestination", xdr.void()], ["paymentNoTrust", xdr.void()], ["paymentNotAuthorized", xdr.void()], ["paymentLineFull", xdr.void()], ["paymentNoIssuer", xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum PathPaymentStrictReceiveResultCode
// {
// // codes considered as "success" for the operation
// PATH_PAYMENT_STRICT_RECEIVE_SUCCESS = 0, // success
//
// // codes considered as "failure" for the operation
// PATH_PAYMENT_STRICT_RECEIVE_MALFORMED = -1, // bad input
// PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED =
// -2, // not enough funds in source account
// PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST =
// -3, // no trust line on source account
// PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED =
// -4, // source not authorized to transfer
// PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION =
// -5, // destination account does not exist
// PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST =
// -6, // dest missing a trust line for asset
// PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED =
// -7, // dest not authorized to hold asset
// PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL =
// -8, // dest would go above their limit
// PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER = -9, // missing issuer on one asset
// PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS =
// -10, // not enough offers to satisfy path
// PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF =
// -11, // would cross one of its own offers
// PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX = -12 // could not satisfy sendmax
// };
//
// ===========================================================================
xdr.enum("PathPaymentStrictReceiveResultCode", {
pathPaymentStrictReceiveSuccess: 0,
pathPaymentStrictReceiveMalformed: -1,
pathPaymentStrictReceiveUnderfunded: -2,
pathPaymentStrictReceiveSrcNoTrust: -3,
pathPaymentStrictReceiveSrcNotAuthorized: -4,
pathPaymentStrictReceiveNoDestination: -5,
pathPaymentStrictReceiveNoTrust: -6,
pathPaymentStrictReceiveNotAuthorized: -7,
pathPaymentStrictReceiveLineFull: -8,
pathPaymentStrictReceiveNoIssuer: -9,
pathPaymentStrictReceiveTooFewOffers: -10,
pathPaymentStrictReceiveOfferCrossSelf: -11,
pathPaymentStrictReceiveOverSendmax: -12
});
// === xdr source ============================================================
//
// struct SimplePaymentResult
// {
// AccountID destination;
// Asset asset;
// int64 amount;
// };
//
// ===========================================================================
xdr.struct("SimplePaymentResult", [["destination", xdr.lookup("AccountId")], ["asset", xdr.lookup("Asset")], ["amount", xdr.lookup("Int64")]]);
// === xdr source ============================================================
//
// struct
// {
// ClaimAtom offers<>;
// SimplePaymentResult last;
// }
//
// ===========================================================================
xdr.struct("PathPaymentStrictReceiveResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]);
// === xdr source ============================================================
//
// union PathPaymentStrictReceiveResult switch (
// PathPaymentStrictReceiveResultCode code)
// {
// case PATH_PAYMENT_STRICT_RECEIVE_SUCCESS:
// struct
// {
// ClaimAtom offers<>;
// SimplePaymentResult last;
// } success;
// case PATH_PAYMENT_STRICT_RECEIVE_MALFORMED:
// case PATH_PAYMENT_STRICT_RECEIVE_UNDERFUNDED:
// case PATH_PAYMENT_STRICT_RECEIVE_SRC_NO_TRUST:
// case PATH_PAYMENT_STRICT_RECEIVE_SRC_NOT_AUTHORIZED:
// case PATH_PAYMENT_STRICT_RECEIVE_NO_DESTINATION:
// case PATH_PAYMENT_STRICT_RECEIVE_NO_TRUST:
// case PATH_PAYMENT_STRICT_RECEIVE_NOT_AUTHORIZED:
// case PATH_PAYMENT_STRICT_RECEIVE_LINE_FULL:
// void;
// case PATH_PAYMENT_STRICT_RECEIVE_NO_ISSUER:
// Asset noIssuer; // the asset that caused the error
// case PATH_PAYMENT_STRICT_RECEIVE_TOO_FEW_OFFERS:
// case PATH_PAYMENT_STRICT_RECEIVE_OFFER_CROSS_SELF:
// case PATH_PAYMENT_STRICT_RECEIVE_OVER_SENDMAX:
// void;
// };
//
// ===========================================================================
xdr.union("PathPaymentStrictReceiveResult", {
switchOn: xdr.lookup("PathPaymentStrictReceiveResultCode"),
switchName: "code",
switches: [["pathPaymentStrictReceiveSuccess", "success"], ["pathPaymentStrictReceiveMalformed", xdr.void()], ["pathPaymentStrictReceiveUnderfunded", xdr.void()], ["pathPaymentStrictReceiveSrcNoTrust", xdr.void()], ["pathPaymentStrictReceiveSrcNotAuthorized", xdr.void()], ["pathPaymentStrictReceiveNoDestination", xdr.void()], ["pathPaymentStrictReceiveNoTrust", xdr.void()], ["pathPaymentStrictReceiveNotAuthorized", xdr.void()], ["pathPaymentStrictReceiveLineFull", xdr.void()], ["pathPaymentStrictReceiveNoIssuer", "noIssuer"], ["pathPaymentStrictReceiveTooFewOffers", xdr.void()], ["pathPaymentStrictReceiveOfferCrossSelf", xdr.void()], ["pathPaymentStrictReceiveOverSendmax", xdr.void()]],
arms: {
success: xdr.lookup("PathPaymentStrictReceiveResultSuccess"),
noIssuer: xdr.lookup("Asset")
}
});
// === xdr source ============================================================
//
// enum PathPaymentStrictSendResultCode
// {
// // codes considered as "success" for the operation
// PATH_PAYMENT_STRICT_SEND_SUCCESS = 0, // success
//
// // codes considered as "failure" for the operation
// PATH_PAYMENT_STRICT_SEND_MALFORMED = -1, // bad input
// PATH_PAYMENT_STRICT_SEND_UNDERFUNDED =
// -2, // not enough funds in source account
// PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST =
// -3, // no trust line on source account
// PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED =
// -4, // source not authorized to transfer
// PATH_PAYMENT_STRICT_SEND_NO_DESTINATION =
// -5, // destination account does not exist
// PATH_PAYMENT_STRICT_SEND_NO_TRUST =
// -6, // dest missing a trust line for asset
// PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED =
// -7, // dest not authorized to hold asset
// PATH_PAYMENT_STRICT_SEND_LINE_FULL = -8, // dest would go above their limit
// PATH_PAYMENT_STRICT_SEND_NO_ISSUER = -9, // missing issuer on one asset
// PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS =
// -10, // not enough offers to satisfy path
// PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF =
// -11, // would cross one of its own offers
// PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN = -12 // could not satisfy destMin
// };
//
// ===========================================================================
xdr.enum("PathPaymentStrictSendResultCode", {
pathPaymentStrictSendSuccess: 0,
pathPaymentStrictSendMalformed: -1,
pathPaymentStrictSendUnderfunded: -2,
pathPaymentStrictSendSrcNoTrust: -3,
pathPaymentStrictSendSrcNotAuthorized: -4,
pathPaymentStrictSendNoDestination: -5,
pathPaymentStrictSendNoTrust: -6,
pathPaymentStrictSendNotAuthorized: -7,
pathPaymentStrictSendLineFull: -8,
pathPaymentStrictSendNoIssuer: -9,
pathPaymentStrictSendTooFewOffers: -10,
pathPaymentStrictSendOfferCrossSelf: -11,
pathPaymentStrictSendUnderDestmin: -12
});
// === xdr source ============================================================
//
// struct
// {
// ClaimAtom offers<>;
// SimplePaymentResult last;
// }
//
// ===========================================================================
xdr.struct("PathPaymentStrictSendResultSuccess", [["offers", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["last", xdr.lookup("SimplePaymentResult")]]);
// === xdr source ============================================================
//
// union PathPaymentStrictSendResult switch (PathPaymentStrictSendResultCode code)
// {
// case PATH_PAYMENT_STRICT_SEND_SUCCESS:
// struct
// {
// ClaimAtom offers<>;
// SimplePaymentResult last;
// } success;
// case PATH_PAYMENT_STRICT_SEND_MALFORMED:
// case PATH_PAYMENT_STRICT_SEND_UNDERFUNDED:
// case PATH_PAYMENT_STRICT_SEND_SRC_NO_TRUST:
// case PATH_PAYMENT_STRICT_SEND_SRC_NOT_AUTHORIZED:
// case PATH_PAYMENT_STRICT_SEND_NO_DESTINATION:
// case PATH_PAYMENT_STRICT_SEND_NO_TRUST:
// case PATH_PAYMENT_STRICT_SEND_NOT_AUTHORIZED:
// case PATH_PAYMENT_STRICT_SEND_LINE_FULL:
// void;
// case PATH_PAYMENT_STRICT_SEND_NO_ISSUER:
// Asset noIssuer; // the asset that caused the error
// case PATH_PAYMENT_STRICT_SEND_TOO_FEW_OFFERS:
// case PATH_PAYMENT_STRICT_SEND_OFFER_CROSS_SELF:
// case PATH_PAYMENT_STRICT_SEND_UNDER_DESTMIN:
// void;
// };
//
// ===========================================================================
xdr.union("PathPaymentStrictSendResult", {
switchOn: xdr.lookup("PathPaymentStrictSendResultCode"),
switchName: "code",
switches: [["pathPaymentStrictSendSuccess", "success"], ["pathPaymentStrictSendMalformed", xdr.void()], ["pathPaymentStrictSendUnderfunded", xdr.void()], ["pathPaymentStrictSendSrcNoTrust", xdr.void()], ["pathPaymentStrictSendSrcNotAuthorized", xdr.void()], ["pathPaymentStrictSendNoDestination", xdr.void()], ["pathPaymentStrictSendNoTrust", xdr.void()], ["pathPaymentStrictSendNotAuthorized", xdr.void()], ["pathPaymentStrictSendLineFull", xdr.void()], ["pathPaymentStrictSendNoIssuer", "noIssuer"], ["pathPaymentStrictSendTooFewOffers", xdr.void()], ["pathPaymentStrictSendOfferCrossSelf", xdr.void()], ["pathPaymentStrictSendUnderDestmin", xdr.void()]],
arms: {
success: xdr.lookup("PathPaymentStrictSendResultSuccess"),
noIssuer: xdr.lookup("Asset")
}
});
// === xdr source ============================================================
//
// enum ManageSellOfferResultCode
// {
// // codes considered as "success" for the operation
// MANAGE_SELL_OFFER_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// MANAGE_SELL_OFFER_MALFORMED = -1, // generated offer would be invalid
// MANAGE_SELL_OFFER_SELL_NO_TRUST =
// -2, // no trust line for what we're selling
// MANAGE_SELL_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying
// MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell
// MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy
// MANAGE_SELL_OFFER_LINE_FULL = -6, // can't receive more of what it's buying
// MANAGE_SELL_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell
// MANAGE_SELL_OFFER_CROSS_SELF =
// -8, // would cross an offer from the same user
// MANAGE_SELL_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling
// MANAGE_SELL_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying
//
// // update errors
// MANAGE_SELL_OFFER_NOT_FOUND =
// -11, // offerID does not match an existing offer
//
// MANAGE_SELL_OFFER_LOW_RESERVE =
// -12 // not enough funds to create a new Offer
// };
//
// ===========================================================================
xdr.enum("ManageSellOfferResultCode", {
manageSellOfferSuccess: 0,
manageSellOfferMalformed: -1,
manageSellOfferSellNoTrust: -2,
manageSellOfferBuyNoTrust: -3,
manageSellOfferSellNotAuthorized: -4,
manageSellOfferBuyNotAuthorized: -5,
manageSellOfferLineFull: -6,
manageSellOfferUnderfunded: -7,
manageSellOfferCrossSelf: -8,
manageSellOfferSellNoIssuer: -9,
manageSellOfferBuyNoIssuer: -10,
manageSellOfferNotFound: -11,
manageSellOfferLowReserve: -12
});
// === xdr source ============================================================
//
// enum ManageOfferEffect
// {
// MANAGE_OFFER_CREATED = 0,
// MANAGE_OFFER_UPDATED = 1,
// MANAGE_OFFER_DELETED = 2
// };
//
// ===========================================================================
xdr.enum("ManageOfferEffect", {
manageOfferCreated: 0,
manageOfferUpdated: 1,
manageOfferDeleted: 2
});
// === xdr source ============================================================
//
// union switch (ManageOfferEffect effect)
// {
// case MANAGE_OFFER_CREATED:
// case MANAGE_OFFER_UPDATED:
// OfferEntry offer;
// case MANAGE_OFFER_DELETED:
// void;
// }
//
// ===========================================================================
xdr.union("ManageOfferSuccessResultOffer", {
switchOn: xdr.lookup("ManageOfferEffect"),
switchName: "effect",
switches: [["manageOfferCreated", "offer"], ["manageOfferUpdated", "offer"], ["manageOfferDeleted", xdr.void()]],
arms: {
offer: xdr.lookup("OfferEntry")
}
});
// === xdr source ============================================================
//
// struct ManageOfferSuccessResult
// {
// // offers that got claimed while creating this offer
// ClaimAtom offersClaimed<>;
//
// union switch (ManageOfferEffect effect)
// {
// case MANAGE_OFFER_CREATED:
// case MANAGE_OFFER_UPDATED:
// OfferEntry offer;
// case MANAGE_OFFER_DELETED:
// void;
// }
// offer;
// };
//
// ===========================================================================
xdr.struct("ManageOfferSuccessResult", [["offersClaimed", xdr.varArray(xdr.lookup("ClaimAtom"), 2147483647)], ["offer", xdr.lookup("ManageOfferSuccessResultOffer")]]);
// === xdr source ============================================================
//
// union ManageSellOfferResult switch (ManageSellOfferResultCode code)
// {
// case MANAGE_SELL_OFFER_SUCCESS:
// ManageOfferSuccessResult success;
// case MANAGE_SELL_OFFER_MALFORMED:
// case MANAGE_SELL_OFFER_SELL_NO_TRUST:
// case MANAGE_SELL_OFFER_BUY_NO_TRUST:
// case MANAGE_SELL_OFFER_SELL_NOT_AUTHORIZED:
// case MANAGE_SELL_OFFER_BUY_NOT_AUTHORIZED:
// case MANAGE_SELL_OFFER_LINE_FULL:
// case MANAGE_SELL_OFFER_UNDERFUNDED:
// case MANAGE_SELL_OFFER_CROSS_SELF:
// case MANAGE_SELL_OFFER_SELL_NO_ISSUER:
// case MANAGE_SELL_OFFER_BUY_NO_ISSUER:
// case MANAGE_SELL_OFFER_NOT_FOUND:
// case MANAGE_SELL_OFFER_LOW_RESERVE:
// void;
// };
//
// ===========================================================================
xdr.union("ManageSellOfferResult", {
switchOn: xdr.lookup("ManageSellOfferResultCode"),
switchName: "code",
switches: [["manageSellOfferSuccess", "success"], ["manageSellOfferMalformed", xdr.void()], ["manageSellOfferSellNoTrust", xdr.void()], ["manageSellOfferBuyNoTrust", xdr.void()], ["manageSellOfferSellNotAuthorized", xdr.void()], ["manageSellOfferBuyNotAuthorized", xdr.void()], ["manageSellOfferLineFull", xdr.void()], ["manageSellOfferUnderfunded", xdr.void()], ["manageSellOfferCrossSelf", xdr.void()], ["manageSellOfferSellNoIssuer", xdr.void()], ["manageSellOfferBuyNoIssuer", xdr.void()], ["manageSellOfferNotFound", xdr.void()], ["manageSellOfferLowReserve", xdr.void()]],
arms: {
success: xdr.lookup("ManageOfferSuccessResult")
}
});
// === xdr source ============================================================
//
// enum ManageBuyOfferResultCode
// {
// // codes considered as "success" for the operation
// MANAGE_BUY_OFFER_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// MANAGE_BUY_OFFER_MALFORMED = -1, // generated offer would be invalid
// MANAGE_BUY_OFFER_SELL_NO_TRUST = -2, // no trust line for what we're selling
// MANAGE_BUY_OFFER_BUY_NO_TRUST = -3, // no trust line for what we're buying
// MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED = -4, // not authorized to sell
// MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED = -5, // not authorized to buy
// MANAGE_BUY_OFFER_LINE_FULL = -6, // can't receive more of what it's buying
// MANAGE_BUY_OFFER_UNDERFUNDED = -7, // doesn't hold what it's trying to sell
// MANAGE_BUY_OFFER_CROSS_SELF = -8, // would cross an offer from the same user
// MANAGE_BUY_OFFER_SELL_NO_ISSUER = -9, // no issuer for what we're selling
// MANAGE_BUY_OFFER_BUY_NO_ISSUER = -10, // no issuer for what we're buying
//
// // update errors
// MANAGE_BUY_OFFER_NOT_FOUND =
// -11, // offerID does not match an existing offer
//
// MANAGE_BUY_OFFER_LOW_RESERVE = -12 // not enough funds to create a new Offer
// };
//
// ===========================================================================
xdr.enum("ManageBuyOfferResultCode", {
manageBuyOfferSuccess: 0,
manageBuyOfferMalformed: -1,
manageBuyOfferSellNoTrust: -2,
manageBuyOfferBuyNoTrust: -3,
manageBuyOfferSellNotAuthorized: -4,
manageBuyOfferBuyNotAuthorized: -5,
manageBuyOfferLineFull: -6,
manageBuyOfferUnderfunded: -7,
manageBuyOfferCrossSelf: -8,
manageBuyOfferSellNoIssuer: -9,
manageBuyOfferBuyNoIssuer: -10,
manageBuyOfferNotFound: -11,
manageBuyOfferLowReserve: -12
});
// === xdr source ============================================================
//
// union ManageBuyOfferResult switch (ManageBuyOfferResultCode code)
// {
// case MANAGE_BUY_OFFER_SUCCESS:
// ManageOfferSuccessResult success;
// case MANAGE_BUY_OFFER_MALFORMED:
// case MANAGE_BUY_OFFER_SELL_NO_TRUST:
// case MANAGE_BUY_OFFER_BUY_NO_TRUST:
// case MANAGE_BUY_OFFER_SELL_NOT_AUTHORIZED:
// case MANAGE_BUY_OFFER_BUY_NOT_AUTHORIZED:
// case MANAGE_BUY_OFFER_LINE_FULL:
// case MANAGE_BUY_OFFER_UNDERFUNDED:
// case MANAGE_BUY_OFFER_CROSS_SELF:
// case MANAGE_BUY_OFFER_SELL_NO_ISSUER:
// case MANAGE_BUY_OFFER_BUY_NO_ISSUER:
// case MANAGE_BUY_OFFER_NOT_FOUND:
// case MANAGE_BUY_OFFER_LOW_RESERVE:
// void;
// };
//
// ===========================================================================
xdr.union("ManageBuyOfferResult", {
switchOn: xdr.lookup("ManageBuyOfferResultCode"),
switchName: "code",
switches: [["manageBuyOfferSuccess", "success"], ["manageBuyOfferMalformed", xdr.void()], ["manageBuyOfferSellNoTrust", xdr.void()], ["manageBuyOfferBuyNoTrust", xdr.void()], ["manageBuyOfferSellNotAuthorized", xdr.void()], ["manageBuyOfferBuyNotAuthorized", xdr.void()], ["manageBuyOfferLineFull", xdr.void()], ["manageBuyOfferUnderfunded", xdr.void()], ["manageBuyOfferCrossSelf", xdr.void()], ["manageBuyOfferSellNoIssuer", xdr.void()], ["manageBuyOfferBuyNoIssuer", xdr.void()], ["manageBuyOfferNotFound", xdr.void()], ["manageBuyOfferLowReserve", xdr.void()]],
arms: {
success: xdr.lookup("ManageOfferSuccessResult")
}
});
// === xdr source ============================================================
//
// enum SetOptionsResultCode
// {
// // codes considered as "success" for the operation
// SET_OPTIONS_SUCCESS = 0,
// // codes considered as "failure" for the operation
// SET_OPTIONS_LOW_RESERVE = -1, // not enough funds to add a signer
// SET_OPTIONS_TOO_MANY_SIGNERS = -2, // max number of signers already reached
// SET_OPTIONS_BAD_FLAGS = -3, // invalid combination of clear/set flags
// SET_OPTIONS_INVALID_INFLATION = -4, // inflation account does not exist
// SET_OPTIONS_CANT_CHANGE = -5, // can no longer change this option
// SET_OPTIONS_UNKNOWN_FLAG = -6, // can't set an unknown flag
// SET_OPTIONS_THRESHOLD_OUT_OF_RANGE = -7, // bad value for weight/threshold
// SET_OPTIONS_BAD_SIGNER = -8, // signer cannot be masterkey
// SET_OPTIONS_INVALID_HOME_DOMAIN = -9, // malformed home domain
// SET_OPTIONS_AUTH_REVOCABLE_REQUIRED =
// -10 // auth revocable is required for clawback
// };
//
// ===========================================================================
xdr.enum("SetOptionsResultCode", {
setOptionsSuccess: 0,
setOptionsLowReserve: -1,
setOptionsTooManySigners: -2,
setOptionsBadFlags: -3,
setOptionsInvalidInflation: -4,
setOptionsCantChange: -5,
setOptionsUnknownFlag: -6,
setOptionsThresholdOutOfRange: -7,
setOptionsBadSigner: -8,
setOptionsInvalidHomeDomain: -9,
setOptionsAuthRevocableRequired: -10
});
// === xdr source ============================================================
//
// union SetOptionsResult switch (SetOptionsResultCode code)
// {
// case SET_OPTIONS_SUCCESS:
// void;
// case SET_OPTIONS_LOW_RESERVE:
// case SET_OPTIONS_TOO_MANY_SIGNERS:
// case SET_OPTIONS_BAD_FLAGS:
// case SET_OPTIONS_INVALID_INFLATION:
// case SET_OPTIONS_CANT_CHANGE:
// case SET_OPTIONS_UNKNOWN_FLAG:
// case SET_OPTIONS_THRESHOLD_OUT_OF_RANGE:
// case SET_OPTIONS_BAD_SIGNER:
// case SET_OPTIONS_INVALID_HOME_DOMAIN:
// case SET_OPTIONS_AUTH_REVOCABLE_REQUIRED:
// void;
// };
//
// ===========================================================================
xdr.union("SetOptionsResult", {
switchOn: xdr.lookup("SetOptionsResultCode"),
switchName: "code",
switches: [["setOptionsSuccess", xdr.void()], ["setOptionsLowReserve", xdr.void()], ["setOptionsTooManySigners", xdr.void()], ["setOptionsBadFlags", xdr.void()], ["setOptionsInvalidInflation", xdr.void()], ["setOptionsCantChange", xdr.void()], ["setOptionsUnknownFlag", xdr.void()], ["setOptionsThresholdOutOfRange", xdr.void()], ["setOptionsBadSigner", xdr.void()], ["setOptionsInvalidHomeDomain", xdr.void()], ["setOptionsAuthRevocableRequired", xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum ChangeTrustResultCode
// {
// // codes considered as "success" for the operation
// CHANGE_TRUST_SUCCESS = 0,
// // codes considered as "failure" for the operation
// CHANGE_TRUST_MALFORMED = -1, // bad input
// CHANGE_TRUST_NO_ISSUER = -2, // could not find issuer
// CHANGE_TRUST_INVALID_LIMIT = -3, // cannot drop limit below balance
// // cannot create with a limit of 0
// CHANGE_TRUST_LOW_RESERVE =
// -4, // not enough funds to create a new trust line,
// CHANGE_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed
// CHANGE_TRUST_TRUST_LINE_MISSING = -6, // Asset trustline is missing for pool
// CHANGE_TRUST_CANNOT_DELETE =
// -7, // Asset trustline is still referenced in a pool
// CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES =
// -8 // Asset trustline is deauthorized
// };
//
// ===========================================================================
xdr.enum("ChangeTrustResultCode", {
changeTrustSuccess: 0,
changeTrustMalformed: -1,
changeTrustNoIssuer: -2,
changeTrustInvalidLimit: -3,
changeTrustLowReserve: -4,
changeTrustSelfNotAllowed: -5,
changeTrustTrustLineMissing: -6,
changeTrustCannotDelete: -7,
changeTrustNotAuthMaintainLiabilities: -8
});
// === xdr source ============================================================
//
// union ChangeTrustResult switch (ChangeTrustResultCode code)
// {
// case CHANGE_TRUST_SUCCESS:
// void;
// case CHANGE_TRUST_MALFORMED:
// case CHANGE_TRUST_NO_ISSUER:
// case CHANGE_TRUST_INVALID_LIMIT:
// case CHANGE_TRUST_LOW_RESERVE:
// case CHANGE_TRUST_SELF_NOT_ALLOWED:
// case CHANGE_TRUST_TRUST_LINE_MISSING:
// case CHANGE_TRUST_CANNOT_DELETE:
// case CHANGE_TRUST_NOT_AUTH_MAINTAIN_LIABILITIES:
// void;
// };
//
// ===========================================================================
xdr.union("ChangeTrustResult", {
switchOn: xdr.lookup("ChangeTrustResultCode"),
switchName: "code",
switches: [["changeTrustSuccess", xdr.void()], ["changeTrustMalformed", xdr.void()], ["changeTrustNoIssuer", xdr.void()], ["changeTrustInvalidLimit", xdr.void()], ["changeTrustLowReserve", xdr.void()], ["changeTrustSelfNotAllowed", xdr.void()], ["changeTrustTrustLineMissing", xdr.void()], ["changeTrustCannotDelete", xdr.void()], ["changeTrustNotAuthMaintainLiabilities", xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum AllowTrustResultCode
// {
// // codes considered as "success" for the operation
// ALLOW_TRUST_SUCCESS = 0,
// // codes considered as "failure" for the operation
// ALLOW_TRUST_MALFORMED = -1, // asset is not ASSET_TYPE_ALPHANUM
// ALLOW_TRUST_NO_TRUST_LINE = -2, // trustor does not have a trustline
// // source account does not require trust
// ALLOW_TRUST_TRUST_NOT_REQUIRED = -3,
// ALLOW_TRUST_CANT_REVOKE = -4, // source account can't revoke trust,
// ALLOW_TRUST_SELF_NOT_ALLOWED = -5, // trusting self is not allowed
// ALLOW_TRUST_LOW_RESERVE = -6 // claimable balances can't be created
// // on revoke due to low reserves
// };
//
// ===========================================================================
xdr.enum("AllowTrustResultCode", {
allowTrustSuccess: 0,
allowTrustMalformed: -1,
allowTrustNoTrustLine: -2,
allowTrustTrustNotRequired: -3,
allowTrustCantRevoke: -4,
allowTrustSelfNotAllowed: -5,
allowTrustLowReserve: -6
});
// === xdr source ============================================================
//
// union AllowTrustResult switch (AllowTrustResultCode code)
// {
// case ALLOW_TRUST_SUCCESS:
// void;
// case ALLOW_TRUST_MALFORMED:
// case ALLOW_TRUST_NO_TRUST_LINE:
// case ALLOW_TRUST_TRUST_NOT_REQUIRED:
// case ALLOW_TRUST_CANT_REVOKE:
// case ALLOW_TRUST_SELF_NOT_ALLOWED:
// case ALLOW_TRUST_LOW_RESERVE:
// void;
// };
//
// ===========================================================================
xdr.union("AllowTrustResult", {
switchOn: xdr.lookup("AllowTrustResultCode"),
switchName: "code",
switches: [["allowTrustSuccess", xdr.void()], ["allowTrustMalformed", xdr.void()], ["allowTrustNoTrustLine", xdr.void()], ["allowTrustTrustNotRequired", xdr.void()], ["allowTrustCantRevoke", xdr.void()], ["allowTrustSelfNotAllowed", xdr.void()], ["allowTrustLowReserve", xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum AccountMergeResultCode
// {
// // codes considered as "success" for the operation
// ACCOUNT_MERGE_SUCCESS = 0,
// // codes considered as "failure" for the operation
// ACCOUNT_MERGE_MALFORMED = -1, // can't merge onto itself
// ACCOUNT_MERGE_NO_ACCOUNT = -2, // destination does not exist
// ACCOUNT_MERGE_IMMUTABLE_SET = -3, // source account has AUTH_IMMUTABLE set
// ACCOUNT_MERGE_HAS_SUB_ENTRIES = -4, // account has trust lines/offers
// ACCOUNT_MERGE_SEQNUM_TOO_FAR = -5, // sequence number is over max allowed
// ACCOUNT_MERGE_DEST_FULL = -6, // can't add source balance to
// // destination balance
// ACCOUNT_MERGE_IS_SPONSOR = -7 // can't merge account that is a sponsor
// };
//
// ===========================================================================
xdr.enum("AccountMergeResultCode", {
accountMergeSuccess: 0,
accountMergeMalformed: -1,
accountMergeNoAccount: -2,
accountMergeImmutableSet: -3,
accountMergeHasSubEntries: -4,
accountMergeSeqnumTooFar: -5,
accountMergeDestFull: -6,
accountMergeIsSponsor: -7
});
// === xdr source ============================================================
//
// union AccountMergeResult switch (AccountMergeResultCode code)
// {
// case ACCOUNT_MERGE_SUCCESS:
// int64 sourceAccountBalance; // how much got transferred from source account
// case ACCOUNT_MERGE_MALFORMED:
// case ACCOUNT_MERGE_NO_ACCOUNT:
// case ACCOUNT_MERGE_IMMUTABLE_SET:
// case ACCOUNT_MERGE_HAS_SUB_ENTRIES:
// case ACCOUNT_MERGE_SEQNUM_TOO_FAR:
// case ACCOUNT_MERGE_DEST_FULL:
// case ACCOUNT_MERGE_IS_SPONSOR:
// void;
// };
//
// ===========================================================================
xdr.union("AccountMergeResult", {
switchOn: xdr.lookup("AccountMergeResultCode"),
switchName: "code",
switches: [["accountMergeSuccess", "sourceAccountBalance"], ["accountMergeMalformed", xdr.void()], ["accountMergeNoAccount", xdr.void()], ["accountMergeImmutableSet", xdr.void()], ["accountMergeHasSubEntries", xdr.void()], ["accountMergeSeqnumTooFar", xdr.void()], ["accountMergeDestFull", xdr.void()], ["accountMergeIsSponsor", xdr.void()]],
arms: {
sourceAccountBalance: xdr.lookup("Int64")
}
});
// === xdr source ============================================================
//
// enum InflationResultCode
// {
// // codes considered as "success" for the operation
// INFLATION_SUCCESS = 0,
// // codes considered as "failure" for the operation
// INFLATION_NOT_TIME = -1
// };
//
// ===========================================================================
xdr.enum("InflationResultCode", {
inflationSuccess: 0,
inflationNotTime: -1
});
// === xdr source ============================================================
//
// struct InflationPayout // or use PaymentResultAtom to limit types?
// {
// AccountID destination;
// int64 amount;
// };
//
// ===========================================================================
xdr.struct("InflationPayout", [["destination", xdr.lookup("AccountId")], ["amount", xdr.lookup("Int64")]]);
// === xdr source ============================================================
//
// union InflationResult switch (InflationResultCode code)
// {
// case INFLATION_SUCCESS:
// InflationPayout payouts<>;
// case INFLATION_NOT_TIME:
// void;
// };
//
// ===========================================================================
xdr.union("InflationResult", {
switchOn: xdr.lookup("InflationResultCode"),
switchName: "code",
switches: [["inflationSuccess", "payouts"], ["inflationNotTime", xdr.void()]],
arms: {
payouts: xdr.varArray(xdr.lookup("InflationPayout"), 2147483647)
}
});
// === xdr source ============================================================
//
// enum ManageDataResultCode
// {
// // codes considered as "success" for the operation
// MANAGE_DATA_SUCCESS = 0,
// // codes considered as "failure" for the operation
// MANAGE_DATA_NOT_SUPPORTED_YET =
// -1, // The network hasn't moved to this protocol change yet
// MANAGE_DATA_NAME_NOT_FOUND =
// -2, // Trying to remove a Data Entry that isn't there
// MANAGE_DATA_LOW_RESERVE = -3, // not enough funds to create a new Data Entry
// MANAGE_DATA_INVALID_NAME = -4 // Name not a valid string
// };
//
// ===========================================================================
xdr.enum("ManageDataResultCode", {
manageDataSuccess: 0,
manageDataNotSupportedYet: -1,
manageDataNameNotFound: -2,
manageDataLowReserve: -3,
manageDataInvalidName: -4
});
// === xdr source ============================================================
//
// union ManageDataResult switch (ManageDataResultCode code)
// {
// case MANAGE_DATA_SUCCESS:
// void;
// case MANAGE_DATA_NOT_SUPPORTED_YET:
// case MANAGE_DATA_NAME_NOT_FOUND:
// case MANAGE_DATA_LOW_RESERVE:
// case MANAGE_DATA_INVALID_NAME:
// void;
// };
//
// ===========================================================================
xdr.union("ManageDataResult", {
switchOn: xdr.lookup("ManageDataResultCode"),
switchName: "code",
switches: [["manageDataSuccess", xdr.void()], ["manageDataNotSupportedYet", xdr.void()], ["manageDataNameNotFound", xdr.void()], ["manageDataLowReserve", xdr.void()], ["manageDataInvalidName", xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum BumpSequenceResultCode
// {
// // codes considered as "success" for the operation
// BUMP_SEQUENCE_SUCCESS = 0,
// // codes considered as "failure" for the operation
// BUMP_SEQUENCE_BAD_SEQ = -1 // `bumpTo` is not within bounds
// };
//
// ===========================================================================
xdr.enum("BumpSequenceResultCode", {
bumpSequenceSuccess: 0,
bumpSequenceBadSeq: -1
});
// === xdr source ============================================================
//
// union BumpSequenceResult switch (BumpSequenceResultCode code)
// {
// case BUMP_SEQUENCE_SUCCESS:
// void;
// case BUMP_SEQUENCE_BAD_SEQ:
// void;
// };
//
// ===========================================================================
xdr.union("BumpSequenceResult", {
switchOn: xdr.lookup("BumpSequenceResultCode"),
switchName: "code",
switches: [["bumpSequenceSuccess", xdr.void()], ["bumpSequenceBadSeq", xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum CreateClaimableBalanceResultCode
// {
// CREATE_CLAIMABLE_BALANCE_SUCCESS = 0,
// CREATE_CLAIMABLE_BALANCE_MALFORMED = -1,
// CREATE_CLAIMABLE_BALANCE_LOW_RESERVE = -2,
// CREATE_CLAIMABLE_BALANCE_NO_TRUST = -3,
// CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -4,
// CREATE_CLAIMABLE_BALANCE_UNDERFUNDED = -5
// };
//
// ===========================================================================
xdr.enum("CreateClaimableBalanceResultCode", {
createClaimableBalanceSuccess: 0,
createClaimableBalanceMalformed: -1,
createClaimableBalanceLowReserve: -2,
createClaimableBalanceNoTrust: -3,
createClaimableBalanceNotAuthorized: -4,
createClaimableBalanceUnderfunded: -5
});
// === xdr source ============================================================
//
// union CreateClaimableBalanceResult switch (
// CreateClaimableBalanceResultCode code)
// {
// case CREATE_CLAIMABLE_BALANCE_SUCCESS:
// ClaimableBalanceID balanceID;
// case CREATE_CLAIMABLE_BALANCE_MALFORMED:
// case CREATE_CLAIMABLE_BALANCE_LOW_RESERVE:
// case CREATE_CLAIMABLE_BALANCE_NO_TRUST:
// case CREATE_CLAIMABLE_BALANCE_NOT_AUTHORIZED:
// case CREATE_CLAIMABLE_BALANCE_UNDERFUNDED:
// void;
// };
//
// ===========================================================================
xdr.union("CreateClaimableBalanceResult", {
switchOn: xdr.lookup("CreateClaimableBalanceResultCode"),
switchName: "code",
switches: [["createClaimableBalanceSuccess", "balanceId"], ["createClaimableBalanceMalformed", xdr.void()], ["createClaimableBalanceLowReserve", xdr.void()], ["createClaimableBalanceNoTrust", xdr.void()], ["createClaimableBalanceNotAuthorized", xdr.void()], ["createClaimableBalanceUnderfunded", xdr.void()]],
arms: {
balanceId: xdr.lookup("ClaimableBalanceId")
}
});
// === xdr source ============================================================
//
// enum ClaimClaimableBalanceResultCode
// {
// CLAIM_CLAIMABLE_BALANCE_SUCCESS = 0,
// CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1,
// CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM = -2,
// CLAIM_CLAIMABLE_BALANCE_LINE_FULL = -3,
// CLAIM_CLAIMABLE_BALANCE_NO_TRUST = -4,
// CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED = -5
// };
//
// ===========================================================================
xdr.enum("ClaimClaimableBalanceResultCode", {
claimClaimableBalanceSuccess: 0,
claimClaimableBalanceDoesNotExist: -1,
claimClaimableBalanceCannotClaim: -2,
claimClaimableBalanceLineFull: -3,
claimClaimableBalanceNoTrust: -4,
claimClaimableBalanceNotAuthorized: -5
});
// === xdr source ============================================================
//
// union ClaimClaimableBalanceResult switch (ClaimClaimableBalanceResultCode code)
// {
// case CLAIM_CLAIMABLE_BALANCE_SUCCESS:
// void;
// case CLAIM_CLAIMABLE_BALANCE_DOES_NOT_EXIST:
// case CLAIM_CLAIMABLE_BALANCE_CANNOT_CLAIM:
// case CLAIM_CLAIMABLE_BALANCE_LINE_FULL:
// case CLAIM_CLAIMABLE_BALANCE_NO_TRUST:
// case CLAIM_CLAIMABLE_BALANCE_NOT_AUTHORIZED:
// void;
// };
//
// ===========================================================================
xdr.union("ClaimClaimableBalanceResult", {
switchOn: xdr.lookup("ClaimClaimableBalanceResultCode"),
switchName: "code",
switches: [["claimClaimableBalanceSuccess", xdr.void()], ["claimClaimableBalanceDoesNotExist", xdr.void()], ["claimClaimableBalanceCannotClaim", xdr.void()], ["claimClaimableBalanceLineFull", xdr.void()], ["claimClaimableBalanceNoTrust", xdr.void()], ["claimClaimableBalanceNotAuthorized", xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum BeginSponsoringFutureReservesResultCode
// {
// // codes considered as "success" for the operation
// BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED = -1,
// BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED = -2,
// BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE = -3
// };
//
// ===========================================================================
xdr.enum("BeginSponsoringFutureReservesResultCode", {
beginSponsoringFutureReservesSuccess: 0,
beginSponsoringFutureReservesMalformed: -1,
beginSponsoringFutureReservesAlreadySponsored: -2,
beginSponsoringFutureReservesRecursive: -3
});
// === xdr source ============================================================
//
// union BeginSponsoringFutureReservesResult switch (
// BeginSponsoringFutureReservesResultCode code)
// {
// case BEGIN_SPONSORING_FUTURE_RESERVES_SUCCESS:
// void;
// case BEGIN_SPONSORING_FUTURE_RESERVES_MALFORMED:
// case BEGIN_SPONSORING_FUTURE_RESERVES_ALREADY_SPONSORED:
// case BEGIN_SPONSORING_FUTURE_RESERVES_RECURSIVE:
// void;
// };
//
// ===========================================================================
xdr.union("BeginSponsoringFutureReservesResult", {
switchOn: xdr.lookup("BeginSponsoringFutureReservesResultCode"),
switchName: "code",
switches: [["beginSponsoringFutureReservesSuccess", xdr.void()], ["beginSponsoringFutureReservesMalformed", xdr.void()], ["beginSponsoringFutureReservesAlreadySponsored", xdr.void()], ["beginSponsoringFutureReservesRecursive", xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum EndSponsoringFutureReservesResultCode
// {
// // codes considered as "success" for the operation
// END_SPONSORING_FUTURE_RESERVES_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED = -1
// };
//
// ===========================================================================
xdr.enum("EndSponsoringFutureReservesResultCode", {
endSponsoringFutureReservesSuccess: 0,
endSponsoringFutureReservesNotSponsored: -1
});
// === xdr source ============================================================
//
// union EndSponsoringFutureReservesResult switch (
// EndSponsoringFutureReservesResultCode code)
// {
// case END_SPONSORING_FUTURE_RESERVES_SUCCESS:
// void;
// case END_SPONSORING_FUTURE_RESERVES_NOT_SPONSORED:
// void;
// };
//
// ===========================================================================
xdr.union("EndSponsoringFutureReservesResult", {
switchOn: xdr.lookup("EndSponsoringFutureReservesResultCode"),
switchName: "code",
switches: [["endSponsoringFutureReservesSuccess", xdr.void()], ["endSponsoringFutureReservesNotSponsored", xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum RevokeSponsorshipResultCode
// {
// // codes considered as "success" for the operation
// REVOKE_SPONSORSHIP_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// REVOKE_SPONSORSHIP_DOES_NOT_EXIST = -1,
// REVOKE_SPONSORSHIP_NOT_SPONSOR = -2,
// REVOKE_SPONSORSHIP_LOW_RESERVE = -3,
// REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE = -4,
// REVOKE_SPONSORSHIP_MALFORMED = -5
// };
//
// ===========================================================================
xdr.enum("RevokeSponsorshipResultCode", {
revokeSponsorshipSuccess: 0,
revokeSponsorshipDoesNotExist: -1,
revokeSponsorshipNotSponsor: -2,
revokeSponsorshipLowReserve: -3,
revokeSponsorshipOnlyTransferable: -4,
revokeSponsorshipMalformed: -5
});
// === xdr source ============================================================
//
// union RevokeSponsorshipResult switch (RevokeSponsorshipResultCode code)
// {
// case REVOKE_SPONSORSHIP_SUCCESS:
// void;
// case REVOKE_SPONSORSHIP_DOES_NOT_EXIST:
// case REVOKE_SPONSORSHIP_NOT_SPONSOR:
// case REVOKE_SPONSORSHIP_LOW_RESERVE:
// case REVOKE_SPONSORSHIP_ONLY_TRANSFERABLE:
// case REVOKE_SPONSORSHIP_MALFORMED:
// void;
// };
//
// ===========================================================================
xdr.union("RevokeSponsorshipResult", {
switchOn: xdr.lookup("RevokeSponsorshipResultCode"),
switchName: "code",
switches: [["revokeSponsorshipSuccess", xdr.void()], ["revokeSponsorshipDoesNotExist", xdr.void()], ["revokeSponsorshipNotSponsor", xdr.void()], ["revokeSponsorshipLowReserve", xdr.void()], ["revokeSponsorshipOnlyTransferable", xdr.void()], ["revokeSponsorshipMalformed", xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum ClawbackResultCode
// {
// // codes considered as "success" for the operation
// CLAWBACK_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// CLAWBACK_MALFORMED = -1,
// CLAWBACK_NOT_CLAWBACK_ENABLED = -2,
// CLAWBACK_NO_TRUST = -3,
// CLAWBACK_UNDERFUNDED = -4
// };
//
// ===========================================================================
xdr.enum("ClawbackResultCode", {
clawbackSuccess: 0,
clawbackMalformed: -1,
clawbackNotClawbackEnabled: -2,
clawbackNoTrust: -3,
clawbackUnderfunded: -4
});
// === xdr source ============================================================
//
// union ClawbackResult switch (ClawbackResultCode code)
// {
// case CLAWBACK_SUCCESS:
// void;
// case CLAWBACK_MALFORMED:
// case CLAWBACK_NOT_CLAWBACK_ENABLED:
// case CLAWBACK_NO_TRUST:
// case CLAWBACK_UNDERFUNDED:
// void;
// };
//
// ===========================================================================
xdr.union("ClawbackResult", {
switchOn: xdr.lookup("ClawbackResultCode"),
switchName: "code",
switches: [["clawbackSuccess", xdr.void()], ["clawbackMalformed", xdr.void()], ["clawbackNotClawbackEnabled", xdr.void()], ["clawbackNoTrust", xdr.void()], ["clawbackUnderfunded", xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum ClawbackClaimableBalanceResultCode
// {
// // codes considered as "success" for the operation
// CLAWBACK_CLAIMABLE_BALANCE_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST = -1,
// CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER = -2,
// CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED = -3
// };
//
// ===========================================================================
xdr.enum("ClawbackClaimableBalanceResultCode", {
clawbackClaimableBalanceSuccess: 0,
clawbackClaimableBalanceDoesNotExist: -1,
clawbackClaimableBalanceNotIssuer: -2,
clawbackClaimableBalanceNotClawbackEnabled: -3
});
// === xdr source ============================================================
//
// union ClawbackClaimableBalanceResult switch (
// ClawbackClaimableBalanceResultCode code)
// {
// case CLAWBACK_CLAIMABLE_BALANCE_SUCCESS:
// void;
// case CLAWBACK_CLAIMABLE_BALANCE_DOES_NOT_EXIST:
// case CLAWBACK_CLAIMABLE_BALANCE_NOT_ISSUER:
// case CLAWBACK_CLAIMABLE_BALANCE_NOT_CLAWBACK_ENABLED:
// void;
// };
//
// ===========================================================================
xdr.union("ClawbackClaimableBalanceResult", {
switchOn: xdr.lookup("ClawbackClaimableBalanceResultCode"),
switchName: "code",
switches: [["clawbackClaimableBalanceSuccess", xdr.void()], ["clawbackClaimableBalanceDoesNotExist", xdr.void()], ["clawbackClaimableBalanceNotIssuer", xdr.void()], ["clawbackClaimableBalanceNotClawbackEnabled", xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum SetTrustLineFlagsResultCode
// {
// // codes considered as "success" for the operation
// SET_TRUST_LINE_FLAGS_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// SET_TRUST_LINE_FLAGS_MALFORMED = -1,
// SET_TRUST_LINE_FLAGS_NO_TRUST_LINE = -2,
// SET_TRUST_LINE_FLAGS_CANT_REVOKE = -3,
// SET_TRUST_LINE_FLAGS_INVALID_STATE = -4,
// SET_TRUST_LINE_FLAGS_LOW_RESERVE = -5 // claimable balances can't be created
// // on revoke due to low reserves
// };
//
// ===========================================================================
xdr.enum("SetTrustLineFlagsResultCode", {
setTrustLineFlagsSuccess: 0,
setTrustLineFlagsMalformed: -1,
setTrustLineFlagsNoTrustLine: -2,
setTrustLineFlagsCantRevoke: -3,
setTrustLineFlagsInvalidState: -4,
setTrustLineFlagsLowReserve: -5
});
// === xdr source ============================================================
//
// union SetTrustLineFlagsResult switch (SetTrustLineFlagsResultCode code)
// {
// case SET_TRUST_LINE_FLAGS_SUCCESS:
// void;
// case SET_TRUST_LINE_FLAGS_MALFORMED:
// case SET_TRUST_LINE_FLAGS_NO_TRUST_LINE:
// case SET_TRUST_LINE_FLAGS_CANT_REVOKE:
// case SET_TRUST_LINE_FLAGS_INVALID_STATE:
// case SET_TRUST_LINE_FLAGS_LOW_RESERVE:
// void;
// };
//
// ===========================================================================
xdr.union("SetTrustLineFlagsResult", {
switchOn: xdr.lookup("SetTrustLineFlagsResultCode"),
switchName: "code",
switches: [["setTrustLineFlagsSuccess", xdr.void()], ["setTrustLineFlagsMalformed", xdr.void()], ["setTrustLineFlagsNoTrustLine", xdr.void()], ["setTrustLineFlagsCantRevoke", xdr.void()], ["setTrustLineFlagsInvalidState", xdr.void()], ["setTrustLineFlagsLowReserve", xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum LiquidityPoolDepositResultCode
// {
// // codes considered as "success" for the operation
// LIQUIDITY_POOL_DEPOSIT_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// LIQUIDITY_POOL_DEPOSIT_MALFORMED = -1, // bad input
// LIQUIDITY_POOL_DEPOSIT_NO_TRUST = -2, // no trust line for one of the
// // assets
// LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED = -3, // not authorized for one of the
// // assets
// LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED = -4, // not enough balance for one of
// // the assets
// LIQUIDITY_POOL_DEPOSIT_LINE_FULL = -5, // pool share trust line doesn't
// // have sufficient limit
// LIQUIDITY_POOL_DEPOSIT_BAD_PRICE = -6, // deposit price outside bounds
// LIQUIDITY_POOL_DEPOSIT_POOL_FULL = -7 // pool reserves are full
// };
//
// ===========================================================================
xdr.enum("LiquidityPoolDepositResultCode", {
liquidityPoolDepositSuccess: 0,
liquidityPoolDepositMalformed: -1,
liquidityPoolDepositNoTrust: -2,
liquidityPoolDepositNotAuthorized: -3,
liquidityPoolDepositUnderfunded: -4,
liquidityPoolDepositLineFull: -5,
liquidityPoolDepositBadPrice: -6,
liquidityPoolDepositPoolFull: -7
});
// === xdr source ============================================================
//
// union LiquidityPoolDepositResult switch (LiquidityPoolDepositResultCode code)
// {
// case LIQUIDITY_POOL_DEPOSIT_SUCCESS:
// void;
// case LIQUIDITY_POOL_DEPOSIT_MALFORMED:
// case LIQUIDITY_POOL_DEPOSIT_NO_TRUST:
// case LIQUIDITY_POOL_DEPOSIT_NOT_AUTHORIZED:
// case LIQUIDITY_POOL_DEPOSIT_UNDERFUNDED:
// case LIQUIDITY_POOL_DEPOSIT_LINE_FULL:
// case LIQUIDITY_POOL_DEPOSIT_BAD_PRICE:
// case LIQUIDITY_POOL_DEPOSIT_POOL_FULL:
// void;
// };
//
// ===========================================================================
xdr.union("LiquidityPoolDepositResult", {
switchOn: xdr.lookup("LiquidityPoolDepositResultCode"),
switchName: "code",
switches: [["liquidityPoolDepositSuccess", xdr.void()], ["liquidityPoolDepositMalformed", xdr.void()], ["liquidityPoolDepositNoTrust", xdr.void()], ["liquidityPoolDepositNotAuthorized", xdr.void()], ["liquidityPoolDepositUnderfunded", xdr.void()], ["liquidityPoolDepositLineFull", xdr.void()], ["liquidityPoolDepositBadPrice", xdr.void()], ["liquidityPoolDepositPoolFull", xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum LiquidityPoolWithdrawResultCode
// {
// // codes considered as "success" for the operation
// LIQUIDITY_POOL_WITHDRAW_SUCCESS = 0,
//
// // codes considered as "failure" for the operation
// LIQUIDITY_POOL_WITHDRAW_MALFORMED = -1, // bad input
// LIQUIDITY_POOL_WITHDRAW_NO_TRUST = -2, // no trust line for one of the
// // assets
// LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED = -3, // not enough balance of the
// // pool share
// LIQUIDITY_POOL_WITHDRAW_LINE_FULL = -4, // would go above limit for one
// // of the assets
// LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM = -5 // didn't withdraw enough
// };
//
// ===========================================================================
xdr.enum("LiquidityPoolWithdrawResultCode", {
liquidityPoolWithdrawSuccess: 0,
liquidityPoolWithdrawMalformed: -1,
liquidityPoolWithdrawNoTrust: -2,
liquidityPoolWithdrawUnderfunded: -3,
liquidityPoolWithdrawLineFull: -4,
liquidityPoolWithdrawUnderMinimum: -5
});
// === xdr source ============================================================
//
// union LiquidityPoolWithdrawResult switch (LiquidityPoolWithdrawResultCode code)
// {
// case LIQUIDITY_POOL_WITHDRAW_SUCCESS:
// void;
// case LIQUIDITY_POOL_WITHDRAW_MALFORMED:
// case LIQUIDITY_POOL_WITHDRAW_NO_TRUST:
// case LIQUIDITY_POOL_WITHDRAW_UNDERFUNDED:
// case LIQUIDITY_POOL_WITHDRAW_LINE_FULL:
// case LIQUIDITY_POOL_WITHDRAW_UNDER_MINIMUM:
// void;
// };
//
// ===========================================================================
xdr.union("LiquidityPoolWithdrawResult", {
switchOn: xdr.lookup("LiquidityPoolWithdrawResultCode"),
switchName: "code",
switches: [["liquidityPoolWithdrawSuccess", xdr.void()], ["liquidityPoolWithdrawMalformed", xdr.void()], ["liquidityPoolWithdrawNoTrust", xdr.void()], ["liquidityPoolWithdrawUnderfunded", xdr.void()], ["liquidityPoolWithdrawLineFull", xdr.void()], ["liquidityPoolWithdrawUnderMinimum", xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum OperationResultCode
// {
// opINNER = 0, // inner object result is valid
//
// opBAD_AUTH = -1, // too few valid signatures / wrong network
// opNO_ACCOUNT = -2, // source account was not found
// opNOT_SUPPORTED = -3, // operation not supported at this time
// opTOO_MANY_SUBENTRIES = -4, // max number of subentries already reached
// opEXCEEDED_WORK_LIMIT = -5, // operation did too much work
// opTOO_MANY_SPONSORING = -6 // account is sponsoring too many entries
// };
//
// ===========================================================================
xdr.enum("OperationResultCode", {
opInner: 0,
opBadAuth: -1,
opNoAccount: -2,
opNotSupported: -3,
opTooManySubentries: -4,
opExceededWorkLimit: -5,
opTooManySponsoring: -6
});
// === xdr source ============================================================
//
// union switch (OperationType type)
// {
// case CREATE_ACCOUNT:
// CreateAccountResult createAccountResult;
// case PAYMENT:
// PaymentResult paymentResult;
// case PATH_PAYMENT_STRICT_RECEIVE:
// PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult;
// case MANAGE_SELL_OFFER:
// ManageSellOfferResult manageSellOfferResult;
// case CREATE_PASSIVE_SELL_OFFER:
// ManageSellOfferResult createPassiveSellOfferResult;
// case SET_OPTIONS:
// SetOptionsResult setOptionsResult;
// case CHANGE_TRUST:
// ChangeTrustResult changeTrustResult;
// case ALLOW_TRUST:
// AllowTrustResult allowTrustResult;
// case ACCOUNT_MERGE:
// AccountMergeResult accountMergeResult;
// case INFLATION:
// InflationResult inflationResult;
// case MANAGE_DATA:
// ManageDataResult manageDataResult;
// case BUMP_SEQUENCE:
// BumpSequenceResult bumpSeqResult;
// case MANAGE_BUY_OFFER:
// ManageBuyOfferResult manageBuyOfferResult;
// case PATH_PAYMENT_STRICT_SEND:
// PathPaymentStrictSendResult pathPaymentStrictSendResult;
// case CREATE_CLAIMABLE_BALANCE:
// CreateClaimableBalanceResult createClaimableBalanceResult;
// case CLAIM_CLAIMABLE_BALANCE:
// ClaimClaimableBalanceResult claimClaimableBalanceResult;
// case BEGIN_SPONSORING_FUTURE_RESERVES:
// BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult;
// case END_SPONSORING_FUTURE_RESERVES:
// EndSponsoringFutureReservesResult endSponsoringFutureReservesResult;
// case REVOKE_SPONSORSHIP:
// RevokeSponsorshipResult revokeSponsorshipResult;
// case CLAWBACK:
// ClawbackResult clawbackResult;
// case CLAWBACK_CLAIMABLE_BALANCE:
// ClawbackClaimableBalanceResult clawbackClaimableBalanceResult;
// case SET_TRUST_LINE_FLAGS:
// SetTrustLineFlagsResult setTrustLineFlagsResult;
// case LIQUIDITY_POOL_DEPOSIT:
// LiquidityPoolDepositResult liquidityPoolDepositResult;
// case LIQUIDITY_POOL_WITHDRAW:
// LiquidityPoolWithdrawResult liquidityPoolWithdrawResult;
// }
//
// ===========================================================================
xdr.union("OperationResultTr", {
switchOn: xdr.lookup("OperationType"),
switchName: "type",
switches: [["createAccount", "createAccountResult"], ["payment", "paymentResult"], ["pathPaymentStrictReceive", "pathPaymentStrictReceiveResult"], ["manageSellOffer", "manageSellOfferResult"], ["createPassiveSellOffer", "createPassiveSellOfferResult"], ["setOptions", "setOptionsResult"], ["changeTrust", "changeTrustResult"], ["allowTrust", "allowTrustResult"], ["accountMerge", "accountMergeResult"], ["inflation", "inflationResult"], ["manageData", "manageDataResult"], ["bumpSequence", "bumpSeqResult"], ["manageBuyOffer", "manageBuyOfferResult"], ["pathPaymentStrictSend", "pathPaymentStrictSendResult"], ["createClaimableBalance", "createClaimableBalanceResult"], ["claimClaimableBalance", "claimClaimableBalanceResult"], ["beginSponsoringFutureReserves", "beginSponsoringFutureReservesResult"], ["endSponsoringFutureReserves", "endSponsoringFutureReservesResult"], ["revokeSponsorship", "revokeSponsorshipResult"], ["clawback", "clawbackResult"], ["clawbackClaimableBalance", "clawbackClaimableBalanceResult"], ["setTrustLineFlags", "setTrustLineFlagsResult"], ["liquidityPoolDeposit", "liquidityPoolDepositResult"], ["liquidityPoolWithdraw", "liquidityPoolWithdrawResult"]],
arms: {
createAccountResult: xdr.lookup("CreateAccountResult"),
paymentResult: xdr.lookup("PaymentResult"),
pathPaymentStrictReceiveResult: xdr.lookup("PathPaymentStrictReceiveResult"),
manageSellOfferResult: xdr.lookup("ManageSellOfferResult"),
createPassiveSellOfferResult: xdr.lookup("ManageSellOfferResult"),
setOptionsResult: xdr.lookup("SetOptionsResult"),
changeTrustResult: xdr.lookup("ChangeTrustResult"),
allowTrustResult: xdr.lookup("AllowTrustResult"),
accountMergeResult: xdr.lookup("AccountMergeResult"),
inflationResult: xdr.lookup("InflationResult"),
manageDataResult: xdr.lookup("ManageDataResult"),
bumpSeqResult: xdr.lookup("BumpSequenceResult"),
manageBuyOfferResult: xdr.lookup("ManageBuyOfferResult"),
pathPaymentStrictSendResult: xdr.lookup("PathPaymentStrictSendResult"),
createClaimableBalanceResult: xdr.lookup("CreateClaimableBalanceResult"),
claimClaimableBalanceResult: xdr.lookup("ClaimClaimableBalanceResult"),
beginSponsoringFutureReservesResult: xdr.lookup("BeginSponsoringFutureReservesResult"),
endSponsoringFutureReservesResult: xdr.lookup("EndSponsoringFutureReservesResult"),
revokeSponsorshipResult: xdr.lookup("RevokeSponsorshipResult"),
clawbackResult: xdr.lookup("ClawbackResult"),
clawbackClaimableBalanceResult: xdr.lookup("ClawbackClaimableBalanceResult"),
setTrustLineFlagsResult: xdr.lookup("SetTrustLineFlagsResult"),
liquidityPoolDepositResult: xdr.lookup("LiquidityPoolDepositResult"),
liquidityPoolWithdrawResult: xdr.lookup("LiquidityPoolWithdrawResult")
}
});
// === xdr source ============================================================
//
// union OperationResult switch (OperationResultCode code)
// {
// case opINNER:
// union switch (OperationType type)
// {
// case CREATE_ACCOUNT:
// CreateAccountResult createAccountResult;
// case PAYMENT:
// PaymentResult paymentResult;
// case PATH_PAYMENT_STRICT_RECEIVE:
// PathPaymentStrictReceiveResult pathPaymentStrictReceiveResult;
// case MANAGE_SELL_OFFER:
// ManageSellOfferResult manageSellOfferResult;
// case CREATE_PASSIVE_SELL_OFFER:
// ManageSellOfferResult createPassiveSellOfferResult;
// case SET_OPTIONS:
// SetOptionsResult setOptionsResult;
// case CHANGE_TRUST:
// ChangeTrustResult changeTrustResult;
// case ALLOW_TRUST:
// AllowTrustResult allowTrustResult;
// case ACCOUNT_MERGE:
// AccountMergeResult accountMergeResult;
// case INFLATION:
// InflationResult inflationResult;
// case MANAGE_DATA:
// ManageDataResult manageDataResult;
// case BUMP_SEQUENCE:
// BumpSequenceResult bumpSeqResult;
// case MANAGE_BUY_OFFER:
// ManageBuyOfferResult manageBuyOfferResult;
// case PATH_PAYMENT_STRICT_SEND:
// PathPaymentStrictSendResult pathPaymentStrictSendResult;
// case CREATE_CLAIMABLE_BALANCE:
// CreateClaimableBalanceResult createClaimableBalanceResult;
// case CLAIM_CLAIMABLE_BALANCE:
// ClaimClaimableBalanceResult claimClaimableBalanceResult;
// case BEGIN_SPONSORING_FUTURE_RESERVES:
// BeginSponsoringFutureReservesResult beginSponsoringFutureReservesResult;
// case END_SPONSORING_FUTURE_RESERVES:
// EndSponsoringFutureReservesResult endSponsoringFutureReservesResult;
// case REVOKE_SPONSORSHIP:
// RevokeSponsorshipResult revokeSponsorshipResult;
// case CLAWBACK:
// ClawbackResult clawbackResult;
// case CLAWBACK_CLAIMABLE_BALANCE:
// ClawbackClaimableBalanceResult clawbackClaimableBalanceResult;
// case SET_TRUST_LINE_FLAGS:
// SetTrustLineFlagsResult setTrustLineFlagsResult;
// case LIQUIDITY_POOL_DEPOSIT:
// LiquidityPoolDepositResult liquidityPoolDepositResult;
// case LIQUIDITY_POOL_WITHDRAW:
// LiquidityPoolWithdrawResult liquidityPoolWithdrawResult;
// }
// tr;
// case opBAD_AUTH:
// case opNO_ACCOUNT:
// case opNOT_SUPPORTED:
// case opTOO_MANY_SUBENTRIES:
// case opEXCEEDED_WORK_LIMIT:
// case opTOO_MANY_SPONSORING:
// void;
// };
//
// ===========================================================================
xdr.union("OperationResult", {
switchOn: xdr.lookup("OperationResultCode"),
switchName: "code",
switches: [["opInner", "tr"], ["opBadAuth", xdr.void()], ["opNoAccount", xdr.void()], ["opNotSupported", xdr.void()], ["opTooManySubentries", xdr.void()], ["opExceededWorkLimit", xdr.void()], ["opTooManySponsoring", xdr.void()]],
arms: {
tr: xdr.lookup("OperationResultTr")
}
});
// === xdr source ============================================================
//
// enum TransactionResultCode
// {
// txFEE_BUMP_INNER_SUCCESS = 1, // fee bump inner transaction succeeded
// txSUCCESS = 0, // all operations succeeded
//
// txFAILED = -1, // one of the operations failed (none were applied)
//
// txTOO_EARLY = -2, // ledger closeTime before minTime
// txTOO_LATE = -3, // ledger closeTime after maxTime
// txMISSING_OPERATION = -4, // no operation was specified
// txBAD_SEQ = -5, // sequence number does not match source account
//
// txBAD_AUTH = -6, // too few valid signatures / wrong network
// txINSUFFICIENT_BALANCE = -7, // fee would bring account below reserve
// txNO_ACCOUNT = -8, // source account not found
// txINSUFFICIENT_FEE = -9, // fee is too small
// txBAD_AUTH_EXTRA = -10, // unused signatures attached to transaction
// txINTERNAL_ERROR = -11, // an unknown error occurred
//
// txNOT_SUPPORTED = -12, // transaction type not supported
// txFEE_BUMP_INNER_FAILED = -13, // fee bump inner transaction failed
// txBAD_SPONSORSHIP = -14, // sponsorship not confirmed
// txBAD_MIN_SEQ_AGE_OR_GAP =
// -15, // minSeqAge or minSeqLedgerGap conditions not met
// txMALFORMED = -16 // precondition is invalid
// };
//
// ===========================================================================
xdr.enum("TransactionResultCode", {
txFeeBumpInnerSuccess: 1,
txSuccess: 0,
txFailed: -1,
txTooEarly: -2,
txTooLate: -3,
txMissingOperation: -4,
txBadSeq: -5,
txBadAuth: -6,
txInsufficientBalance: -7,
txNoAccount: -8,
txInsufficientFee: -9,
txBadAuthExtra: -10,
txInternalError: -11,
txNotSupported: -12,
txFeeBumpInnerFailed: -13,
txBadSponsorship: -14,
txBadMinSeqAgeOrGap: -15,
txMalformed: -16
});
// === xdr source ============================================================
//
// union switch (TransactionResultCode code)
// {
// // txFEE_BUMP_INNER_SUCCESS is not included
// case txSUCCESS:
// case txFAILED:
// OperationResult results<>;
// case txTOO_EARLY:
// case txTOO_LATE:
// case txMISSING_OPERATION:
// case txBAD_SEQ:
// case txBAD_AUTH:
// case txINSUFFICIENT_BALANCE:
// case txNO_ACCOUNT:
// case txINSUFFICIENT_FEE:
// case txBAD_AUTH_EXTRA:
// case txINTERNAL_ERROR:
// case txNOT_SUPPORTED:
// // txFEE_BUMP_INNER_FAILED is not included
// case txBAD_SPONSORSHIP:
// case txBAD_MIN_SEQ_AGE_OR_GAP:
// case txMALFORMED:
// void;
// }
//
// ===========================================================================
xdr.union("InnerTransactionResultResult", {
switchOn: xdr.lookup("TransactionResultCode"),
switchName: "code",
switches: [["txSuccess", "results"], ["txFailed", "results"], ["txTooEarly", xdr.void()], ["txTooLate", xdr.void()], ["txMissingOperation", xdr.void()], ["txBadSeq", xdr.void()], ["txBadAuth", xdr.void()], ["txInsufficientBalance", xdr.void()], ["txNoAccount", xdr.void()], ["txInsufficientFee", xdr.void()], ["txBadAuthExtra", xdr.void()], ["txInternalError", xdr.void()], ["txNotSupported", xdr.void()], ["txBadSponsorship", xdr.void()], ["txBadMinSeqAgeOrGap", xdr.void()], ["txMalformed", xdr.void()]],
arms: {
results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647)
}
});
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("InnerTransactionResultExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// struct InnerTransactionResult
// {
// // Always 0. Here for binary compatibility.
// int64 feeCharged;
//
// union switch (TransactionResultCode code)
// {
// // txFEE_BUMP_INNER_SUCCESS is not included
// case txSUCCESS:
// case txFAILED:
// OperationResult results<>;
// case txTOO_EARLY:
// case txTOO_LATE:
// case txMISSING_OPERATION:
// case txBAD_SEQ:
// case txBAD_AUTH:
// case txINSUFFICIENT_BALANCE:
// case txNO_ACCOUNT:
// case txINSUFFICIENT_FEE:
// case txBAD_AUTH_EXTRA:
// case txINTERNAL_ERROR:
// case txNOT_SUPPORTED:
// // txFEE_BUMP_INNER_FAILED is not included
// case txBAD_SPONSORSHIP:
// case txBAD_MIN_SEQ_AGE_OR_GAP:
// case txMALFORMED:
// void;
// }
// result;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("InnerTransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("InnerTransactionResultResult")], ["ext", xdr.lookup("InnerTransactionResultExt")]]);
// === xdr source ============================================================
//
// struct InnerTransactionResultPair
// {
// Hash transactionHash; // hash of the inner transaction
// InnerTransactionResult result; // result for the inner transaction
// };
//
// ===========================================================================
xdr.struct("InnerTransactionResultPair", [["transactionHash", xdr.lookup("Hash")], ["result", xdr.lookup("InnerTransactionResult")]]);
// === xdr source ============================================================
//
// union switch (TransactionResultCode code)
// {
// case txFEE_BUMP_INNER_SUCCESS:
// case txFEE_BUMP_INNER_FAILED:
// InnerTransactionResultPair innerResultPair;
// case txSUCCESS:
// case txFAILED:
// OperationResult results<>;
// case txTOO_EARLY:
// case txTOO_LATE:
// case txMISSING_OPERATION:
// case txBAD_SEQ:
// case txBAD_AUTH:
// case txINSUFFICIENT_BALANCE:
// case txNO_ACCOUNT:
// case txINSUFFICIENT_FEE:
// case txBAD_AUTH_EXTRA:
// case txINTERNAL_ERROR:
// case txNOT_SUPPORTED:
// // case txFEE_BUMP_INNER_FAILED: handled above
// case txBAD_SPONSORSHIP:
// case txBAD_MIN_SEQ_AGE_OR_GAP:
// case txMALFORMED:
// void;
// }
//
// ===========================================================================
xdr.union("TransactionResultResult", {
switchOn: xdr.lookup("TransactionResultCode"),
switchName: "code",
switches: [["txFeeBumpInnerSuccess", "innerResultPair"], ["txFeeBumpInnerFailed", "innerResultPair"], ["txSuccess", "results"], ["txFailed", "results"], ["txTooEarly", xdr.void()], ["txTooLate", xdr.void()], ["txMissingOperation", xdr.void()], ["txBadSeq", xdr.void()], ["txBadAuth", xdr.void()], ["txInsufficientBalance", xdr.void()], ["txNoAccount", xdr.void()], ["txInsufficientFee", xdr.void()], ["txBadAuthExtra", xdr.void()], ["txInternalError", xdr.void()], ["txNotSupported", xdr.void()], ["txBadSponsorship", xdr.void()], ["txBadMinSeqAgeOrGap", xdr.void()], ["txMalformed", xdr.void()]],
arms: {
innerResultPair: xdr.lookup("InnerTransactionResultPair"),
results: xdr.varArray(xdr.lookup("OperationResult"), 2147483647)
}
});
// === xdr source ============================================================
//
// union switch (int v)
// {
// case 0:
// void;
// }
//
// ===========================================================================
xdr.union("TransactionResultExt", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// struct TransactionResult
// {
// int64 feeCharged; // actual fee charged for the transaction
//
// union switch (TransactionResultCode code)
// {
// case txFEE_BUMP_INNER_SUCCESS:
// case txFEE_BUMP_INNER_FAILED:
// InnerTransactionResultPair innerResultPair;
// case txSUCCESS:
// case txFAILED:
// OperationResult results<>;
// case txTOO_EARLY:
// case txTOO_LATE:
// case txMISSING_OPERATION:
// case txBAD_SEQ:
// case txBAD_AUTH:
// case txINSUFFICIENT_BALANCE:
// case txNO_ACCOUNT:
// case txINSUFFICIENT_FEE:
// case txBAD_AUTH_EXTRA:
// case txINTERNAL_ERROR:
// case txNOT_SUPPORTED:
// // case txFEE_BUMP_INNER_FAILED: handled above
// case txBAD_SPONSORSHIP:
// case txBAD_MIN_SEQ_AGE_OR_GAP:
// case txMALFORMED:
// void;
// }
// result;
//
// // reserved for future use
// union switch (int v)
// {
// case 0:
// void;
// }
// ext;
// };
//
// ===========================================================================
xdr.struct("TransactionResult", [["feeCharged", xdr.lookup("Int64")], ["result", xdr.lookup("TransactionResultResult")], ["ext", xdr.lookup("TransactionResultExt")]]);
// === xdr source ============================================================
//
// typedef opaque Hash[32];
//
// ===========================================================================
xdr.typedef("Hash", xdr.opaque(32));
// === xdr source ============================================================
//
// typedef opaque uint256[32];
//
// ===========================================================================
xdr.typedef("Uint256", xdr.opaque(32));
// === xdr source ============================================================
//
// typedef unsigned int uint32;
//
// ===========================================================================
xdr.typedef("Uint32", xdr.uint());
// === xdr source ============================================================
//
// typedef int int32;
//
// ===========================================================================
xdr.typedef("Int32", xdr.int());
// === xdr source ============================================================
//
// typedef unsigned hyper uint64;
//
// ===========================================================================
xdr.typedef("Uint64", xdr.uhyper());
// === xdr source ============================================================
//
// typedef hyper int64;
//
// ===========================================================================
xdr.typedef("Int64", xdr.hyper());
// === xdr source ============================================================
//
// union ExtensionPoint switch (int v)
// {
// case 0:
// void;
// };
//
// ===========================================================================
xdr.union("ExtensionPoint", {
switchOn: xdr.int(),
switchName: "v",
switches: [[0, xdr.void()]],
arms: {}
});
// === xdr source ============================================================
//
// enum CryptoKeyType
// {
// KEY_TYPE_ED25519 = 0,
// KEY_TYPE_PRE_AUTH_TX = 1,
// KEY_TYPE_HASH_X = 2,
// KEY_TYPE_ED25519_SIGNED_PAYLOAD = 3,
// // MUXED enum values for supported type are derived from the enum values
// // above by ORing them with 0x100
// KEY_TYPE_MUXED_ED25519 = 0x100
// };
//
// ===========================================================================
xdr.enum("CryptoKeyType", {
keyTypeEd25519: 0,
keyTypePreAuthTx: 1,
keyTypeHashX: 2,
keyTypeEd25519SignedPayload: 3,
keyTypeMuxedEd25519: 256
});
// === xdr source ============================================================
//
// enum PublicKeyType
// {
// PUBLIC_KEY_TYPE_ED25519 = KEY_TYPE_ED25519
// };
//
// ===========================================================================
xdr.enum("PublicKeyType", {
publicKeyTypeEd25519: 0
});
// === xdr source ============================================================
//
// enum SignerKeyType
// {
// SIGNER_KEY_TYPE_ED25519 = KEY_TYPE_ED25519,
// SIGNER_KEY_TYPE_PRE_AUTH_TX = KEY_TYPE_PRE_AUTH_TX,
// SIGNER_KEY_TYPE_HASH_X = KEY_TYPE_HASH_X,
// SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD = KEY_TYPE_ED25519_SIGNED_PAYLOAD
// };
//
// ===========================================================================
xdr.enum("SignerKeyType", {
signerKeyTypeEd25519: 0,
signerKeyTypePreAuthTx: 1,
signerKeyTypeHashX: 2,
signerKeyTypeEd25519SignedPayload: 3
});
// === xdr source ============================================================
//
// union PublicKey switch (PublicKeyType type)
// {
// case PUBLIC_KEY_TYPE_ED25519:
// uint256 ed25519;
// };
//
// ===========================================================================
xdr.union("PublicKey", {
switchOn: xdr.lookup("PublicKeyType"),
switchName: "type",
switches: [["publicKeyTypeEd25519", "ed25519"]],
arms: {
ed25519: xdr.lookup("Uint256")
}
});
// === xdr source ============================================================
//
// struct
// {
// /* Public key that must sign the payload. */
// uint256 ed25519;
// /* Payload to be raw signed by ed25519. */
// opaque payload<64>;
// }
//
// ===========================================================================
xdr.struct("SignerKeyEd25519SignedPayload", [["ed25519", xdr.lookup("Uint256")], ["payload", xdr.varOpaque(64)]]);
// === xdr source ============================================================
//
// union SignerKey switch (SignerKeyType type)
// {
// case SIGNER_KEY_TYPE_ED25519:
// uint256 ed25519;
// case SIGNER_KEY_TYPE_PRE_AUTH_TX:
// /* SHA-256 Hash of TransactionSignaturePayload structure */
// uint256 preAuthTx;
// case SIGNER_KEY_TYPE_HASH_X:
// /* Hash of random 256 bit preimage X */
// uint256 hashX;
// case SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD:
// struct
// {
// /* Public key that must sign the payload. */
// uint256 ed25519;
// /* Payload to be raw signed by ed25519. */
// opaque payload<64>;
// } ed25519SignedPayload;
// };
//
// ===========================================================================
xdr.union("SignerKey", {
switchOn: xdr.lookup("SignerKeyType"),
switchName: "type",
switches: [["signerKeyTypeEd25519", "ed25519"], ["signerKeyTypePreAuthTx", "preAuthTx"], ["signerKeyTypeHashX", "hashX"], ["signerKeyTypeEd25519SignedPayload", "ed25519SignedPayload"]],
arms: {
ed25519: xdr.lookup("Uint256"),
preAuthTx: xdr.lookup("Uint256"),
hashX: xdr.lookup("Uint256"),
ed25519SignedPayload: xdr.lookup("SignerKeyEd25519SignedPayload")
}
});
// === xdr source ============================================================
//
// typedef opaque Signature<64>;
//
// ===========================================================================
xdr.typedef("Signature", xdr.varOpaque(64));
// === xdr source ============================================================
//
// typedef opaque SignatureHint[4];
//
// ===========================================================================
xdr.typedef("SignatureHint", xdr.opaque(4));
// === xdr source ============================================================
//
// typedef PublicKey NodeID;
//
// ===========================================================================
xdr.typedef("NodeId", xdr.lookup("PublicKey"));
// === xdr source ============================================================
//
// struct Curve25519Secret
// {
// opaque key[32];
// };
//
// ===========================================================================
xdr.struct("Curve25519Secret", [["key", xdr.opaque(32)]]);
// === xdr source ============================================================
//
// struct Curve25519Public
// {
// opaque key[32];
// };
//
// ===========================================================================
xdr.struct("Curve25519Public", [["key", xdr.opaque(32)]]);
// === xdr source ============================================================
//
// struct HmacSha256Key
// {
// opaque key[32];
// };
//
// ===========================================================================
xdr.struct("HmacSha256Key", [["key", xdr.opaque(32)]]);
// === xdr source ============================================================
//
// struct HmacSha256Mac
// {
// opaque mac[32];
// };
//
// ===========================================================================
xdr.struct("HmacSha256Mac", [["mac", xdr.opaque(32)]]);
}); // Automatically generated by xdrgen
// DO NOT EDIT or your changes may be overwritten
/* jshint maxstatements:2147483647 */
/* jshint esnext:true */
exports.default = types;
/***/ }),
/* 200 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(201);
/***/ }),
/* 201 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(33),
createAssigner = __webpack_require__(109),
keysIn = __webpack_require__(24);
/**
* This method is like `_.assign` except that it iterates over own and
* inherited source properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extend
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assign
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assignIn({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
*/
var assignIn = createAssigner(function(object, source) {
copyObject(source, keysIn(source), object);
});
module.exports = assignIn;
/***/ }),
/* 202 */
/***/ (function(module, exports, __webpack_require__) {
var isFunction = __webpack_require__(50),
isMasked = __webpack_require__(203),
isObject = __webpack_require__(18),
toSource = __webpack_require__(108);
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
module.exports = baseIsNative;
/***/ }),
/* 203 */
/***/ (function(module, exports, __webpack_require__) {
var coreJsData = __webpack_require__(204);
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
module.exports = isMasked;
/***/ }),
/* 204 */
/***/ (function(module, exports, __webpack_require__) {
var root = __webpack_require__(14);
/** Used to detect overreaching core-js shims. */
var coreJsData = root['__core-js_shared__'];
module.exports = coreJsData;
/***/ }),
/* 205 */
/***/ (function(module, exports) {
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
module.exports = getValue;
/***/ }),
/* 206 */
/***/ (function(module, exports, __webpack_require__) {
var identity = __webpack_require__(46),
overRest = __webpack_require__(207),
setToString = __webpack_require__(209);
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return setToString(overRest(func, start, identity), func + '');
}
module.exports = baseRest;
/***/ }),
/* 207 */
/***/ (function(module, exports, __webpack_require__) {
var apply = __webpack_require__(208);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest(func, start, transform) {
start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return apply(func, this, otherArgs);
};
}
module.exports = overRest;
/***/ }),
/* 208 */
/***/ (function(module, exports) {
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
switch (args.length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
module.exports = apply;
/***/ }),
/* 209 */
/***/ (function(module, exports, __webpack_require__) {
var baseSetToString = __webpack_require__(210),
shortOut = __webpack_require__(212);
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString = shortOut(baseSetToString);
module.exports = setToString;
/***/ }),
/* 210 */
/***/ (function(module, exports, __webpack_require__) {
var constant = __webpack_require__(211),
defineProperty = __webpack_require__(107),
identity = __webpack_require__(46);
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !defineProperty ? identity : function(func, string) {
return defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant(string),
'writable': true
});
};
module.exports = baseSetToString;
/***/ }),
/* 211 */
/***/ (function(module, exports) {
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
module.exports = constant;
/***/ }),
/* 212 */
/***/ (function(module, exports) {
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeNow = Date.now;
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
module.exports = shortOut;
/***/ }),
/* 213 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Cursor = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _util = __webpack_require__(51);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Cursor = function () {
function Cursor(buffer) {
_classCallCheck(this, Cursor);
if (!(buffer instanceof Buffer)) {
buffer = typeof buffer === 'number' ? Buffer.alloc(buffer) : Buffer.from(buffer);
}
this._setBuffer(buffer);
this.rewind();
}
_createClass(Cursor, [{
key: '_setBuffer',
value: function _setBuffer(buffer) {
this._buffer = buffer;
this.length = buffer.length;
}
}, {
key: 'buffer',
value: function buffer() {
return this._buffer;
}
}, {
key: 'tap',
value: function tap(cb) {
cb(this);
return this;
}
}, {
key: 'clone',
value: function clone(newIndex) {
var c = new this.constructor(this.buffer());
c.seek(arguments.length === 0 ? this.tell() : newIndex);
return c;
}
}, {
key: 'tell',
value: function tell() {
return this._index;
}
}, {
key: 'seek',
value: function seek(op, index) {
if (arguments.length === 1) {
index = op;
op = '=';
}
if (op === '+') {
this._index += index;
} else if (op === '-') {
this._index -= index;
} else {
this._index = index;
}
return this;
}
}, {
key: 'rewind',
value: function rewind() {
return this.seek(0);
}
}, {
key: 'eof',
value: function eof() {
return this.tell() === this.buffer().length;
}
}, {
key: 'write',
value: function write(string, length, encoding) {
return this.seek('+', this.buffer().write(string, this.tell(), length, encoding));
}
}, {
key: 'fill',
value: function fill(value, length) {
if (arguments.length === 1) {
length = this.buffer().length - this.tell();
}
this.buffer().fill(value, this.tell(), this.tell() + length);
this.seek('+', length);
return this;
}
}, {
key: 'slice',
value: function slice(length) {
if (arguments.length === 0) {
length = this.length - this.tell();
}
var c = new this.constructor(this.buffer().slice(this.tell(), this.tell() + length));
this.seek('+', length);
return c;
}
}, {
key: 'copyFrom',
value: function copyFrom(source) {
var buf = source instanceof Buffer ? source : source.buffer();
buf.copy(this.buffer(), this.tell(), 0, buf.length);
this.seek('+', buf.length);
return this;
}
}, {
key: 'concat',
value: function concat(list) {
list.forEach(function (item, i) {
if (item instanceof Cursor) {
list[i] = item.buffer();
}
});
list.unshift(this.buffer());
var b = Buffer.concat(list);
this._setBuffer(b);
return this;
}
}, {
key: 'toString',
value: function toString(encoding, length) {
if (arguments.length === 0) {
encoding = 'utf8';
length = this.buffer().length - this.tell();
} else if (arguments.length === 1) {
length = this.buffer().length - this.tell();
}
var val = this.buffer().toString(encoding, this.tell(), this.tell() + length);
this.seek('+', length);
return val;
}
}, {
key: 'writeBufferPadded',
value: function writeBufferPadded(buffer) {
var padding = (0, _util.calculatePadding)(buffer.length);
var paddingBuffer = Buffer.alloc(padding);
return this.copyFrom(new Cursor(buffer)).copyFrom(new Cursor(paddingBuffer));
}
}]);
return Cursor;
}();
[[1, ['readInt8', 'readUInt8']], [2, ['readInt16BE', 'readInt16LE', 'readUInt16BE', 'readUInt16LE']], [4, ['readInt32BE', 'readInt32LE', 'readUInt32BE', 'readUInt32LE', 'readFloatBE', 'readFloatLE']], [8, ['readDoubleBE', 'readDoubleLE']]].forEach(function (arr) {
arr[1].forEach(function (method) {
Cursor.prototype[method] = function read() {
var val = this.buffer()[method](this.tell());
this.seek('+', arr[0]);
return val;
};
});
});
[[1, ['writeInt8', 'writeUInt8']], [2, ['writeInt16BE', 'writeInt16LE', 'writeUInt16BE', 'writeUInt16LE']], [4, ['writeInt32BE', 'writeInt32LE', 'writeUInt32BE', 'writeUInt32LE', 'writeFloatBE', 'writeFloatLE']], [8, ['writeDoubleBE', 'writeDoubleLE']]].forEach(function (arr) {
arr[1].forEach(function (method) {
Cursor.prototype[method] = function write(val) {
this.buffer()[method](val, this.tell());
this.seek('+', arr[0]);
return this;
};
});
});
exports.Cursor = Cursor;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 214 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.every` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
*/
function arrayEvery(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (!predicate(array[index], index, array)) {
return false;
}
}
return true;
}
module.exports = arrayEvery;
/***/ }),
/* 215 */
/***/ (function(module, exports, __webpack_require__) {
var baseEach = __webpack_require__(74);
/**
* The base implementation of `_.every` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`
*/
function baseEvery(collection, predicate) {
var result = true;
baseEach(collection, function(value, index, collection) {
result = !!predicate(value, index, collection);
return result;
});
return result;
}
module.exports = baseEvery;
/***/ }),
/* 216 */
/***/ (function(module, exports, __webpack_require__) {
var baseFor = __webpack_require__(66),
keys = __webpack_require__(34);
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && baseFor(object, iteratee, keys);
}
module.exports = baseForOwn;
/***/ }),
/* 217 */
/***/ (function(module, exports, __webpack_require__) {
var overArg = __webpack_require__(112);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
module.exports = nativeKeys;
/***/ }),
/* 218 */
/***/ (function(module, exports, __webpack_require__) {
var isArrayLike = __webpack_require__(25);
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
module.exports = createBaseEach;
/***/ }),
/* 219 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsMatch = __webpack_require__(220),
getMatchData = __webpack_require__(258),
matchesStrictComparable = __webpack_require__(122);
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || baseIsMatch(object, source, matchData);
};
}
module.exports = baseMatches;
/***/ }),
/* 220 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(52),
baseIsEqual = __webpack_require__(114);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
: result
)) {
return false;
}
}
}
return true;
}
module.exports = baseIsMatch;
/***/ }),
/* 221 */
/***/ (function(module, exports) {
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
module.exports = listCacheClear;
/***/ }),
/* 222 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(54);
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
module.exports = listCacheDelete;
/***/ }),
/* 223 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(54);
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
module.exports = listCacheGet;
/***/ }),
/* 224 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(54);
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
module.exports = listCacheHas;
/***/ }),
/* 225 */
/***/ (function(module, exports, __webpack_require__) {
var assocIndexOf = __webpack_require__(54);
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
module.exports = listCacheSet;
/***/ }),
/* 226 */
/***/ (function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(53);
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
module.exports = stackClear;
/***/ }),
/* 227 */
/***/ (function(module, exports) {
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
module.exports = stackDelete;
/***/ }),
/* 228 */
/***/ (function(module, exports) {
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
module.exports = stackGet;
/***/ }),
/* 229 */
/***/ (function(module, exports) {
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
module.exports = stackHas;
/***/ }),
/* 230 */
/***/ (function(module, exports, __webpack_require__) {
var ListCache = __webpack_require__(53),
Map = __webpack_require__(75),
MapCache = __webpack_require__(76);
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
module.exports = stackSet;
/***/ }),
/* 231 */
/***/ (function(module, exports, __webpack_require__) {
var Hash = __webpack_require__(232),
ListCache = __webpack_require__(53),
Map = __webpack_require__(75);
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
module.exports = mapCacheClear;
/***/ }),
/* 232 */
/***/ (function(module, exports, __webpack_require__) {
var hashClear = __webpack_require__(233),
hashDelete = __webpack_require__(234),
hashGet = __webpack_require__(235),
hashHas = __webpack_require__(236),
hashSet = __webpack_require__(237);
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
module.exports = Hash;
/***/ }),
/* 233 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(55);
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
module.exports = hashClear;
/***/ }),
/* 234 */
/***/ (function(module, exports) {
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
module.exports = hashDelete;
/***/ }),
/* 235 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(55);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}
module.exports = hashGet;
/***/ }),
/* 236 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(55);
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
}
module.exports = hashHas;
/***/ }),
/* 237 */
/***/ (function(module, exports, __webpack_require__) {
var nativeCreate = __webpack_require__(55);
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
module.exports = hashSet;
/***/ }),
/* 238 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(56);
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
module.exports = mapCacheDelete;
/***/ }),
/* 239 */
/***/ (function(module, exports) {
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
module.exports = isKeyable;
/***/ }),
/* 240 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(56);
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
module.exports = mapCacheGet;
/***/ }),
/* 241 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(56);
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
module.exports = mapCacheHas;
/***/ }),
/* 242 */
/***/ (function(module, exports, __webpack_require__) {
var getMapData = __webpack_require__(56);
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
module.exports = mapCacheSet;
/***/ }),
/* 243 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(52),
equalArrays = __webpack_require__(115),
equalByTag = __webpack_require__(249),
equalObjects = __webpack_require__(252),
getTag = __webpack_require__(44),
isArray = __webpack_require__(3),
isBuffer = __webpack_require__(40),
isTypedArray = __webpack_require__(48);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
objectTag = '[object Object]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = objIsArr ? arrayTag : getTag(object),
othTag = othIsArr ? arrayTag : getTag(other);
objTag = objTag == argsTag ? objectTag : objTag;
othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
module.exports = baseIsEqualDeep;
/***/ }),
/* 244 */
/***/ (function(module, exports, __webpack_require__) {
var MapCache = __webpack_require__(76),
setCacheAdd = __webpack_require__(245),
setCacheHas = __webpack_require__(246);
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values == null ? 0 : values.length;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
module.exports = SetCache;
/***/ }),
/* 245 */
/***/ (function(module, exports) {
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED);
return this;
}
module.exports = setCacheAdd;
/***/ }),
/* 246 */
/***/ (function(module, exports) {
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
module.exports = setCacheHas;
/***/ }),
/* 247 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
module.exports = arraySome;
/***/ }),
/* 248 */
/***/ (function(module, exports) {
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
module.exports = cacheHas;
/***/ }),
/* 249 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(39),
Uint8Array = __webpack_require__(116),
eq = __webpack_require__(43),
equalArrays = __webpack_require__(115),
mapToArray = __webpack_require__(250),
setToArray = __webpack_require__(251);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]';
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
module.exports = equalByTag;
/***/ }),
/* 250 */
/***/ (function(module, exports) {
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
module.exports = mapToArray;
/***/ }),
/* 251 */
/***/ (function(module, exports) {
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
module.exports = setToArray;
/***/ }),
/* 252 */
/***/ (function(module, exports, __webpack_require__) {
var getAllKeys = __webpack_require__(117);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1;
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
objProps = getAllKeys(object),
objLength = objProps.length,
othProps = getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Check that cyclic values are equal.
var objStacked = stack.get(object);
var othStacked = stack.get(other);
if (objStacked && othStacked) {
return objStacked == other && othStacked == object;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
stack['delete'](other);
return result;
}
module.exports = equalObjects;
/***/ }),
/* 253 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
module.exports = arrayFilter;
/***/ }),
/* 254 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(26),
root = __webpack_require__(14);
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');
module.exports = DataView;
/***/ }),
/* 255 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(26),
root = __webpack_require__(14);
/* Built-in method references that are verified to be native. */
var Promise = getNative(root, 'Promise');
module.exports = Promise;
/***/ }),
/* 256 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(26),
root = __webpack_require__(14);
/* Built-in method references that are verified to be native. */
var Set = getNative(root, 'Set');
module.exports = Set;
/***/ }),
/* 257 */
/***/ (function(module, exports, __webpack_require__) {
var getNative = __webpack_require__(26),
root = __webpack_require__(14);
/* Built-in method references that are verified to be native. */
var WeakMap = getNative(root, 'WeakMap');
module.exports = WeakMap;
/***/ }),
/* 258 */
/***/ (function(module, exports, __webpack_require__) {
var isStrictComparable = __webpack_require__(121),
keys = __webpack_require__(34);
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = keys(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, isStrictComparable(value)];
}
return result;
}
module.exports = getMatchData;
/***/ }),
/* 259 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsEqual = __webpack_require__(114),
get = __webpack_require__(260),
hasIn = __webpack_require__(264),
isKey = __webpack_require__(78),
isStrictComparable = __webpack_require__(121),
matchesStrictComparable = __webpack_require__(122),
toKey = __webpack_require__(58);
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (isKey(path) && isStrictComparable(srcValue)) {
return matchesStrictComparable(toKey(path), srcValue);
}
return function(object) {
var objValue = get(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn(object, path)
: baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
};
}
module.exports = baseMatchesProperty;
/***/ }),
/* 260 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(123);
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
module.exports = get;
/***/ }),
/* 261 */
/***/ (function(module, exports, __webpack_require__) {
var memoizeCapped = __webpack_require__(262);
/** Used to match property names within property paths. */
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoizeCapped(function(string) {
var result = [];
if (string.charCodeAt(0) === 46 /* . */) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, subString) {
result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
module.exports = stringToPath;
/***/ }),
/* 262 */
/***/ (function(module, exports, __webpack_require__) {
var memoize = __webpack_require__(263);
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
module.exports = memoizeCapped;
/***/ }),
/* 263 */
/***/ (function(module, exports, __webpack_require__) {
var MapCache = __webpack_require__(76);
/** Error message constants. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
// Expose `MapCache`.
memoize.Cache = MapCache;
module.exports = memoize;
/***/ }),
/* 264 */
/***/ (function(module, exports, __webpack_require__) {
var baseHasIn = __webpack_require__(265),
hasPath = __webpack_require__(266);
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn(object, path) {
return object != null && hasPath(object, path, baseHasIn);
}
module.exports = hasIn;
/***/ }),
/* 265 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return object != null && key in Object(object);
}
module.exports = baseHasIn;
/***/ }),
/* 266 */
/***/ (function(module, exports, __webpack_require__) {
var castPath = __webpack_require__(124),
isArguments = __webpack_require__(47),
isArray = __webpack_require__(3),
isIndex = __webpack_require__(68),
isLength = __webpack_require__(69),
toKey = __webpack_require__(58);
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = castPath(path, object);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength(length) && isIndex(key, length) &&
(isArray(object) || isArguments(object));
}
module.exports = hasPath;
/***/ }),
/* 267 */
/***/ (function(module, exports, __webpack_require__) {
var baseProperty = __webpack_require__(125),
basePropertyDeep = __webpack_require__(268),
isKey = __webpack_require__(78),
toKey = __webpack_require__(58);
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}
module.exports = property;
/***/ }),
/* 268 */
/***/ (function(module, exports, __webpack_require__) {
var baseGet = __webpack_require__(123);
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyDeep(path) {
return function(object) {
return baseGet(object, path);
};
}
module.exports = basePropertyDeep;
/***/ }),
/* 269 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Hyper = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _long = __webpack_require__(126);
var _long2 = _interopRequireDefault(_long);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Hyper = exports.Hyper = function (_Long) {
_inherits(Hyper, _Long);
_createClass(Hyper, null, [{
key: 'read',
value: function read(io) {
var high = io.readInt32BE();
var low = io.readInt32BE();
return this.fromBits(low, high);
}
}, {
key: 'write',
value: function write(value, io) {
if (!(value instanceof this)) {
throw new Error('XDR Write Error: ' + value + ' is not a Hyper');
}
io.writeInt32BE(value.high);
io.writeInt32BE(value.low);
}
}, {
key: 'fromString',
value: function fromString(string) {
if (!/^-?\d+$/.test(string)) {
throw new Error('Invalid hyper string: ' + string);
}
var result = _get(Hyper.__proto__ || Object.getPrototypeOf(Hyper), 'fromString', this).call(this, string, false);
return new this(result.low, result.high);
}
}, {
key: 'fromBits',
value: function fromBits(low, high) {
var result = _get(Hyper.__proto__ || Object.getPrototypeOf(Hyper), 'fromBits', this).call(this, low, high, false);
return new this(result.low, result.high);
}
}, {
key: 'isValid',
value: function isValid(value) {
return value instanceof this;
}
}]);
function Hyper(low, high) {
_classCallCheck(this, Hyper);
return _possibleConstructorReturn(this, (Hyper.__proto__ || Object.getPrototypeOf(Hyper)).call(this, low, high, false));
}
return Hyper;
}(_long2.default);
(0, _ioMixin2.default)(Hyper);
Hyper.MAX_VALUE = new Hyper(_long2.default.MAX_VALUE.low, _long2.default.MAX_VALUE.high);
Hyper.MIN_VALUE = new Hyper(_long2.default.MIN_VALUE.low, _long2.default.MIN_VALUE.high);
/***/ }),
/* 270 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.UnsignedHyper = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _long = __webpack_require__(126);
var _long2 = _interopRequireDefault(_long);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var UnsignedHyper = exports.UnsignedHyper = function (_Long) {
_inherits(UnsignedHyper, _Long);
_createClass(UnsignedHyper, null, [{
key: 'read',
value: function read(io) {
var high = io.readInt32BE();
var low = io.readInt32BE();
return this.fromBits(low, high);
}
}, {
key: 'write',
value: function write(value, io) {
if (!(value instanceof this)) {
throw new Error('XDR Write Error: ' + value + ' is not an UnsignedHyper');
}
io.writeInt32BE(value.high);
io.writeInt32BE(value.low);
}
}, {
key: 'fromString',
value: function fromString(string) {
if (!/^\d+$/.test(string)) {
throw new Error('Invalid hyper string: ' + string);
}
var result = _get(UnsignedHyper.__proto__ || Object.getPrototypeOf(UnsignedHyper), 'fromString', this).call(this, string, true);
return new this(result.low, result.high);
}
}, {
key: 'fromBits',
value: function fromBits(low, high) {
var result = _get(UnsignedHyper.__proto__ || Object.getPrototypeOf(UnsignedHyper), 'fromBits', this).call(this, low, high, true);
return new this(result.low, result.high);
}
}, {
key: 'isValid',
value: function isValid(value) {
return value instanceof this;
}
}]);
function UnsignedHyper(low, high) {
_classCallCheck(this, UnsignedHyper);
return _possibleConstructorReturn(this, (UnsignedHyper.__proto__ || Object.getPrototypeOf(UnsignedHyper)).call(this, low, high, true));
}
return UnsignedHyper;
}(_long2.default);
(0, _ioMixin2.default)(UnsignedHyper);
UnsignedHyper.MAX_VALUE = new UnsignedHyper(_long2.default.MAX_UNSIGNED_VALUE.low, _long2.default.MAX_UNSIGNED_VALUE.high);
UnsignedHyper.MIN_VALUE = new UnsignedHyper(_long2.default.MIN_VALUE.low, _long2.default.MIN_VALUE.high);
/***/ }),
/* 271 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Float = undefined;
var _isNumber = __webpack_require__(42);
var _isNumber2 = _interopRequireDefault(_isNumber);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Float = exports.Float = {
read: function read(io) {
return io.readFloatBE();
},
write: function write(value, io) {
if (!(0, _isNumber2.default)(value)) {
throw new Error('XDR Write Error: not a number');
}
io.writeFloatBE(value);
},
isValid: function isValid(value) {
return (0, _isNumber2.default)(value);
}
};
(0, _ioMixin2.default)(Float);
/***/ }),
/* 272 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Double = undefined;
var _isNumber = __webpack_require__(42);
var _isNumber2 = _interopRequireDefault(_isNumber);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Double = exports.Double = {
read: function read(io) {
return io.readDoubleBE();
},
write: function write(value, io) {
if (!(0, _isNumber2.default)(value)) {
throw new Error('XDR Write Error: not a number');
}
io.writeDoubleBE(value);
},
isValid: function isValid(value) {
return (0, _isNumber2.default)(value);
}
};
(0, _ioMixin2.default)(Double);
/***/ }),
/* 273 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Quadruple = undefined;
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var Quadruple = exports.Quadruple = {
/* jshint unused: false */
read: function read() {
throw new Error('XDR Read Error: quadruple not supported');
},
write: function write() {
throw new Error('XDR Write Error: quadruple not supported');
},
isValid: function isValid() {
return false;
}
};
(0, _ioMixin2.default)(Quadruple);
/***/ }),
/* 274 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(20),
isObjectLike = __webpack_require__(12);
/** `Object#toString` result references. */
var boolTag = '[object Boolean]';
/**
* Checks if `value` is classified as a boolean primitive or object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
* @example
*
* _.isBoolean(false);
* // => true
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false ||
(isObjectLike(value) && baseGetTag(value) == boolTag);
}
module.exports = isBoolean;
/***/ }),
/* 275 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.String = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _isString = __webpack_require__(9);
var _isString2 = _interopRequireDefault(_isString);
var _isArray = __webpack_require__(3);
var _isArray2 = _interopRequireDefault(_isArray);
var _int = __webpack_require__(32);
var _unsignedInt = __webpack_require__(59);
var _util = __webpack_require__(51);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var String = exports.String = function () {
function String() {
var maxLength = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _unsignedInt.UnsignedInt.MAX_VALUE;
_classCallCheck(this, String);
this._maxLength = maxLength;
}
_createClass(String, [{
key: 'read',
value: function read(io) {
var length = _int.Int.read(io);
if (length > this._maxLength) {
throw new Error('XDR Read Error: Saw ' + length + ' length String,' + ('max allowed is ' + this._maxLength));
}
var padding = (0, _util.calculatePadding)(length);
var result = io.slice(length);
(0, _util.slicePadding)(io, padding);
return result.buffer();
}
}, {
key: 'readString',
value: function readString(io) {
return this.read(io).toString('utf8');
}
}, {
key: 'write',
value: function write(value, io) {
if (value.length > this._maxLength) {
throw new Error('XDR Write Error: Got ' + value.length + ' bytes,' + ('max allows is ' + this._maxLength));
}
var buffer = void 0;
if ((0, _isString2.default)(value)) {
buffer = Buffer.from(value, 'utf8');
} else {
buffer = Buffer.from(value);
}
_int.Int.write(buffer.length, io);
io.writeBufferPadded(buffer);
}
}, {
key: 'isValid',
value: function isValid(value) {
var buffer = void 0;
if ((0, _isString2.default)(value)) {
buffer = Buffer.from(value, 'utf8');
} else if ((0, _isArray2.default)(value) || Buffer.isBuffer(value)) {
buffer = Buffer.from(value);
} else {
return false;
}
return buffer.length <= this._maxLength;
}
}]);
return String;
}();
(0, _ioMixin2.default)(String.prototype);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 276 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Opaque = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _util = __webpack_require__(51);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Opaque = exports.Opaque = function () {
function Opaque(length) {
_classCallCheck(this, Opaque);
this._length = length;
this._padding = (0, _util.calculatePadding)(length);
}
_createClass(Opaque, [{
key: 'read',
value: function read(io) {
var result = io.slice(this._length);
(0, _util.slicePadding)(io, this._padding);
return result.buffer();
}
}, {
key: 'write',
value: function write(value, io) {
if (value.length !== this._length) {
throw new Error('XDR Write Error: Got ' + value.length + ' bytes, expected ' + this._length);
}
io.writeBufferPadded(value);
}
}, {
key: 'isValid',
value: function isValid(value) {
return Buffer.isBuffer(value) && value.length === this._length;
}
}]);
return Opaque;
}();
(0, _ioMixin2.default)(Opaque.prototype);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 277 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.VarOpaque = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _int = __webpack_require__(32);
var _unsignedInt = __webpack_require__(59);
var _util = __webpack_require__(51);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var VarOpaque = exports.VarOpaque = function () {
function VarOpaque() {
var maxLength = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _unsignedInt.UnsignedInt.MAX_VALUE;
_classCallCheck(this, VarOpaque);
this._maxLength = maxLength;
}
_createClass(VarOpaque, [{
key: 'read',
value: function read(io) {
var length = _int.Int.read(io);
if (length > this._maxLength) {
throw new Error('XDR Read Error: Saw ' + length + ' length VarOpaque,' + ('max allowed is ' + this._maxLength));
}
var padding = (0, _util.calculatePadding)(length);
var result = io.slice(length);
(0, _util.slicePadding)(io, padding);
return result.buffer();
}
}, {
key: 'write',
value: function write(value, io) {
if (value.length > this._maxLength) {
throw new Error('XDR Write Error: Got ' + value.length + ' bytes,' + ('max allows is ' + this._maxLength));
}
_int.Int.write(value.length, io);
io.writeBufferPadded(value);
}
}, {
key: 'isValid',
value: function isValid(value) {
return Buffer.isBuffer(value) && value.length <= this._maxLength;
}
}]);
return VarOpaque;
}();
(0, _ioMixin2.default)(VarOpaque.prototype);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 278 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Array = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _every = __webpack_require__(73);
var _every2 = _interopRequireDefault(_every);
var _each = __webpack_require__(35);
var _each2 = _interopRequireDefault(_each);
var _times = __webpack_require__(129);
var _times2 = _interopRequireDefault(_times);
var _isArray = __webpack_require__(3);
var _isArray2 = _interopRequireDefault(_isArray);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Array = exports.Array = function () {
function Array(childType, length) {
_classCallCheck(this, Array);
this._childType = childType;
this._length = length;
}
_createClass(Array, [{
key: 'read',
value: function read(io) {
var _this = this;
return (0, _times2.default)(this._length, function () {
return _this._childType.read(io);
});
}
}, {
key: 'write',
value: function write(value, io) {
var _this2 = this;
if (!(0, _isArray2.default)(value)) {
throw new Error('XDR Write Error: value is not array');
}
if (value.length !== this._length) {
throw new Error('XDR Write Error: Got array of size ' + value.length + ',' + ('expected ' + this._length));
}
(0, _each2.default)(value, function (child) {
return _this2._childType.write(child, io);
});
}
}, {
key: 'isValid',
value: function isValid(value) {
var _this3 = this;
if (!(0, _isArray2.default)(value)) {
return false;
}
if (value.length !== this._length) {
return false;
}
return (0, _every2.default)(value, function (child) {
return _this3._childType.isValid(child);
});
}
}]);
return Array;
}();
(0, _ioMixin2.default)(Array.prototype);
/***/ }),
/* 279 */
/***/ (function(module, exports, __webpack_require__) {
var arrayEach = __webpack_require__(128),
baseEach = __webpack_require__(74),
castFunction = __webpack_require__(67),
isArray = __webpack_require__(3);
/**
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `_.forIn`
* or `_.forOwn` for object iteration.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEachRight
* @example
*
* _.forEach([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forEach(collection, iteratee) {
var func = isArray(collection) ? arrayEach : baseEach;
return func(collection, castFunction(iteratee));
}
module.exports = forEach;
/***/ }),
/* 280 */
/***/ (function(module, exports, __webpack_require__) {
var toNumber = __webpack_require__(281);
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_INTEGER = 1.7976931348623157e+308;
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
module.exports = toFinite;
/***/ }),
/* 281 */
/***/ (function(module, exports, __webpack_require__) {
var baseTrim = __webpack_require__(282),
isObject = __webpack_require__(18),
isSymbol = __webpack_require__(57);
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = baseTrim(value);
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
module.exports = toNumber;
/***/ }),
/* 282 */
/***/ (function(module, exports, __webpack_require__) {
var trimmedEndIndex = __webpack_require__(131);
/** Used to match leading whitespace. */
var reTrimStart = /^\s+/;
/**
* The base implementation of `_.trim`.
*
* @private
* @param {string} string The string to trim.
* @returns {string} Returns the trimmed string.
*/
function baseTrim(string) {
return string
? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
: string;
}
module.exports = baseTrim;
/***/ }),
/* 283 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.VarArray = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _every = __webpack_require__(73);
var _every2 = _interopRequireDefault(_every);
var _each = __webpack_require__(35);
var _each2 = _interopRequireDefault(_each);
var _times = __webpack_require__(129);
var _times2 = _interopRequireDefault(_times);
var _isArray = __webpack_require__(3);
var _isArray2 = _interopRequireDefault(_isArray);
var _unsignedInt = __webpack_require__(59);
var _int = __webpack_require__(32);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var VarArray = exports.VarArray = function () {
function VarArray(childType) {
var maxLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _unsignedInt.UnsignedInt.MAX_VALUE;
_classCallCheck(this, VarArray);
this._childType = childType;
this._maxLength = maxLength;
}
_createClass(VarArray, [{
key: 'read',
value: function read(io) {
var _this = this;
var length = _int.Int.read(io);
if (length > this._maxLength) {
throw new Error('XDR Read Error: Saw ' + length + ' length VarArray,' + ('max allowed is ' + this._maxLength));
}
return (0, _times2.default)(length, function () {
return _this._childType.read(io);
});
}
}, {
key: 'write',
value: function write(value, io) {
var _this2 = this;
if (!(0, _isArray2.default)(value)) {
throw new Error('XDR Write Error: value is not array');
}
if (value.length > this._maxLength) {
throw new Error('XDR Write Error: Got array of size ' + value.length + ',' + ('max allowed is ' + this._maxLength));
}
_int.Int.write(value.length, io);
(0, _each2.default)(value, function (child) {
return _this2._childType.write(child, io);
});
}
}, {
key: 'isValid',
value: function isValid(value) {
var _this3 = this;
if (!(0, _isArray2.default)(value)) {
return false;
}
if (value.length > this._maxLength) {
return false;
}
return (0, _every2.default)(value, function (child) {
return _this3._childType.isValid(child);
});
}
}]);
return VarArray;
}();
(0, _ioMixin2.default)(VarArray.prototype);
/***/ }),
/* 284 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Option = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _isNull = __webpack_require__(132);
var _isNull2 = _interopRequireDefault(_isNull);
var _isUndefined = __webpack_require__(7);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _bool = __webpack_require__(127);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Option = exports.Option = function () {
function Option(childType) {
_classCallCheck(this, Option);
this._childType = childType;
}
_createClass(Option, [{
key: 'read',
value: function read(io) {
if (_bool.Bool.read(io)) {
return this._childType.read(io);
}
return undefined;
}
}, {
key: 'write',
value: function write(value, io) {
var isPresent = !((0, _isNull2.default)(value) || (0, _isUndefined2.default)(value));
_bool.Bool.write(isPresent, io);
if (isPresent) {
this._childType.write(value, io);
}
}
}, {
key: 'isValid',
value: function isValid(value) {
if ((0, _isNull2.default)(value)) {
return true;
}
if ((0, _isUndefined2.default)(value)) {
return true;
}
return this._childType.isValid(value);
}
}]);
return Option;
}();
(0, _ioMixin2.default)(Option.prototype);
/***/ }),
/* 285 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Enum = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _each = __webpack_require__(35);
var _each2 = _interopRequireDefault(_each);
var _values = __webpack_require__(286);
var _values2 = _interopRequireDefault(_values);
var _int = __webpack_require__(32);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Enum = exports.Enum = function () {
function Enum(name, value) {
_classCallCheck(this, Enum);
this.name = name;
this.value = value;
}
_createClass(Enum, null, [{
key: 'read',
value: function read(io) {
var intVal = _int.Int.read(io);
if (!this._byValue.has(intVal)) {
throw new Error('XDR Read Error: Unknown ' + this.enumName + ' member for value ' + intVal);
}
return this._byValue.get(intVal);
}
}, {
key: 'write',
value: function write(value, io) {
if (!(value instanceof this)) {
throw new Error('XDR Write Error: Unknown ' + value + ' is not a ' + this.enumName);
}
_int.Int.write(value.value, io);
}
}, {
key: 'isValid',
value: function isValid(value) {
return value instanceof this;
}
}, {
key: 'members',
value: function members() {
return this._members;
}
}, {
key: 'values',
value: function values() {
return (0, _values2.default)(this._members);
}
}, {
key: 'fromName',
value: function fromName(name) {
var result = this._members[name];
if (!result) {
throw new Error(name + ' is not a member of ' + this.enumName);
}
return result;
}
}, {
key: 'fromValue',
value: function fromValue(value) {
var result = this._byValue.get(value);
if (!result) {
throw new Error(value + ' is not a value of any member of ' + this.enumName);
}
return result;
}
}, {
key: 'create',
value: function create(context, name, members) {
var ChildEnum = function (_Enum) {
_inherits(ChildEnum, _Enum);
function ChildEnum() {
_classCallCheck(this, ChildEnum);
return _possibleConstructorReturn(this, (ChildEnum.__proto__ || Object.getPrototypeOf(ChildEnum)).apply(this, arguments));
}
return ChildEnum;
}(Enum);
ChildEnum.enumName = name;
context.results[name] = ChildEnum;
ChildEnum._members = {};
ChildEnum._byValue = new Map();
(0, _each2.default)(members, function (value, key) {
var inst = new ChildEnum(key, value);
ChildEnum._members[key] = inst;
ChildEnum._byValue.set(value, inst);
ChildEnum[key] = function () {
return inst;
};
});
return ChildEnum;
}
}]);
return Enum;
}();
(0, _ioMixin2.default)(Enum);
/***/ }),
/* 286 */
/***/ (function(module, exports, __webpack_require__) {
var baseValues = __webpack_require__(287),
keys = __webpack_require__(34);
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return object == null ? [] : baseValues(object, keys(object));
}
module.exports = values;
/***/ }),
/* 287 */
/***/ (function(module, exports, __webpack_require__) {
var arrayMap = __webpack_require__(81);
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/
function baseValues(object, props) {
return arrayMap(props, function(key) {
return object[key];
});
}
module.exports = baseValues;
/***/ }),
/* 288 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Struct = undefined;
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _each = __webpack_require__(35);
var _each2 = _interopRequireDefault(_each);
var _map = __webpack_require__(134);
var _map2 = _interopRequireDefault(_map);
var _isUndefined = __webpack_require__(7);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _fromPairs = __webpack_require__(290);
var _fromPairs2 = _interopRequireDefault(_fromPairs);
var _reference = __webpack_require__(82);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Struct = exports.Struct = function () {
function Struct(attributes) {
_classCallCheck(this, Struct);
this._attributes = attributes || {};
}
_createClass(Struct, null, [{
key: 'read',
value: function read(io) {
var fields = (0, _map2.default)(this._fields, function (field) {
var _field = _slicedToArray(field, 2),
name = _field[0],
type = _field[1];
var value = type.read(io);
return [name, value];
});
return new this((0, _fromPairs2.default)(fields));
}
}, {
key: 'write',
value: function write(value, io) {
if (!(value instanceof this)) {
throw new Error('XDR Write Error: ' + value + ' is not a ' + this.structName);
}
(0, _each2.default)(this._fields, function (field) {
var _field2 = _slicedToArray(field, 2),
name = _field2[0],
type = _field2[1];
var attribute = value._attributes[name];
type.write(attribute, io);
});
}
}, {
key: 'isValid',
value: function isValid(value) {
return value instanceof this;
}
}, {
key: 'create',
value: function create(context, name, fields) {
var ChildStruct = function (_Struct) {
_inherits(ChildStruct, _Struct);
function ChildStruct() {
_classCallCheck(this, ChildStruct);
return _possibleConstructorReturn(this, (ChildStruct.__proto__ || Object.getPrototypeOf(ChildStruct)).apply(this, arguments));
}
return ChildStruct;
}(Struct);
ChildStruct.structName = name;
context.results[name] = ChildStruct;
ChildStruct._fields = fields.map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
fieldName = _ref2[0],
field = _ref2[1];
if (field instanceof _reference.Reference) {
field = field.resolve(context);
}
return [fieldName, field];
});
(0, _each2.default)(ChildStruct._fields, function (field) {
var _field3 = _slicedToArray(field, 1),
fieldName = _field3[0];
ChildStruct.prototype[fieldName] = getReadOrWriteAttribute(fieldName);
});
return ChildStruct;
}
}]);
return Struct;
}();
(0, _ioMixin2.default)(Struct);
function getReadOrWriteAttribute(name) {
return function readOrWriteAttribute(value) {
if (!(0, _isUndefined2.default)(value)) {
this._attributes[name] = value;
}
return this._attributes[name];
};
}
/***/ }),
/* 289 */
/***/ (function(module, exports, __webpack_require__) {
var baseEach = __webpack_require__(74),
isArrayLike = __webpack_require__(25);
/**
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
module.exports = baseMap;
/***/ }),
/* 290 */
/***/ (function(module, exports) {
/**
* The inverse of `_.toPairs`; this method returns an object composed
* from key-value `pairs`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} pairs The key-value pairs.
* @returns {Object} Returns the new object.
* @example
*
* _.fromPairs([['a', 1], ['b', 2]]);
* // => { 'a': 1, 'b': 2 }
*/
function fromPairs(pairs) {
var index = -1,
length = pairs == null ? 0 : pairs.length,
result = {};
while (++index < length) {
var pair = pairs[index];
result[pair[0]] = pair[1];
}
return result;
}
module.exports = fromPairs;
/***/ }),
/* 291 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Union = undefined;
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _each = __webpack_require__(35);
var _each2 = _interopRequireDefault(_each);
var _isUndefined = __webpack_require__(7);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _isString = __webpack_require__(9);
var _isString2 = _interopRequireDefault(_isString);
var _void = __webpack_require__(133);
var _reference = __webpack_require__(82);
var _ioMixin = __webpack_require__(4);
var _ioMixin2 = _interopRequireDefault(_ioMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Union = exports.Union = function () {
function Union(aSwitch, value) {
_classCallCheck(this, Union);
this.set(aSwitch, value);
}
_createClass(Union, [{
key: 'set',
value: function set(aSwitch, value) {
if ((0, _isString2.default)(aSwitch)) {
aSwitch = this.constructor._switchOn.fromName(aSwitch);
}
this._switch = aSwitch;
this._arm = this.constructor.armForSwitch(this._switch);
this._armType = this.constructor.armTypeForArm(this._arm);
this._value = value;
}
}, {
key: 'get',
value: function get() {
var armName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this._arm;
if (this._arm !== _void.Void && this._arm !== armName) {
throw new Error(armName + ' not set');
}
return this._value;
}
}, {
key: 'switch',
value: function _switch() {
return this._switch;
}
}, {
key: 'arm',
value: function arm() {
return this._arm;
}
}, {
key: 'armType',
value: function armType() {
return this._armType;
}
}, {
key: 'value',
value: function value() {
return this._value;
}
}], [{
key: 'armForSwitch',
value: function armForSwitch(aSwitch) {
if (this._switches.has(aSwitch)) {
return this._switches.get(aSwitch);
}
if (this._defaultArm) {
return this._defaultArm;
}
throw new Error('Bad union switch: ' + aSwitch);
}
}, {
key: 'armTypeForArm',
value: function armTypeForArm(arm) {
if (arm === _void.Void) {
return _void.Void;
}
return this._arms[arm];
}
}, {
key: 'read',
value: function read(io) {
var aSwitch = this._switchOn.read(io);
var arm = this.armForSwitch(aSwitch);
var armType = this.armTypeForArm(arm);
var value = void 0;
if (!(0, _isUndefined2.default)(armType)) {
value = armType.read(io);
} else {
value = arm.read(io);
}
return new this(aSwitch, value);
}
}, {
key: 'write',
value: function write(value, io) {
if (!(value instanceof this)) {
throw new Error('XDR Write Error: ' + value + ' is not a ' + this.unionName);
}
this._switchOn.write(value.switch(), io);
value.armType().write(value.value(), io);
}
}, {
key: 'isValid',
value: function isValid(value) {
return value instanceof this;
}
}, {
key: 'create',
value: function create(context, name, config) {
var ChildUnion = function (_Union) {
_inherits(ChildUnion, _Union);
function ChildUnion() {
_classCallCheck(this, ChildUnion);
return _possibleConstructorReturn(this, (ChildUnion.__proto__ || Object.getPrototypeOf(ChildUnion)).apply(this, arguments));
}
return ChildUnion;
}(Union);
ChildUnion.unionName = name;
context.results[name] = ChildUnion;
if (config.switchOn instanceof _reference.Reference) {
ChildUnion._switchOn = config.switchOn.resolve(context);
} else {
ChildUnion._switchOn = config.switchOn;
}
ChildUnion._switches = new Map();
ChildUnion._arms = {};
(0, _each2.default)(config.arms, function (value, armsName) {
if (value instanceof _reference.Reference) {
value = value.resolve(context);
}
ChildUnion._arms[armsName] = value;
});
// resolve default arm
var defaultArm = config.defaultArm;
if (defaultArm instanceof _reference.Reference) {
defaultArm = defaultArm.resolve(context);
}
ChildUnion._defaultArm = defaultArm;
(0, _each2.default)(config.switches, function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
aSwitch = _ref2[0],
armName = _ref2[1];
if ((0, _isString2.default)(aSwitch)) {
aSwitch = ChildUnion._switchOn.fromName(aSwitch);
}
ChildUnion._switches.set(aSwitch, armName);
});
// add enum-based helpers
// NOTE: we don't have good notation for "is a subclass of XDR.Enum",
// and so we use the following check (does _switchOn have a `values`
// attribute) to approximate the intent.
if (!(0, _isUndefined2.default)(ChildUnion._switchOn.values)) {
(0, _each2.default)(ChildUnion._switchOn.values(), function (aSwitch) {
// Add enum-based constrocutors
ChildUnion[aSwitch.name] = function (value) {
return new ChildUnion(aSwitch, value);
};
// Add enum-based "set" helpers
// (note: normally I'd use an arrow function but the use of `this`
// here might rely on it NOT being an arrow function. so just keep it.)
ChildUnion.prototype[aSwitch.name] = function set(value) {
return this.set(aSwitch, value);
};
});
}
// Add arm accessor helpers
(0, _each2.default)(ChildUnion._arms, function (type, armsName) {
if (type === _void.Void) {
return;
}
ChildUnion.prototype[armsName] = function get() {
return this.get(armsName);
};
});
return ChildUnion;
}
}]);
return Union;
}();
(0, _ioMixin2.default)(Union);
/***/ }),
/* 292 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _reference = __webpack_require__(82);
Object.keys(_reference).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _reference[key];
}
});
});
exports.config = config;
var _isUndefined = __webpack_require__(7);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _each = __webpack_require__(35);
var _each2 = _interopRequireDefault(_each);
var _types = __webpack_require__(105);
var XDRTypes = _interopRequireWildcard(_types);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function config(fn) {
var types = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (fn) {
var builder = new TypeBuilder(types);
fn(builder);
builder.resolve();
}
return types;
}
var SimpleReference = function (_Reference) {
_inherits(SimpleReference, _Reference);
function SimpleReference(name) {
_classCallCheck(this, SimpleReference);
var _this = _possibleConstructorReturn(this, (SimpleReference.__proto__ || Object.getPrototypeOf(SimpleReference)).call(this));
_this.name = name;
return _this;
}
_createClass(SimpleReference, [{
key: 'resolve',
value: function resolve(context) {
var defn = context.definitions[this.name];
return defn.resolve(context);
}
}]);
return SimpleReference;
}(_reference.Reference);
var ArrayReference = function (_Reference2) {
_inherits(ArrayReference, _Reference2);
function ArrayReference(childReference, length) {
var variable = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
_classCallCheck(this, ArrayReference);
var _this2 = _possibleConstructorReturn(this, (ArrayReference.__proto__ || Object.getPrototypeOf(ArrayReference)).call(this));
_this2.childReference = childReference;
_this2.length = length;
_this2.variable = variable;
return _this2;
}
_createClass(ArrayReference, [{
key: 'resolve',
value: function resolve(context) {
var resolvedChild = this.childReference;
var length = this.length;
if (resolvedChild instanceof _reference.Reference) {
resolvedChild = resolvedChild.resolve(context);
}
if (length instanceof _reference.Reference) {
length = length.resolve(context);
}
if (this.variable) {
return new XDRTypes.VarArray(resolvedChild, length);
}
return new XDRTypes.Array(resolvedChild, length);
}
}]);
return ArrayReference;
}(_reference.Reference);
var OptionReference = function (_Reference3) {
_inherits(OptionReference, _Reference3);
function OptionReference(childReference) {
_classCallCheck(this, OptionReference);
var _this3 = _possibleConstructorReturn(this, (OptionReference.__proto__ || Object.getPrototypeOf(OptionReference)).call(this));
_this3.childReference = childReference;
_this3.name = childReference.name;
return _this3;
}
_createClass(OptionReference, [{
key: 'resolve',
value: function resolve(context) {
var resolvedChild = this.childReference;
if (resolvedChild instanceof _reference.Reference) {
resolvedChild = resolvedChild.resolve(context);
}
return new XDRTypes.Option(resolvedChild);
}
}]);
return OptionReference;
}(_reference.Reference);
var SizedReference = function (_Reference4) {
_inherits(SizedReference, _Reference4);
function SizedReference(sizedType, length) {
_classCallCheck(this, SizedReference);
var _this4 = _possibleConstructorReturn(this, (SizedReference.__proto__ || Object.getPrototypeOf(SizedReference)).call(this));
_this4.sizedType = sizedType;
_this4.length = length;
return _this4;
}
_createClass(SizedReference, [{
key: 'resolve',
value: function resolve(context) {
var length = this.length;
if (length instanceof _reference.Reference) {
length = length.resolve(context);
}
return new this.sizedType(length);
}
}]);
return SizedReference;
}(_reference.Reference);
var Definition = function () {
function Definition(constructor, name, cfg) {
_classCallCheck(this, Definition);
this.constructor = constructor;
this.name = name;
this.config = cfg;
}
// resolve calls the constructor of this definition with the provided context
// and this definitions config values. The definitions constructor should
// populate the final type on `context.results`, and may refer to other
// definitions through `context.definitions`
_createClass(Definition, [{
key: 'resolve',
value: function resolve(context) {
if (this.name in context.results) {
return context.results[this.name];
}
return this.constructor(context, this.name, this.config);
}
}]);
return Definition;
}();
// let the reference resoltion system do it's thing
// the "constructor" for a typedef just returns the resolved value
function createTypedef(context, typeName, value) {
if (value instanceof _reference.Reference) {
value = value.resolve(context);
}
context.results[typeName] = value;
return value;
}
function createConst(context, name, value) {
context.results[name] = value;
return value;
}
var TypeBuilder = function () {
function TypeBuilder(destination) {
_classCallCheck(this, TypeBuilder);
this._destination = destination;
this._definitions = {};
}
_createClass(TypeBuilder, [{
key: 'enum',
value: function _enum(name, members) {
var result = new Definition(XDRTypes.Enum.create, name, members);
this.define(name, result);
}
}, {
key: 'struct',
value: function struct(name, members) {
var result = new Definition(XDRTypes.Struct.create, name, members);
this.define(name, result);
}
}, {
key: 'union',
value: function union(name, cfg) {
var result = new Definition(XDRTypes.Union.create, name, cfg);
this.define(name, result);
}
}, {
key: 'typedef',
value: function typedef(name, cfg) {
var result = new Definition(createTypedef, name, cfg);
this.define(name, result);
}
}, {
key: 'const',
value: function _const(name, cfg) {
var result = new Definition(createConst, name, cfg);
this.define(name, result);
}
}, {
key: 'void',
value: function _void() {
return XDRTypes.Void;
}
}, {
key: 'bool',
value: function bool() {
return XDRTypes.Bool;
}
}, {
key: 'int',
value: function int() {
return XDRTypes.Int;
}
}, {
key: 'hyper',
value: function hyper() {
return XDRTypes.Hyper;
}
}, {
key: 'uint',
value: function uint() {
return XDRTypes.UnsignedInt;
}
}, {
key: 'uhyper',
value: function uhyper() {
return XDRTypes.UnsignedHyper;
}
}, {
key: 'float',
value: function float() {
return XDRTypes.Float;
}
}, {
key: 'double',
value: function double() {
return XDRTypes.Double;
}
}, {
key: 'quadruple',
value: function quadruple() {
return XDRTypes.Quadruple;
}
}, {
key: 'string',
value: function string(length) {
return new SizedReference(XDRTypes.String, length);
}
}, {
key: 'opaque',
value: function opaque(length) {
return new SizedReference(XDRTypes.Opaque, length);
}
}, {
key: 'varOpaque',
value: function varOpaque(length) {
return new SizedReference(XDRTypes.VarOpaque, length);
}
}, {
key: 'array',
value: function array(childType, length) {
return new ArrayReference(childType, length);
}
}, {
key: 'varArray',
value: function varArray(childType, maxLength) {
return new ArrayReference(childType, maxLength, true);
}
}, {
key: 'option',
value: function option(childType) {
return new OptionReference(childType);
}
}, {
key: 'define',
value: function define(name, definition) {
if ((0, _isUndefined2.default)(this._destination[name])) {
this._definitions[name] = definition;
} else {
throw new Error('XDRTypes Error:' + name + ' is already defined');
}
}
}, {
key: 'lookup',
value: function lookup(name) {
return new SimpleReference(name);
}
}, {
key: 'resolve',
value: function resolve() {
var _this5 = this;
(0, _each2.default)(this._definitions, function (defn) {
defn.resolve({
definitions: _this5._definitions,
results: _this5._destination
});
});
}
}]);
return TypeBuilder;
}();
/***/ }),
/* 293 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(52),
arrayEach = __webpack_require__(128),
assignValue = __webpack_require__(106),
baseAssign = __webpack_require__(294),
baseAssignIn = __webpack_require__(295),
cloneBuffer = __webpack_require__(135),
copyArray = __webpack_require__(136),
copySymbols = __webpack_require__(296),
copySymbolsIn = __webpack_require__(297),
getAllKeys = __webpack_require__(117),
getAllKeysIn = __webpack_require__(298),
getTag = __webpack_require__(44),
initCloneArray = __webpack_require__(299),
initCloneByTag = __webpack_require__(300),
initCloneObject = __webpack_require__(139),
isArray = __webpack_require__(3),
isBuffer = __webpack_require__(40),
isMap = __webpack_require__(305),
isObject = __webpack_require__(18),
isSet = __webpack_require__(307),
keys = __webpack_require__(34),
keysIn = __webpack_require__(24);
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag(value),
isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : initCloneObject(value);
if (!isDeep) {
return isFlat
? copySymbolsIn(value, baseAssignIn(result, value))
: copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
if (isSet(value)) {
value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
});
} else if (isMap(value)) {
value.forEach(function(subValue, key) {
result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
}
var keysFunc = isFull
? (isFlat ? getAllKeysIn : getAllKeys)
: (isFlat ? keysIn : keys);
var props = isArr ? undefined : keysFunc(value);
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
module.exports = baseClone;
/***/ }),
/* 294 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(33),
keys = __webpack_require__(34);
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
module.exports = baseAssign;
/***/ }),
/* 295 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(33),
keysIn = __webpack_require__(24);
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && copyObject(source, keysIn(source), object);
}
module.exports = baseAssignIn;
/***/ }),
/* 296 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(33),
getSymbols = __webpack_require__(77);
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return copyObject(source, getSymbols(source), object);
}
module.exports = copySymbols;
/***/ }),
/* 297 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(33),
getSymbolsIn = __webpack_require__(137);
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbolsIn(source, object) {
return copyObject(source, getSymbolsIn(source), object);
}
module.exports = copySymbolsIn;
/***/ }),
/* 298 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetAllKeys = __webpack_require__(118),
getSymbolsIn = __webpack_require__(137),
keysIn = __webpack_require__(24);
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return baseGetAllKeys(object, keysIn, getSymbolsIn);
}
module.exports = getAllKeysIn;
/***/ }),
/* 299 */
/***/ (function(module, exports) {
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = new array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
module.exports = initCloneArray;
/***/ }),
/* 300 */
/***/ (function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(84),
cloneDataView = __webpack_require__(301),
cloneRegExp = __webpack_require__(302),
cloneSymbol = __webpack_require__(303),
cloneTypedArray = __webpack_require__(138);
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
mapTag = '[object Map]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return cloneArrayBuffer(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case dataViewTag:
return cloneDataView(object, isDeep);
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
return cloneTypedArray(object, isDeep);
case mapTag:
return new Ctor;
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
return cloneRegExp(object);
case setTag:
return new Ctor;
case symbolTag:
return cloneSymbol(object);
}
}
module.exports = initCloneByTag;
/***/ }),
/* 301 */
/***/ (function(module, exports, __webpack_require__) {
var cloneArrayBuffer = __webpack_require__(84);
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
module.exports = cloneDataView;
/***/ }),
/* 302 */
/***/ (function(module, exports) {
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
module.exports = cloneRegExp;
/***/ }),
/* 303 */
/***/ (function(module, exports, __webpack_require__) {
var Symbol = __webpack_require__(39);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
module.exports = cloneSymbol;
/***/ }),
/* 304 */
/***/ (function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(18);
/** Built-in value references. */
var objectCreate = Object.create;
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
module.exports = baseCreate;
/***/ }),
/* 305 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsMap = __webpack_require__(306),
baseUnary = __webpack_require__(70),
nodeUtil = __webpack_require__(71);
/* Node.js helper references. */
var nodeIsMap = nodeUtil && nodeUtil.isMap;
/**
* Checks if `value` is classified as a `Map` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
* @example
*
* _.isMap(new Map);
* // => true
*
* _.isMap(new WeakMap);
* // => false
*/
var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
module.exports = isMap;
/***/ }),
/* 306 */
/***/ (function(module, exports, __webpack_require__) {
var getTag = __webpack_require__(44),
isObjectLike = __webpack_require__(12);
/** `Object#toString` result references. */
var mapTag = '[object Map]';
/**
* The base implementation of `_.isMap` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
*/
function baseIsMap(value) {
return isObjectLike(value) && getTag(value) == mapTag;
}
module.exports = baseIsMap;
/***/ }),
/* 307 */
/***/ (function(module, exports, __webpack_require__) {
var baseIsSet = __webpack_require__(308),
baseUnary = __webpack_require__(70),
nodeUtil = __webpack_require__(71);
/* Node.js helper references. */
var nodeIsSet = nodeUtil && nodeUtil.isSet;
/**
* Checks if `value` is classified as a `Set` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
* @example
*
* _.isSet(new Set);
* // => true
*
* _.isSet(new WeakSet);
* // => false
*/
var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
module.exports = isSet;
/***/ }),
/* 308 */
/***/ (function(module, exports, __webpack_require__) {
var getTag = __webpack_require__(44),
isObjectLike = __webpack_require__(12);
/** `Object#toString` result references. */
var setTag = '[object Set]';
/**
* The base implementation of `_.isSet` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
*/
function baseIsSet(value) {
return isObjectLike(value) && getTag(value) == setTag;
}
module.exports = baseIsSet;
/***/ }),
/* 309 */
/***/ (function(module, exports, __webpack_require__) {
var baseRepeat = __webpack_require__(310),
baseToString = __webpack_require__(80),
castSlice = __webpack_require__(141),
hasUnicode = __webpack_require__(85),
stringSize = __webpack_require__(142),
stringToArray = __webpack_require__(143);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil;
/**
* Creates the padding for `string` based on `length`. The `chars` string
* is truncated if the number of characters exceeds `length`.
*
* @private
* @param {number} length The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padding for `string`.
*/
function createPadding(length, chars) {
chars = chars === undefined ? ' ' : baseToString(chars);
var charsLength = chars.length;
if (charsLength < 2) {
return charsLength ? baseRepeat(chars, length) : chars;
}
var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
return hasUnicode(chars)
? castSlice(stringToArray(result), 0, length).join('')
: result.slice(0, length);
}
module.exports = createPadding;
/***/ }),
/* 310 */
/***/ (function(module, exports) {
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeFloor = Math.floor;
/**
* The base implementation of `_.repeat` which doesn't coerce arguments.
*
* @private
* @param {string} string The string to repeat.
* @param {number} n The number of times to repeat the string.
* @returns {string} Returns the repeated string.
*/
function baseRepeat(string, n) {
var result = '';
if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
return result;
}
// Leverage the exponentiation by squaring algorithm for a faster repeat.
// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
do {
if (n % 2) {
result += string;
}
n = nativeFloor(n / 2);
if (n) {
string += string;
}
} while (n);
return result;
}
module.exports = baseRepeat;
/***/ }),
/* 311 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
module.exports = baseSlice;
/***/ }),
/* 312 */
/***/ (function(module, exports, __webpack_require__) {
var baseProperty = __webpack_require__(125);
/**
* Gets the size of an ASCII `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
*/
var asciiSize = baseProperty('length');
module.exports = asciiSize;
/***/ }),
/* 313 */
/***/ (function(module, exports) {
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsAstral = '[' + rsAstralRange + ']',
rsCombo = '[' + rsComboRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/**
* Gets the size of a Unicode `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
*/
function unicodeSize(string) {
var result = reUnicode.lastIndex = 0;
while (reUnicode.test(string)) {
++result;
}
return result;
}
module.exports = unicodeSize;
/***/ }),
/* 314 */
/***/ (function(module, exports) {
/**
* Converts an ASCII `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function asciiToArray(string) {
return string.split('');
}
module.exports = asciiToArray;
/***/ }),
/* 315 */
/***/ (function(module, exports) {
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsVarRange = '\\ufe0e\\ufe0f';
/** Used to compose unicode capture groups. */
var rsAstral = '[' + rsAstralRange + ']',
rsCombo = '[' + rsComboRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/**
* Converts a Unicode `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function unicodeToArray(string) {
return string.match(reUnicode) || [];
}
module.exports = unicodeToArray;
/***/ }),
/* 316 */
/***/ (function(module, exports, __webpack_require__) {
var baseIndexOf = __webpack_require__(317);
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the last unmatched string symbol.
*/
function charsEndIndex(strSymbols, chrSymbols) {
var index = strSymbols.length;
while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
module.exports = charsEndIndex;
/***/ }),
/* 317 */
/***/ (function(module, exports, __webpack_require__) {
var baseFindIndex = __webpack_require__(318),
baseIsNaN = __webpack_require__(319),
strictIndexOf = __webpack_require__(320);
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
return value === value
? strictIndexOf(array, value, fromIndex)
: baseFindIndex(array, baseIsNaN, fromIndex);
}
module.exports = baseIndexOf;
/***/ }),
/* 318 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
module.exports = baseFindIndex;
/***/ }),
/* 319 */
/***/ (function(module, exports) {
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
module.exports = baseIsNaN;
/***/ }),
/* 320 */
/***/ (function(module, exports) {
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
module.exports = strictIndexOf;
/***/ }),
/* 321 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Generate a character map.
* @param {string} alphabet e.g. "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
* @param {object} mappings map overrides from key to value
* @method
*/
var charmap = function (alphabet, mappings) {
mappings || (mappings = {});
alphabet.split("").forEach(function (c, i) {
if (!(c in mappings)) mappings[c] = i;
});
return mappings;
}
/**
* The RFC 4648 base 32 alphabet and character map.
* @see {@link https://tools.ietf.org/html/rfc4648}
*/
var rfc4648 = {
alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
charmap: {
0: 14,
1: 8
}
};
rfc4648.charmap = charmap(rfc4648.alphabet, rfc4648.charmap);
/**
* The Crockford base 32 alphabet and character map.
* @see {@link http://www.crockford.com/wrmg/base32.html}
*/
var crockford = {
alphabet: "0123456789ABCDEFGHJKMNPQRSTVWXYZ",
charmap: {
O: 0,
I: 1,
L: 1
}
};
crockford.charmap = charmap(crockford.alphabet, crockford.charmap);
/**
* base32hex
* @see {@link https://en.wikipedia.org/wiki/Base32#base32hex}
*/
var base32hex = {
alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV",
charmap: {}
};
base32hex.charmap = charmap(base32hex.alphabet, base32hex.charmap);
/**
* Create a new `Decoder` with the given options.
*
* @param {object} [options]
* @param {string} [type] Supported Base-32 variants are "rfc4648" and
* "crockford".
* @param {object} [charmap] Override the character map used in decoding.
* @constructor
*/
function Decoder (options) {
this.buf = [];
this.shift = 8;
this.carry = 0;
if (options) {
switch (options.type) {
case "rfc4648":
this.charmap = exports.rfc4648.charmap;
break;
case "crockford":
this.charmap = exports.crockford.charmap;
break;
case "base32hex":
this.charmap = exports.base32hex.charmap;
break;
default:
throw new Error("invalid type");
}
if (options.charmap) this.charmap = options.charmap;
}
}
/**
* The default character map coresponds to RFC4648.
*/
Decoder.prototype.charmap = rfc4648.charmap;
/**
* Decode a string, continuing from the previous state.
*
* @param {string} str
* @return {Decoder} this
*/
Decoder.prototype.write = function (str) {
var charmap = this.charmap;
var buf = this.buf;
var shift = this.shift;
var carry = this.carry;
// decode string
str.toUpperCase().split("").forEach(function (char) {
// ignore padding
if (char == "=") return;
// lookup symbol
var symbol = charmap[char] & 0xff;
// 1: 00000 000
// 2: 00 00000 0
// 3: 0000 0000
// 4: 0 00000 00
// 5: 000 00000
// 6: 00000 000
// 7: 00 00000 0
shift -= 5;
if (shift > 0) {
carry |= symbol << shift;
} else if (shift < 0) {
buf.push(carry | (symbol >> -shift));
shift += 8;
carry = (symbol << shift) & 0xff;
} else {
buf.push(carry | symbol);
shift = 8;
carry = 0;
}
});
// save state
this.shift = shift;
this.carry = carry;
// for chaining
return this;
};
/**
* Finish decoding.
*
* @param {string} [str] The final string to decode.
* @return {Array} Decoded byte array.
*/
Decoder.prototype.finalize = function (str) {
if (str) {
this.write(str);
}
if (this.shift !== 8 && this.carry !== 0) {
this.buf.push(this.carry);
this.shift = 8;
this.carry = 0;
}
return this.buf;
};
/**
* Create a new `Encoder` with the given options.
*
* @param {object} [options]
* @param {string} [type] Supported Base-32 variants are "rfc4648" and
* "crockford".
* @param {object} [alphabet] Override the alphabet used in encoding.
* @constructor
*/
function Encoder (options) {
this.buf = "";
this.shift = 3;
this.carry = 0;
if (options) {
switch (options.type) {
case "rfc4648":
this.alphabet = exports.rfc4648.alphabet;
break;
case "crockford":
this.alphabet = exports.crockford.alphabet;
break;
case "base32hex":
this.alphabet = exports.base32hex.alphabet;
break;
default:
throw new Error("invalid type");
}
if (options.alphabet) this.alphabet = options.alphabet;
else if (options.lc) this.alphabet = this.alphabet.toLowerCase();
}
}
/**
* The default alphabet coresponds to RFC4648.
*/
Encoder.prototype.alphabet = rfc4648.alphabet;
/**
* Encode a byte array, continuing from the previous state.
*
* @param {byte[]} buf The byte array to encode.
* @return {Encoder} this
*/
Encoder.prototype.write = function (buf) {
var shift = this.shift;
var carry = this.carry;
var symbol;
var byte;
var i;
// encode each byte in buf
for (i = 0; i < buf.length; i++) {
byte = buf[i];
// 1: 00000 000
// 2: 00 00000 0
// 3: 0000 0000
// 4: 0 00000 00
// 5: 000 00000
// 6: 00000 000
// 7: 00 00000 0
symbol = carry | (byte >> shift);
this.buf += this.alphabet[symbol & 0x1f];
if (shift > 5) {
shift -= 5;
symbol = byte >> shift;
this.buf += this.alphabet[symbol & 0x1f];
}
shift = 5 - shift;
carry = byte << shift;
shift = 8 - shift;
}
// save state
this.shift = shift;
this.carry = carry;
// for chaining
return this;
};
/**
* Finish encoding.
*
* @param {byte[]} [buf] The final byte array to encode.
* @return {string} The encoded byte array.
*/
Encoder.prototype.finalize = function (buf) {
if (buf) {
this.write(buf);
}
if (this.shift !== 3) {
this.buf += this.alphabet[this.carry & 0x1f];
this.shift = 3;
this.carry = 0;
}
return this.buf;
};
/**
* Convenience encoder.
*
* @param {byte[]} buf The byte array to encode.
* @param {object} [options] Options to pass to the encoder.
* @return {string} The encoded string.
*/
exports.encode = function (buf, options) {
return new Encoder(options).finalize(buf);
};
/**
* Convenience decoder.
*
* @param {string} str The string to decode.
* @param {object} [options] Options to pass to the decoder.
* @return {byte[]} The decoded byte array.
*/
exports.decode = function (str, options) {
return new Decoder(options).finalize(str);
};
// Exports.
exports.Decoder = Decoder;
exports.Encoder = Encoder;
exports.charmap = charmap;
exports.crockford = crockford;
exports.rfc4648 = rfc4648;
exports.base32hex = base32hex;
/***/ }),
/* 322 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.crcjam = exports.crc32 = exports.crc24 = exports.crc16kermit = exports.crc16xmodem = exports.crc16modbus = exports.crc16ccitt = exports.crc16 = exports.crc81wire = exports.crc8 = exports.crc1 = undefined;
var _crc = __webpack_require__(323);
var _crc2 = _interopRequireDefault(_crc);
var _crc3 = __webpack_require__(324);
var _crc4 = _interopRequireDefault(_crc3);
var _crc81wire = __webpack_require__(325);
var _crc81wire2 = _interopRequireDefault(_crc81wire);
var _crc5 = __webpack_require__(326);
var _crc6 = _interopRequireDefault(_crc5);
var _crc16ccitt = __webpack_require__(327);
var _crc16ccitt2 = _interopRequireDefault(_crc16ccitt);
var _crc16modbus = __webpack_require__(328);
var _crc16modbus2 = _interopRequireDefault(_crc16modbus);
var _crc16xmodem = __webpack_require__(329);
var _crc16xmodem2 = _interopRequireDefault(_crc16xmodem);
var _crc16kermit = __webpack_require__(330);
var _crc16kermit2 = _interopRequireDefault(_crc16kermit);
var _crc7 = __webpack_require__(331);
var _crc8 = _interopRequireDefault(_crc7);
var _crc9 = __webpack_require__(332);
var _crc10 = _interopRequireDefault(_crc9);
var _crcjam = __webpack_require__(333);
var _crcjam2 = _interopRequireDefault(_crcjam);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.crc1 = _crc2.default;
exports.crc8 = _crc4.default;
exports.crc81wire = _crc81wire2.default;
exports.crc16 = _crc6.default;
exports.crc16ccitt = _crc16ccitt2.default;
exports.crc16modbus = _crc16modbus2.default;
exports.crc16xmodem = _crc16xmodem2.default;
exports.crc16kermit = _crc16kermit2.default;
exports.crc24 = _crc8.default;
exports.crc32 = _crc10.default;
exports.crcjam = _crcjam2.default;
exports.default = {
crc1: _crc2.default,
crc8: _crc4.default,
crc81wire: _crc81wire2.default,
crc16: _crc6.default,
crc16ccitt: _crc16ccitt2.default,
crc16modbus: _crc16modbus2.default,
crc16xmodem: _crc16xmodem2.default,
crc16kermit: _crc16kermit2.default,
crc24: _crc8.default,
crc32: _crc10.default,
crcjam: _crcjam2.default
};
/***/ }),
/* 323 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _buffer = __webpack_require__(1);
var _create_buffer = __webpack_require__(15);
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = __webpack_require__(16);
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var crc1 = (0, _define_crc2.default)('crc1', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = ~~previous;
var accum = 0;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
accum += byte;
}
crc += accum % 256;
return crc % 256;
});
exports.default = crc1;
/***/ }),
/* 324 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _buffer = __webpack_require__(1);
var _create_buffer = __webpack_require__(15);
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = __webpack_require__(16);
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-driven --model=crc-8 --generate=c`
// prettier-ignore
var TABLE = [0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65, 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53, 0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd, 0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0, 0xc9, 0xce, 0xdb, 0xdc, 0xd5, 0xd2, 0xff, 0xf8, 0xf1, 0xf6, 0xe3, 0xe4, 0xed, 0xea, 0xb7, 0xb0, 0xb9, 0xbe, 0xab, 0xac, 0xa5, 0xa2, 0x8f, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9d, 0x9a, 0x27, 0x20, 0x29, 0x2e, 0x3b, 0x3c, 0x35, 0x32, 0x1f, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0d, 0x0a, 0x57, 0x50, 0x59, 0x5e, 0x4b, 0x4c, 0x45, 0x42, 0x6f, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7d, 0x7a, 0x89, 0x8e, 0x87, 0x80, 0x95, 0x92, 0x9b, 0x9c, 0xb1, 0xb6, 0xbf, 0xb8, 0xad, 0xaa, 0xa3, 0xa4, 0xf9, 0xfe, 0xf7, 0xf0, 0xe5, 0xe2, 0xeb, 0xec, 0xc1, 0xc6, 0xcf, 0xc8, 0xdd, 0xda, 0xd3, 0xd4, 0x69, 0x6e, 0x67, 0x60, 0x75, 0x72, 0x7b, 0x7c, 0x51, 0x56, 0x5f, 0x58, 0x4d, 0x4a, 0x43, 0x44, 0x19, 0x1e, 0x17, 0x10, 0x05, 0x02, 0x0b, 0x0c, 0x21, 0x26, 0x2f, 0x28, 0x3d, 0x3a, 0x33, 0x34, 0x4e, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5c, 0x5b, 0x76, 0x71, 0x78, 0x7f, 0x6a, 0x6d, 0x64, 0x63, 0x3e, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2c, 0x2b, 0x06, 0x01, 0x08, 0x0f, 0x1a, 0x1d, 0x14, 0x13, 0xae, 0xa9, 0xa0, 0xa7, 0xb2, 0xb5, 0xbc, 0xbb, 0x96, 0x91, 0x98, 0x9f, 0x8a, 0x8d, 0x84, 0x83, 0xde, 0xd9, 0xd0, 0xd7, 0xc2, 0xc5, 0xcc, 0xcb, 0xe6, 0xe1, 0xe8, 0xef, 0xfa, 0xfd, 0xf4, 0xf3];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
var crc8 = (0, _define_crc2.default)('crc-8', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = ~~previous;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = TABLE[(crc ^ byte) & 0xff] & 0xff;
}
return crc;
});
exports.default = crc8;
/***/ }),
/* 325 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _buffer = __webpack_require__(1);
var _create_buffer = __webpack_require__(15);
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = __webpack_require__(16);
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-driven --model=dallas-1-wire --generate=c`
// prettier-ignore
var TABLE = [0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83, 0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41, 0x9d, 0xc3, 0x21, 0x7f, 0xfc, 0xa2, 0x40, 0x1e, 0x5f, 0x01, 0xe3, 0xbd, 0x3e, 0x60, 0x82, 0xdc, 0x23, 0x7d, 0x9f, 0xc1, 0x42, 0x1c, 0xfe, 0xa0, 0xe1, 0xbf, 0x5d, 0x03, 0x80, 0xde, 0x3c, 0x62, 0xbe, 0xe0, 0x02, 0x5c, 0xdf, 0x81, 0x63, 0x3d, 0x7c, 0x22, 0xc0, 0x9e, 0x1d, 0x43, 0xa1, 0xff, 0x46, 0x18, 0xfa, 0xa4, 0x27, 0x79, 0x9b, 0xc5, 0x84, 0xda, 0x38, 0x66, 0xe5, 0xbb, 0x59, 0x07, 0xdb, 0x85, 0x67, 0x39, 0xba, 0xe4, 0x06, 0x58, 0x19, 0x47, 0xa5, 0xfb, 0x78, 0x26, 0xc4, 0x9a, 0x65, 0x3b, 0xd9, 0x87, 0x04, 0x5a, 0xb8, 0xe6, 0xa7, 0xf9, 0x1b, 0x45, 0xc6, 0x98, 0x7a, 0x24, 0xf8, 0xa6, 0x44, 0x1a, 0x99, 0xc7, 0x25, 0x7b, 0x3a, 0x64, 0x86, 0xd8, 0x5b, 0x05, 0xe7, 0xb9, 0x8c, 0xd2, 0x30, 0x6e, 0xed, 0xb3, 0x51, 0x0f, 0x4e, 0x10, 0xf2, 0xac, 0x2f, 0x71, 0x93, 0xcd, 0x11, 0x4f, 0xad, 0xf3, 0x70, 0x2e, 0xcc, 0x92, 0xd3, 0x8d, 0x6f, 0x31, 0xb2, 0xec, 0x0e, 0x50, 0xaf, 0xf1, 0x13, 0x4d, 0xce, 0x90, 0x72, 0x2c, 0x6d, 0x33, 0xd1, 0x8f, 0x0c, 0x52, 0xb0, 0xee, 0x32, 0x6c, 0x8e, 0xd0, 0x53, 0x0d, 0xef, 0xb1, 0xf0, 0xae, 0x4c, 0x12, 0x91, 0xcf, 0x2d, 0x73, 0xca, 0x94, 0x76, 0x28, 0xab, 0xf5, 0x17, 0x49, 0x08, 0x56, 0xb4, 0xea, 0x69, 0x37, 0xd5, 0x8b, 0x57, 0x09, 0xeb, 0xb5, 0x36, 0x68, 0x8a, 0xd4, 0x95, 0xcb, 0x29, 0x77, 0xf4, 0xaa, 0x48, 0x16, 0xe9, 0xb7, 0x55, 0x0b, 0x88, 0xd6, 0x34, 0x6a, 0x2b, 0x75, 0x97, 0xc9, 0x4a, 0x14, 0xf6, 0xa8, 0x74, 0x2a, 0xc8, 0x96, 0x15, 0x4b, 0xa9, 0xf7, 0xb6, 0xe8, 0x0a, 0x54, 0xd7, 0x89, 0x6b, 0x35];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
var crc81wire = (0, _define_crc2.default)('dallas-1-wire', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = ~~previous;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = TABLE[(crc ^ byte) & 0xff] & 0xff;
}
return crc;
});
exports.default = crc81wire;
/***/ }),
/* 326 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _buffer = __webpack_require__(1);
var _create_buffer = __webpack_require__(15);
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = __webpack_require__(16);
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-driven --model=crc-16 --generate=c`
// prettier-ignore
var TABLE = [0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
var crc16 = (0, _define_crc2.default)('crc-16', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = ~~previous;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = (TABLE[(crc ^ byte) & 0xff] ^ crc >> 8) & 0xffff;
}
return crc;
});
exports.default = crc16;
/***/ }),
/* 327 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _buffer = __webpack_require__(1);
var _create_buffer = __webpack_require__(15);
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = __webpack_require__(16);
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-driven --model=ccitt --generate=c`
// prettier-ignore
var TABLE = [0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
var crc16ccitt = (0, _define_crc2.default)('ccitt', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = typeof previous !== 'undefined' ? ~~previous : 0xffff;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = (TABLE[(crc >> 8 ^ byte) & 0xff] ^ crc << 8) & 0xffff;
}
return crc;
});
exports.default = crc16ccitt;
/***/ }),
/* 328 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _buffer = __webpack_require__(1);
var _create_buffer = __webpack_require__(15);
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = __webpack_require__(16);
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-driven --model=crc-16-modbus --generate=c`
// prettier-ignore
var TABLE = [0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
var crc16modbus = (0, _define_crc2.default)('crc-16-modbus', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = typeof previous !== 'undefined' ? ~~previous : 0xffff;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = (TABLE[(crc ^ byte) & 0xff] ^ crc >> 8) & 0xffff;
}
return crc;
});
exports.default = crc16modbus;
/***/ }),
/* 329 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _buffer = __webpack_require__(1);
var _create_buffer = __webpack_require__(15);
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = __webpack_require__(16);
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var crc16xmodem = (0, _define_crc2.default)('xmodem', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = typeof previous !== 'undefined' ? ~~previous : 0x0;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
var code = crc >>> 8 & 0xff;
code ^= byte & 0xff;
code ^= code >>> 4;
crc = crc << 8 & 0xffff;
crc ^= code;
code = code << 5 & 0xffff;
crc ^= code;
code = code << 7 & 0xffff;
crc ^= code;
}
return crc;
});
exports.default = crc16xmodem;
/***/ }),
/* 330 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _buffer = __webpack_require__(1);
var _create_buffer = __webpack_require__(15);
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = __webpack_require__(16);
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-driven --model=kermit --generate=c`
// prettier-ignore
var TABLE = [0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
var crc16kermit = (0, _define_crc2.default)('kermit', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = typeof previous !== 'undefined' ? ~~previous : 0x0000;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = (TABLE[(crc ^ byte) & 0xff] ^ crc >> 8) & 0xffff;
}
return crc;
});
exports.default = crc16kermit;
/***/ }),
/* 331 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _buffer = __webpack_require__(1);
var _create_buffer = __webpack_require__(15);
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = __webpack_require__(16);
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-drive --model=crc-24 --generate=c`
// prettier-ignore
var TABLE = [0x000000, 0x864cfb, 0x8ad50d, 0x0c99f6, 0x93e6e1, 0x15aa1a, 0x1933ec, 0x9f7f17, 0xa18139, 0x27cdc2, 0x2b5434, 0xad18cf, 0x3267d8, 0xb42b23, 0xb8b2d5, 0x3efe2e, 0xc54e89, 0x430272, 0x4f9b84, 0xc9d77f, 0x56a868, 0xd0e493, 0xdc7d65, 0x5a319e, 0x64cfb0, 0xe2834b, 0xee1abd, 0x685646, 0xf72951, 0x7165aa, 0x7dfc5c, 0xfbb0a7, 0x0cd1e9, 0x8a9d12, 0x8604e4, 0x00481f, 0x9f3708, 0x197bf3, 0x15e205, 0x93aefe, 0xad50d0, 0x2b1c2b, 0x2785dd, 0xa1c926, 0x3eb631, 0xb8faca, 0xb4633c, 0x322fc7, 0xc99f60, 0x4fd39b, 0x434a6d, 0xc50696, 0x5a7981, 0xdc357a, 0xd0ac8c, 0x56e077, 0x681e59, 0xee52a2, 0xe2cb54, 0x6487af, 0xfbf8b8, 0x7db443, 0x712db5, 0xf7614e, 0x19a3d2, 0x9fef29, 0x9376df, 0x153a24, 0x8a4533, 0x0c09c8, 0x00903e, 0x86dcc5, 0xb822eb, 0x3e6e10, 0x32f7e6, 0xb4bb1d, 0x2bc40a, 0xad88f1, 0xa11107, 0x275dfc, 0xdced5b, 0x5aa1a0, 0x563856, 0xd074ad, 0x4f0bba, 0xc94741, 0xc5deb7, 0x43924c, 0x7d6c62, 0xfb2099, 0xf7b96f, 0x71f594, 0xee8a83, 0x68c678, 0x645f8e, 0xe21375, 0x15723b, 0x933ec0, 0x9fa736, 0x19ebcd, 0x8694da, 0x00d821, 0x0c41d7, 0x8a0d2c, 0xb4f302, 0x32bff9, 0x3e260f, 0xb86af4, 0x2715e3, 0xa15918, 0xadc0ee, 0x2b8c15, 0xd03cb2, 0x567049, 0x5ae9bf, 0xdca544, 0x43da53, 0xc596a8, 0xc90f5e, 0x4f43a5, 0x71bd8b, 0xf7f170, 0xfb6886, 0x7d247d, 0xe25b6a, 0x641791, 0x688e67, 0xeec29c, 0x3347a4, 0xb50b5f, 0xb992a9, 0x3fde52, 0xa0a145, 0x26edbe, 0x2a7448, 0xac38b3, 0x92c69d, 0x148a66, 0x181390, 0x9e5f6b, 0x01207c, 0x876c87, 0x8bf571, 0x0db98a, 0xf6092d, 0x7045d6, 0x7cdc20, 0xfa90db, 0x65efcc, 0xe3a337, 0xef3ac1, 0x69763a, 0x578814, 0xd1c4ef, 0xdd5d19, 0x5b11e2, 0xc46ef5, 0x42220e, 0x4ebbf8, 0xc8f703, 0x3f964d, 0xb9dab6, 0xb54340, 0x330fbb, 0xac70ac, 0x2a3c57, 0x26a5a1, 0xa0e95a, 0x9e1774, 0x185b8f, 0x14c279, 0x928e82, 0x0df195, 0x8bbd6e, 0x872498, 0x016863, 0xfad8c4, 0x7c943f, 0x700dc9, 0xf64132, 0x693e25, 0xef72de, 0xe3eb28, 0x65a7d3, 0x5b59fd, 0xdd1506, 0xd18cf0, 0x57c00b, 0xc8bf1c, 0x4ef3e7, 0x426a11, 0xc426ea, 0x2ae476, 0xaca88d, 0xa0317b, 0x267d80, 0xb90297, 0x3f4e6c, 0x33d79a, 0xb59b61, 0x8b654f, 0x0d29b4, 0x01b042, 0x87fcb9, 0x1883ae, 0x9ecf55, 0x9256a3, 0x141a58, 0xefaaff, 0x69e604, 0x657ff2, 0xe33309, 0x7c4c1e, 0xfa00e5, 0xf69913, 0x70d5e8, 0x4e2bc6, 0xc8673d, 0xc4fecb, 0x42b230, 0xddcd27, 0x5b81dc, 0x57182a, 0xd154d1, 0x26359f, 0xa07964, 0xace092, 0x2aac69, 0xb5d37e, 0x339f85, 0x3f0673, 0xb94a88, 0x87b4a6, 0x01f85d, 0x0d61ab, 0x8b2d50, 0x145247, 0x921ebc, 0x9e874a, 0x18cbb1, 0xe37b16, 0x6537ed, 0x69ae1b, 0xefe2e0, 0x709df7, 0xf6d10c, 0xfa48fa, 0x7c0401, 0x42fa2f, 0xc4b6d4, 0xc82f22, 0x4e63d9, 0xd11cce, 0x575035, 0x5bc9c3, 0xdd8538];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
var crc24 = (0, _define_crc2.default)('crc-24', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = typeof previous !== 'undefined' ? ~~previous : 0xb704ce;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = (TABLE[(crc >> 16 ^ byte) & 0xff] ^ crc << 8) & 0xffffff;
}
return crc;
});
exports.default = crc24;
/***/ }),
/* 332 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _buffer = __webpack_require__(1);
var _create_buffer = __webpack_require__(15);
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = __webpack_require__(16);
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-driven --model=crc-32 --generate=c`
// prettier-ignore
var TABLE = [0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
var crc32 = (0, _define_crc2.default)('crc-32', function (buf, previous) {
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = previous === 0 ? 0 : ~~previous ^ -1;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = TABLE[(crc ^ byte) & 0xff] ^ crc >>> 8;
}
return crc ^ -1;
});
exports.default = crc32;
/***/ }),
/* 333 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _buffer = __webpack_require__(1);
var _create_buffer = __webpack_require__(15);
var _create_buffer2 = _interopRequireDefault(_create_buffer);
var _define_crc = __webpack_require__(16);
var _define_crc2 = _interopRequireDefault(_define_crc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// Generated by `./pycrc.py --algorithm=table-driven --model=jam --generate=c`
// prettier-ignore
var TABLE = [0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d];
if (typeof Int32Array !== 'undefined') TABLE = new Int32Array(TABLE);
var crcjam = (0, _define_crc2.default)('jam', function (buf) {
var previous = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : -1;
if (!_buffer.Buffer.isBuffer(buf)) buf = (0, _create_buffer2.default)(buf);
var crc = previous === 0 ? 0 : ~~previous;
for (var index = 0; index < buf.length; index++) {
var byte = buf[index];
crc = TABLE[(crc ^ byte) & 0xff] ^ crc >>> 8;
}
return crc;
});
exports.default = crcjam;
/***/ }),
/* 334 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.verifyChecksum = verifyChecksum;
function verifyChecksum(expected, actual) {
if (expected.length !== actual.length) {
return false;
}
if (expected.length === 0) {
return true;
}
for (var i = 0; i < expected.length; i += 1) {
if (expected[i] !== actual[i]) {
return false;
}
}
return true;
}
/***/ }),
/* 335 */
/***/ (function(module, exports, __webpack_require__) {
var root = __webpack_require__(14);
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeIsFinite = root.isFinite;
/**
* Checks if `value` is a finite primitive number.
*
* **Note:** This method is based on
* [`Number.isFinite`](https://mdn.io/Number/isFinite).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
* @example
*
* _.isFinite(3);
* // => true
*
* _.isFinite(Number.MIN_VALUE);
* // => true
*
* _.isFinite(Infinity);
* // => false
*
* _.isFinite('3');
* // => false
*/
function isFinite(value) {
return typeof value == 'number' && nativeIsFinite(value);
}
module.exports = isFinite;
/***/ }),
/* 336 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
exports.best_r = best_r;
var _bignumber = __webpack_require__(23);
var _bignumber2 = _interopRequireDefault(_bignumber);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// eslint-disable-next-line no-bitwise
var MAX_INT = (1 << 31 >>> 0) - 1;
/**
* Calculates and returns the best rational approximation of the given real number.
* @private
* @param {string|number|BigNumber} rawNumber Real number
* @throws Error Throws `Error` when the best rational approximation cannot be found.
* @returns {array} first element is n (numerator), second element is d (denominator)
*/
function best_r(rawNumber) {
var number = new _bignumber2.default(rawNumber);
var a = void 0;
var f = void 0;
var fractions = [[new _bignumber2.default(0), new _bignumber2.default(1)], [new _bignumber2.default(1), new _bignumber2.default(0)]];
var i = 2;
// eslint-disable-next-line no-constant-condition
while (true) {
if (number.gt(MAX_INT)) {
break;
}
a = number.floor();
f = number.sub(a);
var h = a.mul(fractions[i - 1][0]).add(fractions[i - 2][0]);
var k = a.mul(fractions[i - 1][1]).add(fractions[i - 2][1]);
if (h.gt(MAX_INT) || k.gt(MAX_INT)) {
break;
}
fractions.push([h, k]);
if (f.eq(0)) {
break;
}
number = new _bignumber2.default(1).div(f);
i += 1;
}
var _fractions = _slicedToArray(fractions[fractions.length - 1], 2),
n = _fractions[0],
d = _fractions[1];
if (n.isZero() || d.isZero()) {
throw new Error("Couldn't find approximation");
}
return [n.toNumber(), d.toNumber()];
}
/***/ }),
/* 337 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _manage_sell_offer = __webpack_require__(338);
Object.defineProperty(exports, 'manageSellOffer', {
enumerable: true,
get: function get() {
return _manage_sell_offer.manageSellOffer;
}
});
var _create_passive_sell_offer = __webpack_require__(339);
Object.defineProperty(exports, 'createPassiveSellOffer', {
enumerable: true,
get: function get() {
return _create_passive_sell_offer.createPassiveSellOffer;
}
});
var _account_merge = __webpack_require__(340);
Object.defineProperty(exports, 'accountMerge', {
enumerable: true,
get: function get() {
return _account_merge.accountMerge;
}
});
var _allow_trust = __webpack_require__(341);
Object.defineProperty(exports, 'allowTrust', {
enumerable: true,
get: function get() {
return _allow_trust.allowTrust;
}
});
var _bump_sequence = __webpack_require__(342);
Object.defineProperty(exports, 'bumpSequence', {
enumerable: true,
get: function get() {
return _bump_sequence.bumpSequence;
}
});
var _change_trust = __webpack_require__(343);
Object.defineProperty(exports, 'changeTrust', {
enumerable: true,
get: function get() {
return _change_trust.changeTrust;
}
});
var _create_account = __webpack_require__(344);
Object.defineProperty(exports, 'createAccount', {
enumerable: true,
get: function get() {
return _create_account.createAccount;
}
});
var _create_claimable_balance = __webpack_require__(345);
Object.defineProperty(exports, 'createClaimableBalance', {
enumerable: true,
get: function get() {
return _create_claimable_balance.createClaimableBalance;
}
});
var _claim_claimable_balance = __webpack_require__(147);
Object.defineProperty(exports, 'claimClaimableBalance', {
enumerable: true,
get: function get() {
return _claim_claimable_balance.claimClaimableBalance;
}
});
var _clawback_claimable_balance = __webpack_require__(346);
Object.defineProperty(exports, 'clawbackClaimableBalance', {
enumerable: true,
get: function get() {
return _clawback_claimable_balance.clawbackClaimableBalance;
}
});
var _inflation = __webpack_require__(347);
Object.defineProperty(exports, 'inflation', {
enumerable: true,
get: function get() {
return _inflation.inflation;
}
});
var _manage_data = __webpack_require__(348);
Object.defineProperty(exports, 'manageData', {
enumerable: true,
get: function get() {
return _manage_data.manageData;
}
});
var _manage_buy_offer = __webpack_require__(349);
Object.defineProperty(exports, 'manageBuyOffer', {
enumerable: true,
get: function get() {
return _manage_buy_offer.manageBuyOffer;
}
});
var _path_payment_strict_receive = __webpack_require__(350);
Object.defineProperty(exports, 'pathPaymentStrictReceive', {
enumerable: true,
get: function get() {
return _path_payment_strict_receive.pathPaymentStrictReceive;
}
});
var _path_payment_strict_send = __webpack_require__(351);
Object.defineProperty(exports, 'pathPaymentStrictSend', {
enumerable: true,
get: function get() {
return _path_payment_strict_send.pathPaymentStrictSend;
}
});
var _payment = __webpack_require__(352);
Object.defineProperty(exports, 'payment', {
enumerable: true,
get: function get() {
return _payment.payment;
}
});
var _set_options = __webpack_require__(353);
Object.defineProperty(exports, 'setOptions', {
enumerable: true,
get: function get() {
return _set_options.setOptions;
}
});
var _begin_sponsoring_future_reserves = __webpack_require__(354);
Object.defineProperty(exports, 'beginSponsoringFutureReserves', {
enumerable: true,
get: function get() {
return _begin_sponsoring_future_reserves.beginSponsoringFutureReserves;
}
});
var _end_sponsoring_future_reserves = __webpack_require__(355);
Object.defineProperty(exports, 'endSponsoringFutureReserves', {
enumerable: true,
get: function get() {
return _end_sponsoring_future_reserves.endSponsoringFutureReserves;
}
});
var _revoke_sponsorship = __webpack_require__(356);
Object.defineProperty(exports, 'revokeAccountSponsorship', {
enumerable: true,
get: function get() {
return _revoke_sponsorship.revokeAccountSponsorship;
}
});
Object.defineProperty(exports, 'revokeTrustlineSponsorship', {
enumerable: true,
get: function get() {
return _revoke_sponsorship.revokeTrustlineSponsorship;
}
});
Object.defineProperty(exports, 'revokeOfferSponsorship', {
enumerable: true,
get: function get() {
return _revoke_sponsorship.revokeOfferSponsorship;
}
});
Object.defineProperty(exports, 'revokeDataSponsorship', {
enumerable: true,
get: function get() {
return _revoke_sponsorship.revokeDataSponsorship;
}
});
Object.defineProperty(exports, 'revokeClaimableBalanceSponsorship', {
enumerable: true,
get: function get() {
return _revoke_sponsorship.revokeClaimableBalanceSponsorship;
}
});
Object.defineProperty(exports, 'revokeLiquidityPoolSponsorship', {
enumerable: true,
get: function get() {
return _revoke_sponsorship.revokeLiquidityPoolSponsorship;
}
});
Object.defineProperty(exports, 'revokeSignerSponsorship', {
enumerable: true,
get: function get() {
return _revoke_sponsorship.revokeSignerSponsorship;
}
});
var _clawback = __webpack_require__(357);
Object.defineProperty(exports, 'clawback', {
enumerable: true,
get: function get() {
return _clawback.clawback;
}
});
var _set_trustline_flags = __webpack_require__(358);
Object.defineProperty(exports, 'setTrustLineFlags', {
enumerable: true,
get: function get() {
return _set_trustline_flags.setTrustLineFlags;
}
});
var _liquidity_pool_deposit = __webpack_require__(359);
Object.defineProperty(exports, 'liquidityPoolDeposit', {
enumerable: true,
get: function get() {
return _liquidity_pool_deposit.liquidityPoolDeposit;
}
});
var _liquidity_pool_withdraw = __webpack_require__(360);
Object.defineProperty(exports, 'liquidityPoolWithdraw', {
enumerable: true,
get: function get() {
return _liquidity_pool_withdraw.liquidityPoolWithdraw;
}
});
/***/ }),
/* 338 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.manageSellOffer = manageSellOffer;
var _isUndefined = __webpack_require__(7);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _jsXdr = __webpack_require__(22);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Returns a XDR ManageSellOfferOp. A "manage sell offer" operation creates, updates, or
* deletes an offer.
* @function
* @alias Operation.manageSellOffer
* @param {object} opts Options object
* @param {Asset} opts.selling - What you're selling.
* @param {Asset} opts.buying - What you're buying.
* @param {string} opts.amount - The total amount you're selling. If 0, deletes the offer.
* @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `selling` in terms of `buying`.
* @param {number} opts.price.n - If `opts.price` is an object: the price numerator
* @param {number} opts.price.d - If `opts.price` is an object: the price denominator
* @param {number|string} [opts.offerId ] - If `0`, will create a new offer (default). Otherwise, edits an exisiting offer.
* @param {string} [opts.source] - The source account (defaults to transaction source).
* @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found.
* @returns {xdr.ManageSellOfferOp} Manage Sell Offer operation
*/
function manageSellOffer(opts) {
var attributes = {};
attributes.selling = opts.selling.toXDRObject();
attributes.buying = opts.buying.toXDRObject();
if (!this.isValidAmount(opts.amount, true)) {
throw new TypeError(this.constructAmountRequirementsError('amount'));
}
attributes.amount = this._toXDRAmount(opts.amount);
if ((0, _isUndefined2.default)(opts.price)) {
throw new TypeError('price argument is required');
}
attributes.price = this._toXDRPrice(opts.price);
if (!(0, _isUndefined2.default)(opts.offerId)) {
opts.offerId = opts.offerId.toString();
} else {
opts.offerId = '0';
}
attributes.offerId = _jsXdr.Hyper.fromString(opts.offerId);
var manageSellOfferOp = new _xdr2.default.ManageSellOfferOp(attributes);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.manageSellOffer(manageSellOfferOp);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 339 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createPassiveSellOffer = createPassiveSellOffer;
var _isUndefined = __webpack_require__(7);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Returns a XDR CreatePasiveSellOfferOp. A "create passive offer" operation creates an
* offer that won't consume a counter offer that exactly matches this offer. This is
* useful for offers just used as 1:1 exchanges for path payments. Use manage offer
* to manage this offer after using this operation to create it.
* @function
* @alias Operation.createPassiveSellOffer
* @param {object} opts Options object
* @param {Asset} opts.selling - What you're selling.
* @param {Asset} opts.buying - What you're buying.
* @param {string} opts.amount - The total amount you're selling. If 0, deletes the offer.
* @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `selling` in terms of `buying`.
* @param {number} opts.price.n - If `opts.price` is an object: the price numerator
* @param {number} opts.price.d - If `opts.price` is an object: the price denominator
* @param {string} [opts.source] - The source account (defaults to transaction source).
* @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found.
* @returns {xdr.CreatePassiveSellOfferOp} Create Passive Sell Offer operation
*/
function createPassiveSellOffer(opts) {
var attributes = {};
attributes.selling = opts.selling.toXDRObject();
attributes.buying = opts.buying.toXDRObject();
if (!this.isValidAmount(opts.amount)) {
throw new TypeError(this.constructAmountRequirementsError('amount'));
}
attributes.amount = this._toXDRAmount(opts.amount);
if ((0, _isUndefined2.default)(opts.price)) {
throw new TypeError('price argument is required');
}
attributes.price = this._toXDRPrice(opts.price);
var createPassiveSellOfferOp = new _xdr2.default.CreatePassiveSellOfferOp(attributes);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.createPassiveSellOffer(createPassiveSellOfferOp);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 340 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.accountMerge = accountMerge;
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _decode_encode_muxed_account = __webpack_require__(17);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Transfers native balance to destination account.
*
* @function
* @alias Operation.accountMerge
*
* @param {object} opts - options object
* @param {string} opts.destination - destination to merge the source account into
* @param {string} [opts.source] - operation source account (defaults to
* transaction source)
*
* @returns {xdr.Operation} an Account Merge operation (xdr.AccountMergeOp)
*/
function accountMerge(opts) {
var opAttributes = {};
try {
opAttributes.body = _xdr2.default.OperationBody.accountMerge((0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination));
} catch (e) {
throw new Error('destination is invalid');
}
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 341 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.allowTrust = allowTrust;
var _padEnd = __webpack_require__(140);
var _padEnd2 = _interopRequireDefault(_padEnd);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _keypair = __webpack_require__(19);
var _strkey = __webpack_require__(8);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @deprecated since v5.0
*
* Returns an XDR AllowTrustOp. An "allow trust" operation authorizes another
* account to hold your account's credit for a given asset.
*
* @function
* @alias Operation.allowTrust
*
* @param {object} opts Options object
* @param {string} opts.trustor - The trusting account (the one being authorized)
* @param {string} opts.assetCode - The asset code being authorized.
* @param {(0|1|2)} opts.authorize - `1` to authorize, `2` to authorize to maintain liabilities, and `0` to deauthorize.
* @param {string} [opts.source] - The source account (defaults to transaction source).
*
* @returns {xdr.AllowTrustOp} Allow Trust operation
*/
function allowTrust(opts) {
if (!_strkey.StrKey.isValidEd25519PublicKey(opts.trustor)) {
throw new Error('trustor is invalid');
}
var attributes = {};
attributes.trustor = _keypair.Keypair.fromPublicKey(opts.trustor).xdrAccountId();
if (opts.assetCode.length <= 4) {
var code = (0, _padEnd2.default)(opts.assetCode, 4, '\0');
attributes.asset = _xdr2.default.AssetCode.assetTypeCreditAlphanum4(code);
} else if (opts.assetCode.length <= 12) {
var _code = (0, _padEnd2.default)(opts.assetCode, 12, '\0');
attributes.asset = _xdr2.default.AssetCode.assetTypeCreditAlphanum12(_code);
} else {
throw new Error('Asset code must be 12 characters at max.');
}
if (typeof opts.authorize === 'boolean') {
if (opts.authorize) {
attributes.authorize = _xdr2.default.TrustLineFlags.authorizedFlag().value;
} else {
attributes.authorize = 0;
}
} else {
attributes.authorize = opts.authorize;
}
var allowTrustOp = new _xdr2.default.AllowTrustOp(attributes);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.allowTrust(allowTrustOp);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 342 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.bumpSequence = bumpSequence;
var _jsXdr = __webpack_require__(22);
var _bignumber = __webpack_require__(23);
var _bignumber2 = _interopRequireDefault(_bignumber);
var _isString = __webpack_require__(9);
var _isString2 = _interopRequireDefault(_isString);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* This operation bumps sequence number.
* @function
* @alias Operation.bumpSequence
* @param {object} opts Options object
* @param {string} opts.bumpTo - Sequence number to bump to.
* @param {string} [opts.source] - The optional source account.
* @returns {xdr.BumpSequenceOp} Operation
*/
function bumpSequence(opts) {
var attributes = {};
if (!(0, _isString2.default)(opts.bumpTo)) {
throw new Error('bumpTo must be a string');
}
try {
// eslint-disable-next-line no-new
new _bignumber2.default(opts.bumpTo);
} catch (e) {
throw new Error('bumpTo must be a stringified number');
}
attributes.bumpTo = _jsXdr.Hyper.fromString(opts.bumpTo);
var bumpSequenceOp = new _xdr2.default.BumpSequenceOp(attributes);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.bumpSequence(bumpSequenceOp);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 343 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.changeTrust = changeTrust;
var _isUndefined = __webpack_require__(7);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _jsXdr = __webpack_require__(22);
var _bignumber = __webpack_require__(23);
var _bignumber2 = _interopRequireDefault(_bignumber);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _asset = __webpack_require__(27);
var _liquidity_pool_asset = __webpack_require__(88);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MAX_INT64 = '9223372036854775807';
/**
* Returns an XDR ChangeTrustOp. A "change trust" operation adds, removes, or updates a
* trust line for a given asset from the source account to another.
* @function
* @alias Operation.changeTrust
* @param {object} opts Options object
* @param {Asset | LiquidityPoolAsset} opts.asset - The asset for the trust line.
* @param {string} [opts.limit] - The limit for the asset, defaults to max int64.
* If the limit is set to "0" it deletes the trustline.
* @param {string} [opts.source] - The source account (defaults to transaction source).
* @returns {xdr.ChangeTrustOp} Change Trust operation
*/
function changeTrust(opts) {
var attributes = {};
if (opts.asset instanceof _asset.Asset) {
attributes.line = opts.asset.toChangeTrustXDRObject();
} else if (opts.asset instanceof _liquidity_pool_asset.LiquidityPoolAsset) {
attributes.line = opts.asset.toXDRObject();
} else {
throw new TypeError('asset must be Asset or LiquidityPoolAsset');
}
if (!(0, _isUndefined2.default)(opts.limit) && !this.isValidAmount(opts.limit, true)) {
throw new TypeError(this.constructAmountRequirementsError('limit'));
}
if (opts.limit) {
attributes.limit = this._toXDRAmount(opts.limit);
} else {
attributes.limit = _jsXdr.Hyper.fromString(new _bignumber2.default(MAX_INT64).toString());
}
if (opts.source) {
attributes.source = opts.source.masterKeypair;
}
var changeTrustOP = new _xdr2.default.ChangeTrustOp(attributes);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.changeTrust(changeTrustOP);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 344 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createAccount = createAccount;
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _keypair = __webpack_require__(19);
var _strkey = __webpack_require__(8);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Create and fund a non existent account.
* @function
* @alias Operation.createAccount
* @param {object} opts Options object
* @param {string} opts.destination - Destination account ID to create an account for.
* @param {string} opts.startingBalance - Amount in XLM the account should be funded for. Must be greater
* than the [reserve balance amount](https://developers.stellar.org/docs/glossary/fees/).
* @param {string} [opts.source] - The source account for the payment. Defaults to the transaction's source account.
* @returns {xdr.CreateAccountOp} Create account operation
*/
function createAccount(opts) {
if (!_strkey.StrKey.isValidEd25519PublicKey(opts.destination)) {
throw new Error('destination is invalid');
}
if (!this.isValidAmount(opts.startingBalance, true)) {
throw new TypeError('startingBalance must be of type String, represent a non-negative number and have at most 7 digits after the decimal');
}
var attributes = {};
attributes.destination = _keypair.Keypair.fromPublicKey(opts.destination).xdrAccountId();
attributes.startingBalance = this._toXDRAmount(opts.startingBalance);
var createAccountOp = new _xdr2.default.CreateAccountOp(attributes);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.createAccount(createAccountOp);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 345 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createClaimableBalance = createClaimableBalance;
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _asset = __webpack_require__(27);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Create a new claimable balance operation.
*
* @function
* @alias Operation.createClaimableBalance
*
* @param {object} opts Options object
* @param {Asset} opts.asset - The asset for the claimable balance.
* @param {string} opts.amount - Amount.
* @param {Claimant[]} opts.claimants - An array of Claimants
* @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account.
*
* @returns {xdr.Operation} Create claimable balance operation
*
* @example
* const asset = new Asset(
* 'USD',
* 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7'
* );
* const amount = '100.0000000';
* const claimants = [
* new Claimant(
* 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ',
* Claimant.predicateBeforeAbsoluteTime("4102444800000")
* )
* ];
*
* const op = Operation.createClaimableBalance({
* asset,
* amount,
* claimants
* });
*
*/
function createClaimableBalance(opts) {
if (!(opts.asset instanceof _asset.Asset)) {
throw new Error('must provide an asset for create claimable balance operation');
}
if (!this.isValidAmount(opts.amount)) {
throw new TypeError(this.constructAmountRequirementsError('amount'));
}
if (!Array.isArray(opts.claimants) || opts.claimants.length === 0) {
throw new Error('must provide at least one claimant');
}
var attributes = {};
attributes.asset = opts.asset.toXDRObject();
attributes.amount = this._toXDRAmount(opts.amount);
attributes.claimants = opts.claimants.map(function (c) {
return c.toXDRObject();
});
var createClaimableBalanceOp = new _xdr2.default.CreateClaimableBalanceOp(attributes);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.createClaimableBalance(createClaimableBalanceOp);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 346 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.clawbackClaimableBalance = clawbackClaimableBalance;
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _claim_claimable_balance = __webpack_require__(147);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Creates a clawback operation for a claimable balance.
*
* @function
* @alias Operation.clawbackClaimableBalance
* @param {object} opts - Options object
* @param {string} opts.balanceId - The claimable balance ID to be clawed back.
* @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account.
*
* @return {xdr.ClawbackClaimableBalanceOp}
*
* @example
* const op = Operation.clawbackClaimableBalance({
* balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be',
* });
*
* @link https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#clawback-claimable-balance-operation
*/
function clawbackClaimableBalance() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
(0, _claim_claimable_balance.validateClaimableBalanceId)(opts.balanceId);
var attributes = {
balanceId: _xdr2.default.ClaimableBalanceId.fromXDR(opts.balanceId, 'hex')
};
var opAttributes = {
body: _xdr2.default.OperationBody.clawbackClaimableBalance(new _xdr2.default.ClawbackClaimableBalanceOp(attributes))
};
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 347 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.inflation = inflation;
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* This operation generates the inflation.
* @function
* @alias Operation.inflation
* @param {object} [opts] Options object
* @param {string} [opts.source] - The optional source account.
* @returns {xdr.InflationOp} Inflation operation
*/
function inflation() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.inflation();
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 348 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.manageData = manageData;
var _isString = __webpack_require__(9);
var _isString2 = _interopRequireDefault(_isString);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* This operation adds data entry to the ledger.
* @function
* @alias Operation.manageData
* @param {object} opts Options object
* @param {string} opts.name - The name of the data entry.
* @param {string|Buffer} opts.value - The value of the data entry.
* @param {string} [opts.source] - The optional source account.
* @returns {xdr.ManageDataOp} Manage Data operation
*/
function manageData(opts) {
var attributes = {};
if (!((0, _isString2.default)(opts.name) && opts.name.length <= 64)) {
throw new Error('name must be a string, up to 64 characters');
}
attributes.dataName = opts.name;
if (!(0, _isString2.default)(opts.value) && !Buffer.isBuffer(opts.value) && opts.value !== null) {
throw new Error('value must be a string, Buffer or null');
}
if ((0, _isString2.default)(opts.value)) {
attributes.dataValue = Buffer.from(opts.value);
} else {
attributes.dataValue = opts.value;
}
if (attributes.dataValue !== null && attributes.dataValue.length > 64) {
throw new Error('value cannot be longer that 64 bytes');
}
var manageDataOp = new _xdr2.default.ManageDataOp(attributes);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.manageData(manageDataOp);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 349 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.manageBuyOffer = manageBuyOffer;
var _isUndefined = __webpack_require__(7);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _jsXdr = __webpack_require__(22);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Returns a XDR ManageBuyOfferOp. A "manage buy offer" operation creates, updates, or
* deletes a buy offer.
* @function
* @alias Operation.manageBuyOffer
* @param {object} opts Options object
* @param {Asset} opts.selling - What you're selling.
* @param {Asset} opts.buying - What you're buying.
* @param {string} opts.buyAmount - The total amount you're buying. If 0, deletes the offer.
* @param {number|string|BigNumber|Object} opts.price - Price of 1 unit of `buying` in terms of `selling`.
* @param {number} opts.price.n - If `opts.price` is an object: the price numerator
* @param {number} opts.price.d - If `opts.price` is an object: the price denominator
* @param {number|string} [opts.offerId ] - If `0`, will create a new offer (default). Otherwise, edits an exisiting offer.
* @param {string} [opts.source] - The source account (defaults to transaction source).
* @throws {Error} Throws `Error` when the best rational approximation of `price` cannot be found.
* @returns {xdr.ManageBuyOfferOp} Manage Buy Offer operation
*/
function manageBuyOffer(opts) {
var attributes = {};
attributes.selling = opts.selling.toXDRObject();
attributes.buying = opts.buying.toXDRObject();
if (!this.isValidAmount(opts.buyAmount, true)) {
throw new TypeError(this.constructAmountRequirementsError('buyAmount'));
}
attributes.buyAmount = this._toXDRAmount(opts.buyAmount);
if ((0, _isUndefined2.default)(opts.price)) {
throw new TypeError('price argument is required');
}
attributes.price = this._toXDRPrice(opts.price);
if (!(0, _isUndefined2.default)(opts.offerId)) {
opts.offerId = opts.offerId.toString();
} else {
opts.offerId = '0';
}
attributes.offerId = _jsXdr.Hyper.fromString(opts.offerId);
var manageBuyOfferOp = new _xdr2.default.ManageBuyOfferOp(attributes);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.manageBuyOffer(manageBuyOfferOp);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 350 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.pathPaymentStrictReceive = pathPaymentStrictReceive;
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _decode_encode_muxed_account = __webpack_require__(17);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Creates a PathPaymentStrictReceive operation.
*
* A `PathPaymentStrictReceive` operation sends the specified amount to the
* destination account. It credits the destination with `destAmount` of
* `destAsset`, while debiting at most `sendMax` of `sendAsset` from the source.
* The transfer optionally occurs through a path. XLM payments create the
* destination account if it does not exist.
*
* @function
* @alias Operation.pathPaymentStrictReceive
* @see https://developers.stellar.org/docs/start/list-of-operations/#path-payment-strict-receive
*
* @param {object} opts - Options object
* @param {Asset} opts.sendAsset - asset to pay with
* @param {string} opts.sendMax - maximum amount of sendAsset to send
* @param {string} opts.destination - destination account to send to
* @param {Asset} opts.destAsset - asset the destination will receive
* @param {string} opts.destAmount - amount the destination receives
* @param {Asset[]} opts.path - array of Asset objects to use as the path
*
* @param {string} [opts.source] - The source account for the payment.
* Defaults to the transaction's source account.
*
* @returns {xdr.PathPaymentStrictReceiveOp} the resulting path payment op
*/
function pathPaymentStrictReceive(opts) {
switch (true) {
case !opts.sendAsset:
throw new Error('Must specify a send asset');
case !this.isValidAmount(opts.sendMax):
throw new TypeError(this.constructAmountRequirementsError('sendMax'));
case !opts.destAsset:
throw new Error('Must provide a destAsset for a payment operation');
case !this.isValidAmount(opts.destAmount):
throw new TypeError(this.constructAmountRequirementsError('destAmount'));
default:
break;
}
var attributes = {};
attributes.sendAsset = opts.sendAsset.toXDRObject();
attributes.sendMax = this._toXDRAmount(opts.sendMax);
try {
attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination);
} catch (e) {
throw new Error('destination is invalid');
}
attributes.destAsset = opts.destAsset.toXDRObject();
attributes.destAmount = this._toXDRAmount(opts.destAmount);
var path = opts.path ? opts.path : [];
attributes.path = path.map(function (x) {
return x.toXDRObject();
});
var payment = new _xdr2.default.PathPaymentStrictReceiveOp(attributes);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.pathPaymentStrictReceive(payment);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 351 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.pathPaymentStrictSend = pathPaymentStrictSend;
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _decode_encode_muxed_account = __webpack_require__(17);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Creates a PathPaymentStrictSend operation.
*
* A `PathPaymentStrictSend` operation sends the specified amount to the
* destination account crediting at least `destMin` of `destAsset`, optionally
* through a path. XLM payments create the destination account if it does not
* exist.
*
* @function
* @alias Operation.pathPaymentStrictSend
* @see https://developers.stellar.org/docs/start/list-of-operations/#path-payment-strict-send
*
* @param {object} opts - Options object
* @param {Asset} opts.sendAsset - asset to pay with
* @param {string} opts.sendAmount - amount of sendAsset to send (excluding fees)
* @param {string} opts.destination - destination account to send to
* @param {Asset} opts.destAsset - asset the destination will receive
* @param {string} opts.destMin - minimum amount of destAsset to be receive
* @param {Asset[]} opts.path - array of Asset objects to use as the path
*
* @param {string} [opts.source] - The source account for the payment.
* Defaults to the transaction's source account.
*
* @returns {xdr.Operation} the resulting path payment operation
* (xdr.PathPaymentStrictSendOp)
*/
function pathPaymentStrictSend(opts) {
switch (true) {
case !opts.sendAsset:
throw new Error('Must specify a send asset');
case !this.isValidAmount(opts.sendAmount):
throw new TypeError(this.constructAmountRequirementsError('sendAmount'));
case !opts.destAsset:
throw new Error('Must provide a destAsset for a payment operation');
case !this.isValidAmount(opts.destMin):
throw new TypeError(this.constructAmountRequirementsError('destMin'));
default:
break;
}
var attributes = {};
attributes.sendAsset = opts.sendAsset.toXDRObject();
attributes.sendAmount = this._toXDRAmount(opts.sendAmount);
try {
attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination);
} catch (e) {
throw new Error('destination is invalid');
}
attributes.destAsset = opts.destAsset.toXDRObject();
attributes.destMin = this._toXDRAmount(opts.destMin);
var path = opts.path ? opts.path : [];
attributes.path = path.map(function (x) {
return x.toXDRObject();
});
var payment = new _xdr2.default.PathPaymentStrictSendOp(attributes);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.pathPaymentStrictSend(payment);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 352 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.payment = payment;
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _decode_encode_muxed_account = __webpack_require__(17);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Create a payment operation.
*
* @function
* @alias Operation.payment
* @see https://developers.stellar.org/docs/start/list-of-operations/#payment
*
* @param {object} opts - Options object
* @param {string} opts.destination - destination account ID
* @param {Asset} opts.asset - asset to send
* @param {string} opts.amount - amount to send
*
* @param {string} [opts.source] - The source account for the payment.
* Defaults to the transaction's source account.
*
* @returns {xdr.Operation} The resulting payment operation (xdr.PaymentOp)
*/
function payment(opts) {
if (!opts.asset) {
throw new Error('Must provide an asset for a payment operation');
}
if (!this.isValidAmount(opts.amount)) {
throw new TypeError(this.constructAmountRequirementsError('amount'));
}
var attributes = {};
try {
attributes.destination = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.destination);
} catch (e) {
throw new Error('destination is invalid');
}
attributes.asset = opts.asset.toXDRObject();
attributes.amount = this._toXDRAmount(opts.amount);
var paymentOp = new _xdr2.default.PaymentOp(attributes);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.payment(paymentOp);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 353 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.setOptions = setOptions;
var _isUndefined = __webpack_require__(7);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _isString = __webpack_require__(9);
var _isString2 = _interopRequireDefault(_isString);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _keypair = __webpack_require__(19);
var _strkey = __webpack_require__(8);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function weightCheckFunction(value, name) {
if (value >= 0 && value <= 255) {
return true;
}
throw new Error(name + ' value must be between 0 and 255');
}
/**
* Returns an XDR SetOptionsOp. A "set options" operations set or clear account flags,
* set the account's inflation destination, and/or add new signers to the account.
* The flags used in `opts.clearFlags` and `opts.setFlags` can be the following:
* - `{@link AuthRequiredFlag}`
* - `{@link AuthRevocableFlag}`
* - `{@link AuthImmutableFlag}`
* - `{@link AuthClawbackEnabledFlag}`
*
* It's possible to set/clear multiple flags at once using logical or.
*
* @function
* @alias Operation.setOptions
*
* @param {object} opts Options object
* @param {string} [opts.inflationDest] - Set this account ID as the account's inflation destination.
* @param {(number|string)} [opts.clearFlags] - Bitmap integer for which account flags to clear.
* @param {(number|string)} [opts.setFlags] - Bitmap integer for which account flags to set.
* @param {number|string} [opts.masterWeight] - The master key weight.
* @param {number|string} [opts.lowThreshold] - The sum weight for the low threshold.
* @param {number|string} [opts.medThreshold] - The sum weight for the medium threshold.
* @param {number|string} [opts.highThreshold] - The sum weight for the high threshold.
* @param {object} [opts.signer] - Add or remove a signer from the account. The signer is
* deleted if the weight is 0. Only one of `ed25519PublicKey`, `sha256Hash`, `preAuthTx` should be defined.
* @param {string} [opts.signer.ed25519PublicKey] - The ed25519 public key of the signer.
* @param {Buffer|string} [opts.signer.sha256Hash] - sha256 hash (Buffer or hex string) of preimage that will unlock funds. Preimage should be used as signature of future transaction.
* @param {Buffer|string} [opts.signer.preAuthTx] - Hash (Buffer or hex string) of transaction that will unlock funds.
* @param {string} [opts.signer.ed25519SignedPayload] - Signed payload signer (ed25519 public key + raw payload) for atomic transaction signature disclosure.
* @param {number|string} [opts.signer.weight] - The weight of the new signer (0 to delete or 1-255)
* @param {string} [opts.homeDomain] - sets the home domain used for reverse federation lookup.
* @param {string} [opts.source] - The source account (defaults to transaction source).
*
* @returns {xdr.SetOptionsOp} XDR operation
* @see [Account flags](https://developers.stellar.org/docs/glossary/accounts/#flags)
*/
/* eslint-disable no-param-reassign */
function setOptions(opts) {
var attributes = {};
if (opts.inflationDest) {
if (!_strkey.StrKey.isValidEd25519PublicKey(opts.inflationDest)) {
throw new Error('inflationDest is invalid');
}
attributes.inflationDest = _keypair.Keypair.fromPublicKey(opts.inflationDest).xdrAccountId();
}
attributes.clearFlags = this._checkUnsignedIntValue('clearFlags', opts.clearFlags);
attributes.setFlags = this._checkUnsignedIntValue('setFlags', opts.setFlags);
attributes.masterWeight = this._checkUnsignedIntValue('masterWeight', opts.masterWeight, weightCheckFunction);
attributes.lowThreshold = this._checkUnsignedIntValue('lowThreshold', opts.lowThreshold, weightCheckFunction);
attributes.medThreshold = this._checkUnsignedIntValue('medThreshold', opts.medThreshold, weightCheckFunction);
attributes.highThreshold = this._checkUnsignedIntValue('highThreshold', opts.highThreshold, weightCheckFunction);
if (!(0, _isUndefined2.default)(opts.homeDomain) && !(0, _isString2.default)(opts.homeDomain)) {
throw new TypeError('homeDomain argument must be of type String');
}
attributes.homeDomain = opts.homeDomain;
if (opts.signer) {
var weight = this._checkUnsignedIntValue('signer.weight', opts.signer.weight, weightCheckFunction);
var key = void 0;
var setValues = 0;
if (opts.signer.ed25519PublicKey) {
if (!_strkey.StrKey.isValidEd25519PublicKey(opts.signer.ed25519PublicKey)) {
throw new Error('signer.ed25519PublicKey is invalid.');
}
var rawKey = _strkey.StrKey.decodeEd25519PublicKey(opts.signer.ed25519PublicKey);
// eslint-disable-next-line new-cap
key = new _xdr2.default.SignerKey.signerKeyTypeEd25519(rawKey);
setValues += 1;
}
if (opts.signer.preAuthTx) {
if ((0, _isString2.default)(opts.signer.preAuthTx)) {
opts.signer.preAuthTx = Buffer.from(opts.signer.preAuthTx, 'hex');
}
if (!(Buffer.isBuffer(opts.signer.preAuthTx) && opts.signer.preAuthTx.length === 32)) {
throw new Error('signer.preAuthTx must be 32 bytes Buffer.');
}
// eslint-disable-next-line new-cap
key = new _xdr2.default.SignerKey.signerKeyTypePreAuthTx(opts.signer.preAuthTx);
setValues += 1;
}
if (opts.signer.sha256Hash) {
if ((0, _isString2.default)(opts.signer.sha256Hash)) {
opts.signer.sha256Hash = Buffer.from(opts.signer.sha256Hash, 'hex');
}
if (!(Buffer.isBuffer(opts.signer.sha256Hash) && opts.signer.sha256Hash.length === 32)) {
throw new Error('signer.sha256Hash must be 32 bytes Buffer.');
}
// eslint-disable-next-line new-cap
key = new _xdr2.default.SignerKey.signerKeyTypeHashX(opts.signer.sha256Hash);
setValues += 1;
}
if (opts.signer.ed25519SignedPayload) {
if (!_strkey.StrKey.isValidSignedPayload(opts.signer.ed25519SignedPayload)) {
throw new Error('signer.ed25519SignedPayload is invalid.');
}
var _rawKey = _strkey.StrKey.decodeSignedPayload(opts.signer.ed25519SignedPayload);
var signedPayloadXdr = _xdr2.default.SignerKeyEd25519SignedPayload.fromXDR(_rawKey);
// eslint-disable-next-line new-cap
key = _xdr2.default.SignerKey.signerKeyTypeEd25519SignedPayload(signedPayloadXdr);
setValues += 1;
}
if (setValues !== 1) {
throw new Error('Signer object must contain exactly one of signer.ed25519PublicKey, signer.sha256Hash, signer.preAuthTx.');
}
attributes.signer = new _xdr2.default.Signer({ key: key, weight: weight });
}
var setOptionsOp = new _xdr2.default.SetOptionsOp(attributes);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.setOptions(setOptionsOp);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 354 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.beginSponsoringFutureReserves = beginSponsoringFutureReserves;
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _strkey = __webpack_require__(8);
var _keypair = __webpack_require__(19);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Create a "begin sponsoring future reserves" operation.
* @function
* @alias Operation.beginSponsoringFutureReserves
* @param {object} opts Options object
* @param {string} opts.sponsoredId - The sponsored account id.
* @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account.
* @returns {xdr.Operation} xdr operation
*
* @example
* const op = Operation.beginSponsoringFutureReserves({
* sponsoredId: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7'
* });
*
*/
function beginSponsoringFutureReserves() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!_strkey.StrKey.isValidEd25519PublicKey(opts.sponsoredId)) {
throw new Error('sponsoredId is invalid');
}
var op = new _xdr2.default.BeginSponsoringFutureReservesOp({
sponsoredId: _keypair.Keypair.fromPublicKey(opts.sponsoredId).xdrAccountId()
});
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.beginSponsoringFutureReserves(op);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 355 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.endSponsoringFutureReserves = endSponsoringFutureReserves;
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Create an "end sponsoring future reserves" operation.
* @function
* @alias Operation.endSponsoringFutureReserves
* @param {object} opts Options object
* @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account.
* @returns {xdr.Operation} xdr operation
*
* @example
* const op = Operation.endSponsoringFutureReserves();
*
*/
function endSponsoringFutureReserves() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.endSponsoringFutureReserves();
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 356 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.revokeAccountSponsorship = revokeAccountSponsorship;
exports.revokeTrustlineSponsorship = revokeTrustlineSponsorship;
exports.revokeOfferSponsorship = revokeOfferSponsorship;
exports.revokeDataSponsorship = revokeDataSponsorship;
exports.revokeClaimableBalanceSponsorship = revokeClaimableBalanceSponsorship;
exports.revokeLiquidityPoolSponsorship = revokeLiquidityPoolSponsorship;
exports.revokeSignerSponsorship = revokeSignerSponsorship;
var _isString = __webpack_require__(9);
var _isString2 = _interopRequireDefault(_isString);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _strkey = __webpack_require__(8);
var _keypair = __webpack_require__(19);
var _asset = __webpack_require__(27);
var _liquidity_pool_id = __webpack_require__(89);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Create a "revoke sponsorship" operation for an account.
*
* @function
* @alias Operation.revokeAccountSponsorship
* @param {object} opts Options object
* @param {string} opts.account - The sponsored account ID.
* @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account.
* @returns {xdr.Operation} xdr operation
*
* @example
* const op = Operation.revokeAccountSponsorship({
* account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7
* });
*
*/
function revokeAccountSponsorship() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) {
throw new Error('account is invalid');
}
var ledgerKey = _xdr2.default.LedgerKey.account(new _xdr2.default.LedgerKeyAccount({
accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId()
}));
var op = _xdr2.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.revokeSponsorship(op);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/**
* Create a "revoke sponsorship" operation for a trustline.
*
* @function
* @alias Operation.revokeTrustlineSponsorship
* @param {object} opts Options object
* @param {string} opts.account - The account ID which owns the trustline.
* @param {Asset | LiquidityPoolId} opts.asset - The trustline asset.
* @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account.
* @returns {xdr.Operation} xdr operation
*
* @example
* const op = Operation.revokeTrustlineSponsorship({
* account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7
* asset: new StellarBase.LiquidityPoolId(
* 'USDUSD',
* 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7'
* )
* });
*
*/
function revokeTrustlineSponsorship() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) {
throw new Error('account is invalid');
}
var asset = void 0;
if (opts.asset instanceof _asset.Asset) {
asset = opts.asset.toTrustLineXDRObject();
} else if (opts.asset instanceof _liquidity_pool_id.LiquidityPoolId) {
asset = opts.asset.toXDRObject();
} else {
throw new TypeError('asset must be an Asset or LiquidityPoolId');
}
var ledgerKey = _xdr2.default.LedgerKey.trustline(new _xdr2.default.LedgerKeyTrustLine({
accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(),
asset: asset
}));
var op = _xdr2.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.revokeSponsorship(op);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/**
* Create a "revoke sponsorship" operation for an offer.
*
* @function
* @alias Operation.revokeOfferSponsorship
* @param {object} opts Options object
* @param {string} opts.seller - The account ID which created the offer.
* @param {string} opts.offerId - The offer ID.
* @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account.
* @returns {xdr.Operation} xdr operation
*
* @example
* const op = Operation.revokeOfferSponsorship({
* seller: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7
* offerId: '1234'
* });
*
*/
function revokeOfferSponsorship() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!_strkey.StrKey.isValidEd25519PublicKey(opts.seller)) {
throw new Error('seller is invalid');
}
if (!(0, _isString2.default)(opts.offerId)) {
throw new Error('offerId is invalid');
}
var ledgerKey = _xdr2.default.LedgerKey.offer(new _xdr2.default.LedgerKeyOffer({
sellerId: _keypair.Keypair.fromPublicKey(opts.seller).xdrAccountId(),
offerId: _xdr2.default.Int64.fromString(opts.offerId)
}));
var op = _xdr2.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.revokeSponsorship(op);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/**
* Create a "revoke sponsorship" operation for a data entry.
*
* @function
* @alias Operation.revokeDataSponsorship
* @param {object} opts Options object
* @param {string} opts.account - The account ID which owns the data entry.
* @param {string} opts.name - The name of the data entry
* @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account.
* @returns {xdr.Operation} xdr operation
*
* @example
* const op = Operation.revokeDataSponsorship({
* account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7
* name: 'foo'
* });
*
*/
function revokeDataSponsorship() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) {
throw new Error('account is invalid');
}
if (!(0, _isString2.default)(opts.name) || opts.name.length > 64) {
throw new Error('name must be a string, up to 64 characters');
}
var ledgerKey = _xdr2.default.LedgerKey.data(new _xdr2.default.LedgerKeyData({
accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(),
dataName: opts.name
}));
var op = _xdr2.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.revokeSponsorship(op);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/**
* Create a "revoke sponsorship" operation for a claimable balance.
*
* @function
* @alias Operation.revokeClaimableBalanceSponsorship
* @param {object} opts Options object
* @param {string} opts.balanceId - The sponsored claimable balance ID.
* @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account.
* @returns {xdr.Operation} xdr operation
*
* @example
* const op = Operation.revokeClaimableBalanceSponsorship({
* balanceId: '00000000da0d57da7d4850e7fc10d2a9d0ebc731f7afb40574c03395b17d49149b91f5be',
* });
*
*/
function revokeClaimableBalanceSponsorship() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!(0, _isString2.default)(opts.balanceId)) {
throw new Error('balanceId is invalid');
}
var ledgerKey = _xdr2.default.LedgerKey.claimableBalance(new _xdr2.default.LedgerKeyClaimableBalance({
balanceId: _xdr2.default.ClaimableBalanceId.fromXDR(opts.balanceId, 'hex')
}));
var op = _xdr2.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.revokeSponsorship(op);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/**
* Creates a "revoke sponsorship" operation for a liquidity pool.
*
* @function
* @alias Operation.revokeLiquidityPoolSponsorship
* @param {object} opts – Options object.
* @param {string} opts.liquidityPoolId - The sponsored liquidity pool ID in 'hex' string.
* @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account.
* @returns {xdr.Operation} xdr Operation.
*
* @example
* const op = Operation.revokeLiquidityPoolSponsorship({
* liquidityPoolId: 'dd7b1ab831c273310ddbec6f97870aa83c2fbd78ce22aded37ecbf4f3380fac7',
* });
*
*/
function revokeLiquidityPoolSponsorship() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!(0, _isString2.default)(opts.liquidityPoolId)) {
throw new Error('liquidityPoolId is invalid');
}
var ledgerKey = _xdr2.default.LedgerKey.liquidityPool(new _xdr2.default.LedgerKeyLiquidityPool({
liquidityPoolId: _xdr2.default.PoolId.fromXDR(opts.liquidityPoolId, 'hex')
}));
var op = _xdr2.default.RevokeSponsorshipOp.revokeSponsorshipLedgerEntry(ledgerKey);
var opAttributes = {
body: _xdr2.default.OperationBody.revokeSponsorship(op)
};
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/**
* Create a "revoke sponsorship" operation for a signer.
*
* @function
* @alias Operation.revokeSignerSponsorship
* @param {object} opts Options object
* @param {string} opts.account - The account ID where the signer sponsorship is being removed from.
* @param {object} opts.signer - The signer whose sponsorship is being removed.
* @param {string} [opts.signer.ed25519PublicKey] - The ed25519 public key of the signer.
* @param {Buffer|string} [opts.signer.sha256Hash] - sha256 hash (Buffer or hex string).
* @param {Buffer|string} [opts.signer.preAuthTx] - Hash (Buffer or hex string) of transaction.
* @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account.
* @returns {xdr.Operation} xdr operation
*
* @example
* const op = Operation.revokeSignerSponsorship({
* account: 'GDGU5OAPHNPU5UCLE5RDJHG7PXZFQYWKCFOEXSXNMR6KRQRI5T6XXCD7
* signer: {
* ed25519PublicKey: 'GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ'
* }
* })
*
*/
function revokeSignerSponsorship() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (!_strkey.StrKey.isValidEd25519PublicKey(opts.account)) {
throw new Error('account is invalid');
}
var key = void 0;
if (opts.signer.ed25519PublicKey) {
if (!_strkey.StrKey.isValidEd25519PublicKey(opts.signer.ed25519PublicKey)) {
throw new Error('signer.ed25519PublicKey is invalid.');
}
var rawKey = _strkey.StrKey.decodeEd25519PublicKey(opts.signer.ed25519PublicKey);
key = new _xdr2.default.SignerKey.signerKeyTypeEd25519(rawKey);
} else if (opts.signer.preAuthTx) {
var buffer = void 0;
if ((0, _isString2.default)(opts.signer.preAuthTx)) {
buffer = Buffer.from(opts.signer.preAuthTx, 'hex');
} else {
buffer = opts.signer.preAuthTx;
}
if (!(Buffer.isBuffer(buffer) && buffer.length === 32)) {
throw new Error('signer.preAuthTx must be 32 bytes Buffer.');
}
key = new _xdr2.default.SignerKey.signerKeyTypePreAuthTx(buffer);
} else if (opts.signer.sha256Hash) {
var _buffer = void 0;
if ((0, _isString2.default)(opts.signer.sha256Hash)) {
_buffer = Buffer.from(opts.signer.sha256Hash, 'hex');
} else {
_buffer = opts.signer.sha256Hash;
}
if (!(Buffer.isBuffer(_buffer) && _buffer.length === 32)) {
throw new Error('signer.sha256Hash must be 32 bytes Buffer.');
}
key = new _xdr2.default.SignerKey.signerKeyTypeHashX(_buffer);
} else {
throw new Error('signer is invalid');
}
var signer = new _xdr2.default.RevokeSponsorshipOpSigner({
accountId: _keypair.Keypair.fromPublicKey(opts.account).xdrAccountId(),
signerKey: key
});
var op = _xdr2.default.RevokeSponsorshipOp.revokeSponsorshipSigner(signer);
var opAttributes = {};
opAttributes.body = _xdr2.default.OperationBody.revokeSponsorship(op);
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 357 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.clawback = clawback;
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _decode_encode_muxed_account = __webpack_require__(17);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Creates a clawback operation.
*
* @function
* @alias Operation.clawback
*
* @param {object} opts - Options object
* @param {Asset} opts.asset - The asset being clawed back.
* @param {string} opts.amount - The amount of the asset to claw back.
* @param {string} opts.from - The public key of the (optionally-muxed)
* account to claw back from.
*
* @param {string} [opts.source] - The source account for the operation.
* Defaults to the transaction's source account.
*
* @return {xdr.ClawbackOp}
*
* @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#clawback-operation
*/
function clawback(opts) {
var attributes = {};
if (!this.isValidAmount(opts.amount)) {
throw new TypeError(this.constructAmountRequirementsError('amount'));
}
attributes.amount = this._toXDRAmount(opts.amount);
attributes.asset = opts.asset.toXDRObject();
try {
attributes.from = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(opts.from);
} catch (e) {
throw new Error('from address is invalid');
}
var opAttributes = {
body: _xdr2.default.OperationBody.clawback(new _xdr2.default.ClawbackOp(attributes))
};
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 358 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; };
exports.setTrustLineFlags = setTrustLineFlags;
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _keypair = __webpack_require__(19);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Creates a trustline flag configuring operation.
*
* For the flags, set them to true to enable them and false to disable them. Any
* unmodified operations will be marked `undefined` in the result.
*
* Note that you can only **clear** the clawbackEnabled flag set; it must be set
* account-wide via operations.SetOptions (setting
* xdr.AccountFlags.clawbackEnabled).
*
* @function
* @alias Operation.setTrustLineFlags
*
* @param {object} opts - Options object
* @param {string} opts.trustor - the account whose trustline this is
* @param {Asset} opts.asset - the asset on the trustline
* @param {object} opts.flags - the set of flags to modify
*
* @param {bool} [opts.flags.authorized] - authorize account to perform
* transactions with its credit
* @param {bool} [opts.flags.authorizedToMaintainLiabilities] - authorize
* account to maintain and reduce liabilities for its credit
* @param {bool} [opts.flags.clawbackEnabled] - stop claimable balances on
* this trustlines from having clawbacks enabled (this flag can only be set
* to false!)
* @param {string} [opts.source] - The source account for the operation.
* Defaults to the transaction's source account.
*
* @note You must include at least one flag.
*
* @return {xdr.SetTrustLineFlagsOp}
*
* @link xdr.AccountFlags
* @link xdr.TrustLineFlags
* @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0035.md#set-trustline-flags-operation
* @see https://developers.stellar.org/docs/start/list-of-operations/#set-options
*/
function setTrustLineFlags() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var attributes = {};
if (_typeof(opts.flags) !== 'object' || Object.keys(opts.flags).length === 0) {
throw new Error('opts.flags must be a map of boolean flags to modify');
}
var mapping = {
authorized: _xdr2.default.TrustLineFlags.authorizedFlag(),
authorizedToMaintainLiabilities: _xdr2.default.TrustLineFlags.authorizedToMaintainLiabilitiesFlag(),
clawbackEnabled: _xdr2.default.TrustLineFlags.trustlineClawbackEnabledFlag()
};
/* eslint no-bitwise: "off" */
var clearFlag = 0;
var setFlag = 0;
Object.keys(opts.flags).forEach(function (flagName) {
if (!Object.prototype.hasOwnProperty.call(mapping, flagName)) {
throw new Error('unsupported flag name specified: ' + flagName);
}
var flagValue = opts.flags[flagName];
var bit = mapping[flagName].value;
if (flagValue === true) {
setFlag |= bit;
} else if (flagValue === false) {
clearFlag |= bit;
}
});
attributes.trustor = _keypair.Keypair.fromPublicKey(opts.trustor).xdrAccountId();
attributes.asset = opts.asset.toXDRObject();
attributes.clearFlags = clearFlag;
attributes.setFlags = setFlag;
var opAttributes = {
body: _xdr2.default.OperationBody.setTrustLineFlags(new _xdr2.default.SetTrustLineFlagsOp(attributes))
};
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 359 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.liquidityPoolDeposit = liquidityPoolDeposit;
var _isUndefined = __webpack_require__(7);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Creates a liquidity pool deposit operation.
*
* @function
* @alias Operation.liquidityPoolDeposit
* @see https://developers.stellar.org/docs/start/list-of-operations/#liquidity-pool-deposit
*
* @param {object} opts - Options object
* @param {string} opts.liquidityPoolId - The liquidity pool ID.
* @param {string} opts.maxAmountA - Maximum amount of first asset to deposit.
* @param {string} opts.maxAmountB - Maximum amount of second asset to deposit.
* @param {number|string|BigNumber|Object} opts.minPrice - Minimum depositA/depositB price.
* @param {number} opts.minPrice.n - If `opts.minPrice` is an object: the price numerator
* @param {number} opts.minPrice.d - If `opts.minPrice` is an object: the price denominator
* @param {number|string|BigNumber|Object} opts.maxPrice - Maximum depositA/depositB price.
* @param {number} opts.maxPrice.n - If `opts.maxPrice` is an object: the price numerator
* @param {number} opts.maxPrice.d - If `opts.maxPrice` is an object: the price denominator
* @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account.
*
* @returns {xdr.Operation} The resulting operation (xdr.LiquidityPoolDepositOp).
*/
function liquidityPoolDeposit() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var liquidityPoolId = opts.liquidityPoolId,
maxAmountA = opts.maxAmountA,
maxAmountB = opts.maxAmountB,
minPrice = opts.minPrice,
maxPrice = opts.maxPrice;
var attributes = {};
if (!liquidityPoolId) {
throw new TypeError('liquidityPoolId argument is required');
}
attributes.liquidityPoolId = _xdr2.default.PoolId.fromXDR(liquidityPoolId, 'hex');
if (!this.isValidAmount(maxAmountA, true)) {
throw new TypeError('maxAmountA argument is required');
}
attributes.maxAmountA = this._toXDRAmount(maxAmountA);
if (!this.isValidAmount(maxAmountB, true)) {
throw new TypeError('maxAmountB argument is required');
}
attributes.maxAmountB = this._toXDRAmount(maxAmountB);
if ((0, _isUndefined2.default)(minPrice)) {
throw new TypeError('minPrice argument is required');
}
attributes.minPrice = this._toXDRPrice(minPrice);
if ((0, _isUndefined2.default)(maxPrice)) {
throw new TypeError('maxPrice argument is required');
}
attributes.maxPrice = this._toXDRPrice(maxPrice);
var liquidityPoolDepositOp = new _xdr2.default.LiquidityPoolDepositOp(attributes);
var opAttributes = {
body: _xdr2.default.OperationBody.liquidityPoolDeposit(liquidityPoolDepositOp)
};
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 360 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.liquidityPoolWithdraw = liquidityPoolWithdraw;
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Creates a liquidity pool withdraw operation.
*
* @function
* @alias Operation.liquidityPoolWithdraw
* @see https://developers.stellar.org/docs/start/list-of-operations/#liquidity-pool-withdraw
*
* @param {object} opts - Options object
* @param {string} opts.liquidityPoolId - The liquidity pool ID.
* @param {string} opts.amount - Amount of pool shares to withdraw.
* @param {string} opts.minAmountA - Minimum amount of first asset to withdraw.
* @param {string} opts.minAmountB - Minimum amount of second asset to withdraw.
* @param {string} [opts.source] - The source account for the operation. Defaults to the transaction's source account.
*
* @returns {xdr.Operation} The resulting operation (xdr.LiquidityPoolWithdrawOp).
*/
function liquidityPoolWithdraw() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var attributes = {};
if (!opts.liquidityPoolId) {
throw new TypeError('liquidityPoolId argument is required');
}
attributes.liquidityPoolId = _xdr2.default.PoolId.fromXDR(opts.liquidityPoolId, 'hex');
if (!this.isValidAmount(opts.amount)) {
throw new TypeError('amount argument is required');
}
attributes.amount = this._toXDRAmount(opts.amount);
if (!this.isValidAmount(opts.minAmountA, true)) {
throw new TypeError('minAmountA argument is required');
}
attributes.minAmountA = this._toXDRAmount(opts.minAmountA);
if (!this.isValidAmount(opts.minAmountB, true)) {
throw new TypeError('minAmountB argument is required');
}
attributes.minAmountB = this._toXDRAmount(opts.minAmountB);
var liquidityPoolWithdrawOp = new _xdr2.default.LiquidityPoolWithdrawOp(attributes);
var opAttributes = {
body: _xdr2.default.OperationBody.liquidityPoolWithdraw(liquidityPoolWithdrawOp)
};
this.setSourceAccount(opAttributes, opts);
return new _xdr2.default.Operation(opAttributes);
}
/***/ }),
/* 361 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TransactionBuilder = exports.TimeoutInfinite = exports.BASE_FEE = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
exports.isValidDate = isValidDate;
var _jsXdr = __webpack_require__(22);
var _bignumber = __webpack_require__(23);
var _bignumber2 = _interopRequireDefault(_bignumber);
var _clone = __webpack_require__(28);
var _clone2 = _interopRequireDefault(_clone);
var _isUndefined = __webpack_require__(7);
var _isUndefined2 = _interopRequireDefault(_isUndefined);
var _isString = __webpack_require__(9);
var _isString2 = _interopRequireDefault(_isString);
var _isArray = __webpack_require__(3);
var _isArray2 = _interopRequireDefault(_isArray);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _transaction = __webpack_require__(87);
var _fee_bump_transaction = __webpack_require__(148);
var _signerkey = __webpack_require__(149);
var _memo = __webpack_require__(90);
var _decode_encode_muxed_account = __webpack_require__(17);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Minimum base fee for transactions. If this fee is below the network
* minimum, the transaction will fail. The more operations in the
* transaction, the greater the required fee. Use {@link
* Server#fetchBaseFee} to get an accurate value of minimum transaction
* fee on the network.
*
* @constant
* @see [Fees](https://developers.stellar.org/docs/glossary/fees/)
*/
var BASE_FEE = exports.BASE_FEE = '100'; // Stroops
/**
* @constant
* @see {@link TransactionBuilder#setTimeout}
* @see [Timeout](https://developers.stellar.org/api/resources/transactions/post/)
*/
var TimeoutInfinite = exports.TimeoutInfinite = 0;
/**
* <p>Transaction builder helps constructs a new `{@link Transaction}` using the
* given {@link Account} as the transaction's "source account". The transaction
* will use the current sequence number of the given account as its sequence
* number and increment the given account's sequence number by one. The given
* source account must include a private key for signing the transaction or an
* error will be thrown.</p>
*
* <p>Operations can be added to the transaction via their corresponding builder
* methods, and each returns the TransactionBuilder object so they can be
* chained together. After adding the desired operations, call the `build()`
* method on the `TransactionBuilder` to return a fully constructed `{@link
* Transaction}` that can be signed. The returned transaction will contain the
* sequence number of the source account and include the signature from the
* source account.</p>
*
* <p><strong>Be careful about unsubmitted transactions!</strong> When you build
* a transaction, stellar-sdk automatically increments the source account's
* sequence number. If you end up not submitting this transaction and submitting
* another one instead, it'll fail due to the sequence number being wrong. So if
* you decide not to use a built transaction, make sure to update the source
* account's sequence number with
* [Server.loadAccount](https://stellar.github.io/js-stellar-sdk/Server.html#loadAccount)
* before creating another transaction.</p>
*
* <p>The following code example creates a new transaction with {@link
* Operation.createAccount} and {@link Operation.payment} operations. The
* Transaction's source account first funds `destinationA`, then sends a payment
* to `destinationB`. The built transaction is then signed by
* `sourceKeypair`.</p>
*
* ```
* var transaction = new TransactionBuilder(source, { fee, networkPassphrase: Networks.TESTNET })
* .addOperation(Operation.createAccount({
* destination: destinationA,
* startingBalance: "20"
* })) // <- funds and creates destinationA
* .addOperation(Operation.payment({
* destination: destinationB,
* amount: "100",
* asset: Asset.native()
* })) // <- sends 100 XLM to destinationB
* .setTimeout(30)
* .build();
*
* transaction.sign(sourceKeypair);
* ```
*
* @constructor
*
* @param {Account} sourceAccount - source account for this transaction
* @param {object} opts - Options object
* @param {string} opts.fee - max fee you're willing to pay per
* operation in this transaction (**in stroops**)
*
* @param {object} [opts.timebounds] - timebounds for the
* validity of this transaction
* @param {number|string|Date} [opts.timebounds.minTime] - 64-bit UNIX
* timestamp or Date object
* @param {number|string|Date} [opts.timebounds.maxTime] - 64-bit UNIX
* timestamp or Date object
* @param {object} [opts.ledgerbounds] - ledger bounds for the
* validity of this transaction
* @param {number} [opts.ledgerbounds.minLedger] - number of the minimum
* ledger sequence
* @param {number} [opts.ledgerbounds.maxLedger] - number of the maximum
* ledger sequence
* @param {string} [opts.minAccountSequence] - number for
* the minimum account sequence
* @param {number} [opts.minAccountSequenceAge] - number of
* seconds for the minimum account sequence age
* @param {number} [opts.minAccountSequenceLedgerGap] - number of
* ledgers for the minimum account sequence ledger gap
* @param {string[]} [opts.extraSigners] - list of the extra signers
* required for this transaction
* @param {Memo} [opts.memo] - memo for the transaction
* @param {string} [opts.networkPassphrase] passphrase of the
* target Stellar network (e.g. "Public Global Stellar Network ; September
* 2015" for the pubnet)
*/
var TransactionBuilder = exports.TransactionBuilder = function () {
function TransactionBuilder(sourceAccount) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
_classCallCheck(this, TransactionBuilder);
if (!sourceAccount) {
throw new Error('must specify source account for the transaction');
}
if ((0, _isUndefined2.default)(opts.fee)) {
throw new Error('must specify fee for the transaction (in stroops)');
}
this.source = sourceAccount;
this.operations = [];
this.baseFee = opts.fee;
this.timebounds = (0, _clone2.default)(opts.timebounds) || null;
this.ledgerbounds = (0, _clone2.default)(opts.ledgerbounds) || null;
this.minAccountSequence = opts.minAccountSequence || null;
this.minAccountSequenceAge = opts.minAccountSequenceAge || null;
this.minAccountSequenceLedgerGap = opts.minAccountSequenceLedgerGap || null;
this.extraSigners = (0, _clone2.default)(opts.extraSigners) || null;
this.memo = opts.memo || _memo.Memo.none();
this.networkPassphrase = opts.networkPassphrase || null;
}
/**
* Adds an operation to the transaction.
*
* @param {xdr.Operation} operation The xdr operation object, use {@link
* Operation} static methods.
*
* @returns {TransactionBuilder}
*/
_createClass(TransactionBuilder, [{
key: 'addOperation',
value: function addOperation(operation) {
this.operations.push(operation);
return this;
}
/**
* Adds a memo to the transaction.
* @param {Memo} memo {@link Memo} object
* @returns {TransactionBuilder}
*/
}, {
key: 'addMemo',
value: function addMemo(memo) {
this.memo = memo;
return this;
}
/**
* Sets a timeout precondition on the transaction.
*
* Because of the distributed nature of the Stellar network it is possible
* that the status of your transaction will be determined after a long time
* if the network is highly congested. If you want to be sure to receive the
* status of the transaction within a given period you should set the {@link
* TimeBounds} with `maxTime` on the transaction (this is what `setTimeout`
* does internally; if there's `minTime` set but no `maxTime` it will be
* added).
*
* A call to `TransactionBuilder.setTimeout` is **required** if Transaction
* does not have `max_time` set. If you don't want to set timeout, use
* `{@link TimeoutInfinite}`. In general you should set `{@link
* TimeoutInfinite}` only in smart contracts.
*
* Please note that Horizon may still return <code>504 Gateway Timeout</code>
* error, even for short timeouts. In such case you need to resubmit the same
* transaction again without making any changes to receive a status. This
* method is using the machine system time (UTC), make sure it is set
* correctly.
*
* @param {number} timeoutSeconds Number of seconds the transaction is good.
* Can't be negative. If the value is {@link TimeoutInfinite}, the
* transaction is good indefinitely.
*
* @returns {TransactionBuilder}
*
* @see {@link TimeoutInfinite}
* @see https://developers.stellar.org/docs/tutorials/handling-errors/
*/
}, {
key: 'setTimeout',
value: function setTimeout(timeoutSeconds) {
if (this.timebounds !== null && this.timebounds.maxTime > 0) {
throw new Error('TimeBounds.max_time has been already set - setting timeout would overwrite it.');
}
if (timeoutSeconds < 0) {
throw new Error('timeout cannot be negative');
}
if (timeoutSeconds > 0) {
var timeoutTimestamp = Math.floor(Date.now() / 1000) + timeoutSeconds;
if (this.timebounds === null) {
this.timebounds = { minTime: 0, maxTime: timeoutTimestamp };
} else {
this.timebounds = {
minTime: this.timebounds.minTime,
maxTime: timeoutTimestamp
};
}
} else {
this.timebounds = {
minTime: 0,
maxTime: 0
};
}
return this;
}
/**
* If you want to prepare a transaction which will become valid at some point
* in the future, or be invalid after some time, you can set a timebounds
* precondition. Internally this will set the `minTime`, and `maxTime`
* preconditions. Conflicts with `setTimeout`, so use one or the other.
*
* @param {Date|number} minEpochOrDate Either a JS Date object, or a number
* of UNIX epoch seconds. The transaction is valid after this timestamp.
* Can't be negative. If the value is `0`, the transaction is valid
* immediately.
* @param {Date|number} maxEpochOrDate Either a JS Date object, or a number
* of UNIX epoch seconds. The transaction is valid until this timestamp.
* Can't be negative. If the value is `0`, the transaction is valid
* indefinitely.
*
* @returns {TransactionBuilder}
*/
}, {
key: 'setTimebounds',
value: function setTimebounds(minEpochOrDate, maxEpochOrDate) {
// Force it to a date type
if (typeof minEpochOrDate === 'number') {
minEpochOrDate = new Date(minEpochOrDate * 1000);
}
if (typeof maxEpochOrDate === 'number') {
maxEpochOrDate = new Date(maxEpochOrDate * 1000);
}
if (this.timebounds !== null) {
throw new Error('TimeBounds has been already set - setting timebounds would overwrite it.');
}
// Convert that date to the epoch seconds
var minTime = Math.floor(minEpochOrDate.valueOf() / 1000);
var maxTime = Math.floor(maxEpochOrDate.valueOf() / 1000);
if (minTime < 0) {
throw new Error('min_time cannot be negative');
}
if (maxTime < 0) {
throw new Error('max_time cannot be negative');
}
if (maxTime > 0 && minTime > maxTime) {
throw new Error('min_time cannot be greater than max_time');
}
this.timebounds = { minTime: minTime, maxTime: maxTime };
return this;
}
/**
* If you want to prepare a transaction which will only be valid within some
* range of ledgers, you can set a ledgerbounds precondition.
* Internally this will set the `minLedger` and `maxLedger` preconditions.
*
* @param {number} minLedger The minimum ledger this transaction is valid at
* or after. Cannot be negative. If the value is `0` (the default), the
* transaction is valid immediately.
*
* @param {number} maxLedger The maximum ledger this transaction is valid
* before. Cannot be negative. If the value is `0`, the transaction is
* valid indefinitely.
*
* @returns {TransactionBuilder}
*/
}, {
key: 'setLedgerbounds',
value: function setLedgerbounds(minLedger, maxLedger) {
if (this.ledgerbounds !== null) {
throw new Error('LedgerBounds has been already set - setting ledgerbounds would overwrite it.');
}
if (minLedger < 0) {
throw new Error('min_ledger cannot be negative');
}
if (maxLedger < 0) {
throw new Error('max_ledger cannot be negative');
}
if (maxLedger > 0 && minLedger > maxLedger) {
throw new Error('min_ledger cannot be greater than max_ledger');
}
this.ledgerbounds = { minLedger: minLedger, maxLedger: maxLedger };
return this;
}
/**
* If you want to prepare a transaction which will be valid only while the
* account sequence number is
*
* minAccountSequence <= sourceAccountSequence < tx.seqNum
*
* Note that after execution the account's sequence number is always raised to
* `tx.seqNum`. Internally this will set the `minAccountSequence`
* precondition.
*
* @param {string} minAccountSequence The minimum source account sequence
* number this transaction is valid for. If the value is `0` (the
* default), the transaction is valid when `sourceAccount's sequence
* number == tx.seqNum- 1`.
*
* @returns {TransactionBuilder}
*/
}, {
key: 'setMinAccountSequence',
value: function setMinAccountSequence(minAccountSequence) {
if (this.minAccountSequence !== null) {
throw new Error('min_account_sequence has been already set - setting min_account_sequence would overwrite it.');
}
this.minAccountSequence = minAccountSequence;
return this;
}
/**
* For the transaction to be valid, the current ledger time must be at least
* `minAccountSequenceAge` greater than sourceAccount's `sequenceTime`.
* Internally this will set the `minAccountSequenceAge` precondition.
*
* @param {number} durationInSeconds The minimum amount of time between
* source account sequence time and the ledger time when this transaction
* will become valid. If the value is `0`, the transaction is unrestricted
* by the account sequence age. Cannot be negative.
*
* @returns {TransactionBuilder}
*/
}, {
key: 'setMinAccountSequenceAge',
value: function setMinAccountSequenceAge(durationInSeconds) {
if (typeof durationInSeconds !== 'number') {
throw new Error('min_account_sequence_age must be a number');
}
if (this.minAccountSequenceAge !== null) {
throw new Error('min_account_sequence_age has been already set - setting min_account_sequence_age would overwrite it.');
}
if (durationInSeconds < 0) {
throw new Error('min_account_sequence_age cannot be negative');
}
this.minAccountSequenceAge = durationInSeconds;
return this;
}
/**
* For the transaction to be valid, the current ledger number must be at least
* `minAccountSequenceLedgerGap` greater than sourceAccount's ledger sequence.
* Internally this will set the `minAccountSequenceLedgerGap` precondition.
*
* @param {number} gap The minimum number of ledgers between source account
* sequence and the ledger number when this transaction will become valid.
* If the value is `0`, the transaction is unrestricted by the account
* sequence ledger. Cannot be negative.
*
* @returns {TransactionBuilder}
*/
}, {
key: 'setMinAccountSequenceLedgerGap',
value: function setMinAccountSequenceLedgerGap(gap) {
if (this.minAccountSequenceLedgerGap !== null) {
throw new Error('min_account_sequence_ledger_gap has been already set - setting min_account_sequence_ledger_gap would overwrite it.');
}
if (gap < 0) {
throw new Error('min_account_sequence_ledger_gap cannot be negative');
}
this.minAccountSequenceLedgerGap = gap;
return this;
}
/**
* For the transaction to be valid, there must be a signature corresponding to
* every Signer in this array, even if the signature is not otherwise required
* by the sourceAccount or operations. Internally this will set the
* `extraSigners` precondition.
*
* @param {string[]} extraSigners required extra signers (as {@link StrKey}s)
*
* @returns {TransactionBuilder}
*/
}, {
key: 'setExtraSigners',
value: function setExtraSigners(extraSigners) {
if (!(0, _isArray2.default)(extraSigners)) {
throw new Error('extra_signers must be an array of strings.');
}
if (this.extraSigners !== null) {
throw new Error('extra_signers has been already set - setting extra_signers would overwrite it.');
}
if (extraSigners.length > 2) {
throw new Error('extra_signers cannot be longer than 2 elements.');
}
this.extraSigners = (0, _clone2.default)(extraSigners);
return this;
}
/**
* Set network nassphrase for the Transaction that will be built.
*
* @param {string} networkPassphrase passphrase of the target Stellar
* network (e.g. "Public Global Stellar Network ; September 2015").
*
* @returns {TransactionBuilder}
*/
}, {
key: 'setNetworkPassphrase',
value: function setNetworkPassphrase(networkPassphrase) {
this.networkPassphrase = networkPassphrase;
return this;
}
/**
* This will build the transaction.
* It will also increment the source account's sequence number by 1.
* @returns {Transaction} This method will return the built {@link Transaction}.
*/
}, {
key: 'build',
value: function build() {
var sequenceNumber = new _bignumber2.default(this.source.sequenceNumber()).add(1);
var fee = new _bignumber2.default(this.baseFee).mul(this.operations.length).toNumber();
var attrs = {
fee: fee,
seqNum: _xdr2.default.SequenceNumber.fromString(sequenceNumber.toString()),
memo: this.memo ? this.memo.toXDRObject() : null
};
if (this.timebounds === null || typeof this.timebounds.minTime === 'undefined' || typeof this.timebounds.maxTime === 'undefined') {
throw new Error('TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).');
}
if (isValidDate(this.timebounds.minTime)) {
this.timebounds.minTime = this.timebounds.minTime.getTime() / 1000;
}
if (isValidDate(this.timebounds.maxTime)) {
this.timebounds.maxTime = this.timebounds.maxTime.getTime() / 1000;
}
this.timebounds.minTime = _jsXdr.UnsignedHyper.fromString(this.timebounds.minTime.toString());
this.timebounds.maxTime = _jsXdr.UnsignedHyper.fromString(this.timebounds.maxTime.toString());
var timeBounds = new _xdr2.default.TimeBounds(this.timebounds);
if (this.hasV2Preconditions()) {
var ledgerBounds = null;
if (this.ledgerbounds !== null) {
ledgerBounds = new _xdr2.default.LedgerBounds(this.ledgerbounds);
}
var minSeqNum = this.minAccountSequence || '0';
minSeqNum = _xdr2.default.SequenceNumber.fromString(minSeqNum);
var minSeqAge = _jsXdr.UnsignedHyper.fromString(this.minAccountSequenceAge !== null ? this.minAccountSequenceAge.toString() : '0');
var minSeqLedgerGap = this.minAccountSequenceLedgerGap || 0;
var extraSigners = this.extraSigners !== null ? this.extraSigners.map(_signerkey.SignerKey.decodeAddress) : [];
attrs.cond = _xdr2.default.Preconditions.precondV2(new _xdr2.default.PreconditionsV2({
timeBounds: timeBounds,
ledgerBounds: ledgerBounds,
minSeqNum: minSeqNum,
minSeqAge: minSeqAge,
minSeqLedgerGap: minSeqLedgerGap,
extraSigners: extraSigners
}));
} else {
attrs.cond = _xdr2.default.Preconditions.precondTime(timeBounds);
}
attrs.sourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(this.source.accountId());
attrs.ext = new _xdr2.default.TransactionExt(0);
var xtx = new _xdr2.default.Transaction(attrs);
xtx.operations(this.operations);
var txEnvelope = new _xdr2.default.TransactionEnvelope.envelopeTypeTx(new _xdr2.default.TransactionV1Envelope({ tx: xtx }));
var tx = new _transaction.Transaction(txEnvelope, this.networkPassphrase);
this.source.incrementSequenceNumber();
return tx;
}
}, {
key: 'hasV2Preconditions',
value: function hasV2Preconditions() {
return this.ledgerbounds !== null || this.minAccountSequence !== null || this.minAccountSequenceAge !== null || this.minAccountSequenceLedgerGap !== null || this.extraSigners !== null && this.extraSigners.length > 0;
}
/**
* Builds a {@link FeeBumpTransaction}, enabling you to resubmit an existing
* transaction with a higher fee.
*
* @param {Keypair|string} feeSource - account paying for the transaction,
* in the form of either a Keypair (only the public key is used) or
* an account ID (in G... or M... form, but refer to `withMuxing`)
* @param {string} baseFee - max fee willing to pay per operation
* in inner transaction (**in stroops**)
* @param {Transaction} innerTx - {@link Transaction} to be bumped by
* the fee bump transaction
* @param {string} networkPassphrase - passphrase of the target
* Stellar network (e.g. "Public Global Stellar Network ; September 2015",
* see {@link Networks})
*
* @todo Alongside the next major version bump, this type signature can be
* changed to be less awkward: accept a MuxedAccount as the `feeSource`
* rather than a keypair or string.
*
* @note Your fee-bump amount should be >= 10x the original fee.
* @see https://developers.stellar.org/docs/glossary/fee-bumps/#replace-by-fee
*
* @returns {FeeBumpTransaction}
*/
}], [{
key: 'buildFeeBumpTransaction',
value: function buildFeeBumpTransaction(feeSource, baseFee, innerTx, networkPassphrase) {
var innerOps = innerTx.operations.length;
var innerBaseFeeRate = new _bignumber2.default(innerTx.fee).div(innerOps);
var base = new _bignumber2.default(baseFee);
// The fee rate for fee bump is at least the fee rate of the inner transaction
if (base.lessThan(innerBaseFeeRate)) {
throw new Error('Invalid baseFee, it should be at least ' + innerBaseFeeRate + ' stroops.');
}
var minBaseFee = new _bignumber2.default(BASE_FEE);
// The fee rate is at least the minimum fee
if (base.lessThan(minBaseFee)) {
throw new Error('Invalid baseFee, it should be at least ' + minBaseFee + ' stroops.');
}
var innerTxEnvelope = innerTx.toEnvelope();
if (innerTxEnvelope.switch() === _xdr2.default.EnvelopeType.envelopeTypeTxV0()) {
var v0Tx = innerTxEnvelope.v0().tx();
var v1Tx = new _xdr2.default.Transaction({
sourceAccount: new _xdr2.default.MuxedAccount.keyTypeEd25519(v0Tx.sourceAccountEd25519()),
fee: v0Tx.fee(),
seqNum: v0Tx.seqNum(),
cond: _xdr2.default.Preconditions.precondTime(v0Tx.timeBounds()),
memo: v0Tx.memo(),
operations: v0Tx.operations(),
ext: new _xdr2.default.TransactionExt(0)
});
innerTxEnvelope = new _xdr2.default.TransactionEnvelope.envelopeTypeTx(new _xdr2.default.TransactionV1Envelope({
tx: v1Tx,
signatures: innerTxEnvelope.v0().signatures()
}));
}
var feeSourceAccount = void 0;
if ((0, _isString2.default)(feeSource)) {
feeSourceAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(feeSource);
} else {
feeSourceAccount = feeSource.xdrMuxedAccount();
}
var tx = new _xdr2.default.FeeBumpTransaction({
feeSource: feeSourceAccount,
fee: _xdr2.default.Int64.fromString(base.mul(innerOps + 1).toString()),
innerTx: _xdr2.default.FeeBumpTransactionInnerTx.envelopeTypeTx(innerTxEnvelope.v1()),
ext: new _xdr2.default.FeeBumpTransactionExt(0)
});
var feeBumpTxEnvelope = new _xdr2.default.FeeBumpTransactionEnvelope({
tx: tx,
signatures: []
});
var envelope = new _xdr2.default.TransactionEnvelope.envelopeTypeTxFeeBump(feeBumpTxEnvelope);
return new _fee_bump_transaction.FeeBumpTransaction(envelope, networkPassphrase);
}
/**
* Build a {@link Transaction} or {@link FeeBumpTransaction} from an
* xdr.TransactionEnvelope.
*
* @param {string|xdr.TransactionEnvelope} envelope - The transaction envelope
* object or base64 encoded string.
* @param {string} networkPassphrase - The network passphrase of the target
* Stellar network (e.g. "Public Global Stellar Network ; September
* 2015"), see {@link Networks}.
*
* @returns {Transaction|FeeBumpTransaction}
*/
}, {
key: 'fromXDR',
value: function fromXDR(envelope, networkPassphrase) {
if (typeof envelope === 'string') {
envelope = _xdr2.default.TransactionEnvelope.fromXDR(envelope, 'base64');
}
if (envelope.switch() === _xdr2.default.EnvelopeType.envelopeTypeTxFeeBump()) {
return new _fee_bump_transaction.FeeBumpTransaction(envelope, networkPassphrase);
}
return new _transaction.Transaction(envelope, networkPassphrase);
}
}]);
return TransactionBuilder;
}();
/**
* Checks whether a provided object is a valid Date.
* @argument {Date} d date object
* @returns {boolean}
*/
function isValidDate(d) {
// isnan is okay here because it correctly checks for invalid date objects
// eslint-disable-next-line no-restricted-globals
return d instanceof Date && !isNaN(d);
}
/***/ }),
/* 362 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MuxedAccount = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _isString = __webpack_require__(9);
var _isString2 = _interopRequireDefault(_isString);
var _xdr = __webpack_require__(0);
var _xdr2 = _interopRequireDefault(_xdr);
var _account = __webpack_require__(150);
var _strkey = __webpack_require__(8);
var _decode_encode_muxed_account = __webpack_require__(17);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Represents a muxed account for transactions and operations.
*
* A muxed (or *multiplexed*) account (defined rigorously in
* [CAP-27](https://stellar.org/protocol/cap-27) and briefly in
* [SEP-23](https://stellar.org/protocol/sep-23)) is one that resolves a single
* Stellar `G...`` account to many different underlying IDs.
*
* For example, you may have a single Stellar address for accounting purposes:
* GA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJVSGZ
*
* Yet would like to use it for 4 different family members:
* 1: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAGZFQ
* 2: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAALIWQ
* 3: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAPYHQ
* 4: MA7QYNF7SOWQ3GLR2BGMZEHXAVIRZA4KVWLTJJFC7MGXUA74P7UJUAAAAAAAAAAAAQLQQ
*
* This object makes it easy to create muxed accounts from regular accounts,
* duplicate them, get/set the underlying IDs, etc. without mucking around with
* the raw XDR.
*
* Because muxed accounts are purely an off-chain convention, they all share the
* sequence number tied to their underlying G... account. Thus, this object
* *requires* an {@link Account} instance to be passed in, so that muxed
* instances of an account can collectively modify the sequence number whenever
* a muxed account is used as the source of a @{link Transaction} with {@link
* TransactionBuilder}.
*
* @constructor
*
* @param {Account} account - the @{link Account} instance representing the
* underlying G... address
* @param {string} id - a stringified uint64 value that represents the
* ID of the muxed account
*
* @link https://developers.stellar.org/docs/glossary/muxed-accounts/
*/
var MuxedAccount = exports.MuxedAccount = function () {
function MuxedAccount(baseAccount, id) {
_classCallCheck(this, MuxedAccount);
var accountId = baseAccount.accountId();
if (!_strkey.StrKey.isValidEd25519PublicKey(accountId)) {
throw new Error('accountId is invalid');
}
this.account = baseAccount;
this._muxedXdr = (0, _decode_encode_muxed_account.encodeMuxedAccount)(accountId, id);
this._mAddress = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(this._muxedXdr);
this._id = id;
}
/**
* Parses an M-address into a MuxedAccount object.
*
* @param {string} mAddress - an M-address to transform
* @param {string} sequenceNum - the sequence number of the underlying {@link
* Account}, to use for the underlying base account (@link
* MuxedAccount.baseAccount). If you're using the SDK, you can use
* `server.loadAccount` to fetch this if you don't know it.
*
* @return {MuxedAccount}
*/
_createClass(MuxedAccount, [{
key: 'baseAccount',
/**
* @return {Account} the underlying account object shared among all muxed
* accounts with this Stellar address
*/
value: function baseAccount() {
return this.account;
}
/**
* @return {string} the M-address representing this account's (G-address, ID)
*/
}, {
key: 'accountId',
value: function accountId() {
return this._mAddress;
}
}, {
key: 'id',
value: function id() {
return this._id;
}
}, {
key: 'setId',
value: function setId(id) {
if (!(0, _isString2.default)(id)) {
throw new Error('id should be a string representing a number (uint64)');
}
this._muxedXdr.med25519().id(_xdr2.default.Uint64.fromString(id));
this._mAddress = (0, _decode_encode_muxed_account.encodeMuxedAccountToAddress)(this._muxedXdr);
this._id = id;
return this;
}
/**
* Accesses the underlying account's sequence number.
* @return {string} strigified sequence number for the underlying account
*/
}, {
key: 'sequenceNumber',
value: function sequenceNumber() {
return this.account.sequenceNumber();
}
/**
* Increments the underlying account's sequence number by one.
* @return {void}
*/
}, {
key: 'incrementSequenceNumber',
value: function incrementSequenceNumber() {
return this.account.incrementSequenceNumber();
}
/**
* @return {xdr.MuxedAccount} the XDR object representing this muxed account's
* G-address and uint64 ID
*/
}, {
key: 'toXDRObject',
value: function toXDRObject() {
return this._muxedXdr;
}
}, {
key: 'equals',
value: function equals(otherMuxedAccount) {
return this.accountId() === otherMuxedAccount.accountId();
}
}], [{
key: 'fromAddress',
value: function fromAddress(mAddress, sequenceNum) {
var muxedAccount = (0, _decode_encode_muxed_account.decodeAddressToMuxedAccount)(mAddress);
var gAddress = (0, _decode_encode_muxed_account.extractBaseAddress)(mAddress);
var id = muxedAccount.med25519().id().toString();
return new MuxedAccount(new _account.Account(gAddress, sequenceNum), id);
}
}]);
return MuxedAccount;
}();
/***/ }),
/* 363 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Contains passphrases for common networks:
* * `Networks.PUBLIC`: `Public Global Stellar Network ; September 2015`
* * `Networks.TESTNET`: `Test SDF Network ; September 2015`
* @type {{PUBLIC: string, TESTNET: string}}
*/
var Networks = exports.Networks = {
PUBLIC: 'Public Global Stellar Network ; September 2015',
TESTNET: 'Test SDF Network ; September 2015'
};
/***/ }),
/* 364 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Server = exports.SUBMIT_TRANSACTION_TIMEOUT = void 0;
var tslib_1 = __webpack_require__(2);
var bignumber_js_1 = tslib_1.__importDefault(__webpack_require__(23));
var isEmpty_1 = tslib_1.__importDefault(__webpack_require__(365));
var merge_1 = tslib_1.__importDefault(__webpack_require__(366));
var stellar_base_1 = __webpack_require__(29);
var urijs_1 = tslib_1.__importDefault(__webpack_require__(37));
var call_builder_1 = __webpack_require__(6);
var config_1 = __webpack_require__(60);
var errors_1 = __webpack_require__(36);
var account_call_builder_1 = __webpack_require__(415);
var account_response_1 = __webpack_require__(95);
var assets_call_builder_1 = __webpack_require__(416);
var claimable_balances_call_builder_1 = __webpack_require__(417);
var effect_call_builder_1 = __webpack_require__(418);
var friendbot_builder_1 = __webpack_require__(419);
var ledger_call_builder_1 = __webpack_require__(420);
var liquidity_pool_call_builder_1 = __webpack_require__(421);
var offer_call_builder_1 = __webpack_require__(422);
var operation_call_builder_1 = __webpack_require__(423);
var orderbook_call_builder_1 = __webpack_require__(424);
var payment_call_builder_1 = __webpack_require__(425);
var strict_receive_path_call_builder_1 = __webpack_require__(426);
var strict_send_path_call_builder_1 = __webpack_require__(427);
var trade_aggregation_call_builder_1 = __webpack_require__(428);
var trades_call_builder_1 = __webpack_require__(429);
var transaction_call_builder_1 = __webpack_require__(430);
var horizon_axios_client_1 = tslib_1.__importStar(__webpack_require__(91));
exports.SUBMIT_TRANSACTION_TIMEOUT = 60 * 1000;
var STROOPS_IN_LUMEN = 10000000;
var ACCOUNT_REQUIRES_MEMO = "MQ==";
function _getAmountInLumens(amt) {
return new bignumber_js_1.default(amt).div(STROOPS_IN_LUMEN).toString();
}
var Server = (function () {
function Server(serverURL, opts) {
if (opts === void 0) { opts = {}; }
this.serverURL = urijs_1.default(serverURL);
var allowHttp = typeof opts.allowHttp === "undefined"
? config_1.Config.isAllowHttp()
: opts.allowHttp;
var customHeaders = {};
if (opts.appName) {
customHeaders["X-App-Name"] = opts.appName;
}
if (opts.appVersion) {
customHeaders["X-App-Version"] = opts.appVersion;
}
if (opts.authToken) {
customHeaders["X-Auth-Token"] = opts.authToken;
}
if (!isEmpty_1.default(customHeaders)) {
horizon_axios_client_1.default.interceptors.request.use(function (config) {
config.headers = merge_1.default(customHeaders, config.headers);
return config;
});
}
if (this.serverURL.protocol() !== "https" && !allowHttp) {
throw new Error("Cannot connect to insecure horizon server");
}
}
Server.prototype.fetchTimebounds = function (seconds, _isRetry) {
if (_isRetry === void 0) { _isRetry = false; }
return tslib_1.__awaiter(this, void 0, void 0, function () {
var currentTime;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
currentTime = horizon_axios_client_1.getCurrentServerTime(this.serverURL.hostname());
if (currentTime) {
return [2, {
minTime: 0,
maxTime: currentTime + seconds,
}];
}
if (_isRetry) {
return [2, {
minTime: 0,
maxTime: Math.floor(new Date().getTime() / 1000) + seconds,
}];
}
return [4, horizon_axios_client_1.default.get(urijs_1.default(this.serverURL).toString())];
case 1:
_a.sent();
return [4, this.fetchTimebounds(seconds, true)];
case 2: return [2, _a.sent()];
}
});
});
};
Server.prototype.fetchBaseFee = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var response;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4, this.feeStats()];
case 1:
response = _a.sent();
return [2, parseInt(response.last_ledger_base_fee, 10) || 100];
}
});
});
};
Server.prototype.feeStats = function () {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var cb;
return tslib_1.__generator(this, function (_a) {
cb = new call_builder_1.CallBuilder(urijs_1.default(this.serverURL));
cb.filter.push(["fee_stats"]);
return [2, cb.call()];
});
});
};
Server.prototype.submitTransaction = function (transaction, opts) {
if (opts === void 0) { opts = { skipMemoRequiredCheck: false }; }
return tslib_1.__awaiter(this, void 0, void 0, function () {
var tx;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!!opts.skipMemoRequiredCheck) return [3, 2];
return [4, this.checkMemoRequired(transaction)];
case 1:
_a.sent();
_a.label = 2;
case 2:
tx = encodeURIComponent(transaction
.toEnvelope()
.toXDR()
.toString("base64"));
return [2, horizon_axios_client_1.default.post(urijs_1.default(this.serverURL)
.segment("transactions")
.toString(), "tx=" + tx, { timeout: exports.SUBMIT_TRANSACTION_TIMEOUT })
.then(function (response) {
if (!response.data.result_xdr) {
return response.data;
}
var responseXDR = stellar_base_1.xdr.TransactionResult
.fromXDR(response.data.result_xdr, "base64");
var results = responseXDR.result().value();
var offerResults;
var hasManageOffer;
if (results.length) {
offerResults = results
.map(function (result, i) {
if (result.value().switch().name !== "manageBuyOffer" &&
result.value().switch().name !== "manageSellOffer") {
return null;
}
hasManageOffer = true;
var amountBought = new bignumber_js_1.default(0);
var amountSold = new bignumber_js_1.default(0);
var offerSuccess = result
.value()
.value()
.success();
var offersClaimed = offerSuccess
.offersClaimed()
.map(function (offerClaimedAtom) {
var offerClaimed = offerClaimedAtom.value();
var sellerId = "";
switch (offerClaimedAtom.switch()) {
case stellar_base_1.xdr.ClaimAtomType.claimAtomTypeV0():
sellerId = stellar_base_1.StrKey.encodeEd25519PublicKey(offerClaimed.sellerEd25519());
break;
case stellar_base_1.xdr.ClaimAtomType.claimAtomTypeOrderBook():
sellerId = stellar_base_1.StrKey.encodeEd25519PublicKey(offerClaimed.sellerId().ed25519());
break;
default:
throw new Error("Invalid offer result type: " +
offerClaimedAtom.switch());
}
var claimedOfferAmountBought = new bignumber_js_1.default(offerClaimed.amountBought().toString());
var claimedOfferAmountSold = new bignumber_js_1.default(offerClaimed.amountSold().toString());
amountBought = amountBought.add(claimedOfferAmountSold);
amountSold = amountSold.add(claimedOfferAmountBought);
var sold = stellar_base_1.Asset.fromOperation(offerClaimed.assetSold());
var bought = stellar_base_1.Asset.fromOperation(offerClaimed.assetBought());
var assetSold = {
type: sold.getAssetType(),
assetCode: sold.getCode(),
issuer: sold.getIssuer(),
};
var assetBought = {
type: bought.getAssetType(),
assetCode: bought.getCode(),
issuer: bought.getIssuer(),
};
return {
sellerId: sellerId,
offerId: offerClaimed.offerId().toString(),
assetSold: assetSold,
amountSold: _getAmountInLumens(claimedOfferAmountSold),
assetBought: assetBought,
amountBought: _getAmountInLumens(claimedOfferAmountBought),
};
});
var effect = offerSuccess.offer().switch().name;
var currentOffer;
if (typeof offerSuccess.offer().value === "function" &&
offerSuccess.offer().value()) {
var offerXDR = offerSuccess.offer().value();
currentOffer = {
offerId: offerXDR.offerId().toString(),
selling: {},
buying: {},
amount: _getAmountInLumens(offerXDR.amount().toString()),
price: {
n: offerXDR.price().n(),
d: offerXDR.price().d(),
},
};
var selling = stellar_base_1.Asset.fromOperation(offerXDR.selling());
currentOffer.selling = {
type: selling.getAssetType(),
assetCode: selling.getCode(),
issuer: selling.getIssuer(),
};
var buying = stellar_base_1.Asset.fromOperation(offerXDR.buying());
currentOffer.buying = {
type: buying.getAssetType(),
assetCode: buying.getCode(),
issuer: buying.getIssuer(),
};
}
return {
offersClaimed: offersClaimed,
effect: effect,
operationIndex: i,
currentOffer: currentOffer,
amountBought: _getAmountInLumens(amountBought),
amountSold: _getAmountInLumens(amountSold),
isFullyOpen: !offersClaimed.length && effect !== "manageOfferDeleted",
wasPartiallyFilled: !!offersClaimed.length && effect !== "manageOfferDeleted",
wasImmediatelyFilled: !!offersClaimed.length && effect === "manageOfferDeleted",
wasImmediatelyDeleted: !offersClaimed.length && effect === "manageOfferDeleted",
};
})
.filter(function (result) { return !!result; });
}
return Object.assign({}, response.data, {
offerResults: hasManageOffer ? offerResults : undefined,
});
})
.catch(function (response) {
if (response instanceof Error) {
return Promise.reject(response);
}
return Promise.reject(new errors_1.BadResponseError("Transaction submission failed. Server responded: " + response.status + " " + response.statusText, response.data));
})];
}
});
});
};
Server.prototype.accounts = function () {
return new account_call_builder_1.AccountCallBuilder(urijs_1.default(this.serverURL));
};
Server.prototype.claimableBalances = function () {
return new claimable_balances_call_builder_1.ClaimableBalanceCallBuilder(urijs_1.default(this.serverURL));
};
Server.prototype.ledgers = function () {
return new ledger_call_builder_1.LedgerCallBuilder(urijs_1.default(this.serverURL));
};
Server.prototype.transactions = function () {
return new transaction_call_builder_1.TransactionCallBuilder(urijs_1.default(this.serverURL));
};
Server.prototype.offers = function () {
return new offer_call_builder_1.OfferCallBuilder(urijs_1.default(this.serverURL));
};
Server.prototype.orderbook = function (selling, buying) {
return new orderbook_call_builder_1.OrderbookCallBuilder(urijs_1.default(this.serverURL), selling, buying);
};
Server.prototype.trades = function () {
return new trades_call_builder_1.TradesCallBuilder(urijs_1.default(this.serverURL));
};
Server.prototype.operations = function () {
return new operation_call_builder_1.OperationCallBuilder(urijs_1.default(this.serverURL));
};
Server.prototype.liquidityPools = function () {
return new liquidity_pool_call_builder_1.LiquidityPoolCallBuilder(urijs_1.default(this.serverURL));
};
Server.prototype.strictReceivePaths = function (source, destinationAsset, destinationAmount) {
return new strict_receive_path_call_builder_1.StrictReceivePathCallBuilder(urijs_1.default(this.serverURL), source, destinationAsset, destinationAmount);
};
Server.prototype.strictSendPaths = function (sourceAsset, sourceAmount, destination) {
return new strict_send_path_call_builder_1.StrictSendPathCallBuilder(urijs_1.default(this.serverURL), sourceAsset, sourceAmount, destination);
};
Server.prototype.payments = function () {
return new payment_call_builder_1.PaymentCallBuilder(urijs_1.default(this.serverURL));
};
Server.prototype.effects = function () {
return new effect_call_builder_1.EffectCallBuilder(urijs_1.default(this.serverURL));
};
Server.prototype.friendbot = function (address) {
return new friendbot_builder_1.FriendbotBuilder(urijs_1.default(this.serverURL), address);
};
Server.prototype.assets = function () {
return new assets_call_builder_1.AssetsCallBuilder(urijs_1.default(this.serverURL));
};
Server.prototype.loadAccount = function (accountId) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var res;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4, this.accounts()
.accountId(accountId)
.call()];
case 1:
res = _a.sent();
return [2, new account_response_1.AccountResponse(res)];
}
});
});
};
Server.prototype.tradeAggregation = function (base, counter, start_time, end_time, resolution, offset) {
return new trade_aggregation_call_builder_1.TradeAggregationCallBuilder(urijs_1.default(this.serverURL), base, counter, start_time, end_time, resolution, offset);
};
Server.prototype.checkMemoRequired = function (transaction) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var destinations, i, operation, destination, account, e_1;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
if (transaction instanceof stellar_base_1.FeeBumpTransaction) {
transaction = transaction.innerTransaction;
}
if (transaction.memo.type !== "none") {
return [2];
}
destinations = new Set();
i = 0;
_a.label = 1;
case 1:
if (!(i < transaction.operations.length)) return [3, 6];
operation = transaction.operations[i];
switch (operation.type) {
case "payment":
case "pathPaymentStrictReceive":
case "pathPaymentStrictSend":
case "accountMerge":
break;
default:
return [3, 5];
}
destination = operation.destination;
if (destinations.has(destination)) {
return [3, 5];
}
destinations.add(destination);
if (destination.startsWith("M")) {
return [3, 5];
}
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4, this.loadAccount(destination)];
case 3:
account = _a.sent();
if (account.data_attr["config.memo_required"] === ACCOUNT_REQUIRES_MEMO) {
throw new errors_1.AccountRequiresMemoError("account requires memo", destination, i);
}
return [3, 5];
case 4:
e_1 = _a.sent();
if (e_1 instanceof errors_1.AccountRequiresMemoError) {
throw e_1;
}
if (!(e_1 instanceof errors_1.NotFoundError)) {
throw e_1;
}
return [3, 5];
case 5:
i++;
return [3, 1];
case 6: return [2];
}
});
});
};
return Server;
}());
exports.Server = Server;
/***/ }),
/* 365 */
/***/ (function(module, exports, __webpack_require__) {
var baseKeys = __webpack_require__(111),
getTag = __webpack_require__(44),
isArguments = __webpack_require__(47),
isArray = __webpack_require__(3),
isArrayLike = __webpack_require__(25),
isBuffer = __webpack_require__(40),
isPrototype = __webpack_require__(49),
isTypedArray = __webpack_require__(48);
/** `Object#toString` result references. */
var mapTag = '[object Map]',
setTag = '[object Set]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value) &&
(isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
isBuffer(value) || isTypedArray(value) || isArguments(value))) {
return !value.length;
}
var tag = getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
if (isPrototype(value)) {
return !baseKeys(value).length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
module.exports = isEmpty;
/***/ }),
/* 366 */
/***/ (function(module, exports, __webpack_require__) {
var baseMerge = __webpack_require__(367),
createAssigner = __webpack_require__(109);
/**
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
*/
var merge = createAssigner(function(object, source, srcIndex) {
baseMerge(object, source, srcIndex);
});
module.exports = merge;
/***/ }),
/* 367 */
/***/ (function(module, exports, __webpack_require__) {
var Stack = __webpack_require__(52),
assignMergeValue = __webpack_require__(151),
baseFor = __webpack_require__(66),
baseMergeDeep = __webpack_require__(368),
isObject = __webpack_require__(18),
keysIn = __webpack_require__(24),
safeGet = __webpack_require__(152);
/**
* The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMerge(object, source, srcIndex, customizer, stack) {
if (object === source) {
return;
}
baseFor(source, function(srcValue, key) {
stack || (stack = new Stack);
if (isObject(srcValue)) {
baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
var newValue = customizer
? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)
: undefined;
if (newValue === undefined) {
newValue = srcValue;
}
assignMergeValue(object, key, newValue);
}
}, keysIn);
}
module.exports = baseMerge;
/***/ }),
/* 368 */
/***/ (function(module, exports, __webpack_require__) {
var assignMergeValue = __webpack_require__(151),
cloneBuffer = __webpack_require__(135),
cloneTypedArray = __webpack_require__(138),
copyArray = __webpack_require__(136),
initCloneObject = __webpack_require__(139),
isArguments = __webpack_require__(47),
isArray = __webpack_require__(3),
isArrayLikeObject = __webpack_require__(369),
isBuffer = __webpack_require__(40),
isFunction = __webpack_require__(50),
isObject = __webpack_require__(18),
isPlainObject = __webpack_require__(370),
isTypedArray = __webpack_require__(48),
safeGet = __webpack_require__(152),
toPlainObject = __webpack_require__(371);
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = safeGet(object, key),
srcValue = safeGet(source, key),
stacked = stack.get(srcValue);
if (stacked) {
assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer
? customizer(objValue, srcValue, (key + ''), object, source, stack)
: undefined;
var isCommon = newValue === undefined;
if (isCommon) {
var isArr = isArray(srcValue),
isBuff = !isArr && isBuffer(srcValue),
isTyped = !isArr && !isBuff && isTypedArray(srcValue);
newValue = srcValue;
if (isArr || isBuff || isTyped) {
if (isArray(objValue)) {
newValue = objValue;
}
else if (isArrayLikeObject(objValue)) {
newValue = copyArray(objValue);
}
else if (isBuff) {
isCommon = false;
newValue = cloneBuffer(srcValue, true);
}
else if (isTyped) {
isCommon = false;
newValue = cloneTypedArray(srcValue, true);
}
else {
newValue = [];
}
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
newValue = objValue;
if (isArguments(objValue)) {
newValue = toPlainObject(objValue);
}
else if (!isObject(objValue) || isFunction(objValue)) {
newValue = initCloneObject(srcValue);
}
}
else {
isCommon = false;
}
}
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack['delete'](srcValue);
}
assignMergeValue(object, key, newValue);
}
module.exports = baseMergeDeep;
/***/ }),
/* 369 */
/***/ (function(module, exports, __webpack_require__) {
var isArrayLike = __webpack_require__(25),
isObjectLike = __webpack_require__(12);
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
module.exports = isArrayLikeObject;
/***/ }),
/* 370 */
/***/ (function(module, exports, __webpack_require__) {
var baseGetTag = __webpack_require__(20),
getPrototype = __webpack_require__(83),
isObjectLike = __webpack_require__(12);
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for built-in method references. */
var funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
funcToString.call(Ctor) == objectCtorString;
}
module.exports = isPlainObject;
/***/ }),
/* 371 */
/***/ (function(module, exports, __webpack_require__) {
var copyObject = __webpack_require__(33),
keysIn = __webpack_require__(24);
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return copyObject(value, keysIn(value));
}
module.exports = toPlainObject;
/***/ }),
/* 372 */
/***/ (function(module, exports) {
module.exports = false;
/***/ }),
/* 373 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* URI.js - Mutating URLs
* URI Template Support - http://tools.ietf.org/html/rfc6570
*
* Version: 1.19.11
*
* Author: Rodney Rehm
* Web: http://medialize.github.io/URI.js/
*
* Licensed under
* MIT License http://www.opensource.org/licenses/mit-license
*
*/
(function (root, factory) {
'use strict';
// https://github.com/umdjs/umd/blob/master/returnExports.js
if ( true && module.exports) {
// Node
module.exports = factory(__webpack_require__(37));
} else if (true) {
// AMD. Register as an anonymous module.
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(37)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}(this, function (URI, root) {
'use strict';
// FIXME: v2.0.0 renamce non-camelCase properties to uppercase
/*jshint camelcase: false */
// save current URITemplate variable, if any
var _URITemplate = root && root.URITemplate;
var hasOwn = Object.prototype.hasOwnProperty;
function URITemplate(expression) {
// serve from cache where possible
if (URITemplate._cache[expression]) {
return URITemplate._cache[expression];
}
// Allow instantiation without the 'new' keyword
if (!(this instanceof URITemplate)) {
return new URITemplate(expression);
}
this.expression = expression;
URITemplate._cache[expression] = this;
return this;
}
function Data(data) {
this.data = data;
this.cache = {};
}
var p = URITemplate.prototype;
// list of operators and their defined options
var operators = {
// Simple string expansion
'' : {
prefix: '',
separator: ',',
named: false,
empty_name_separator: false,
encode : 'encode'
},
// Reserved character strings
'+' : {
prefix: '',
separator: ',',
named: false,
empty_name_separator: false,
encode : 'encodeReserved'
},
// Fragment identifiers prefixed by '#'
'#' : {
prefix: '#',
separator: ',',
named: false,
empty_name_separator: false,
encode : 'encodeReserved'
},
// Name labels or extensions prefixed by '.'
'.' : {
prefix: '.',
separator: '.',
named: false,
empty_name_separator: false,
encode : 'encode'
},
// Path segments prefixed by '/'
'/' : {
prefix: '/',
separator: '/',
named: false,
empty_name_separator: false,
encode : 'encode'
},
// Path parameter name or name=value pairs prefixed by ';'
';' : {
prefix: ';',
separator: ';',
named: true,
empty_name_separator: false,
encode : 'encode'
},
// Query component beginning with '?' and consisting
// of name=value pairs separated by '&'; an
'?' : {
prefix: '?',
separator: '&',
named: true,
empty_name_separator: true,
encode : 'encode'
},
// Continuation of query-style &name=value pairs
// within a literal query component.
'&' : {
prefix: '&',
separator: '&',
named: true,
empty_name_separator: true,
encode : 'encode'
}
// The operator characters equals ("="), comma (","), exclamation ("!"),
// at sign ("@"), and pipe ("|") are reserved for future extensions.
};
// storage for already parsed templates
URITemplate._cache = {};
// pattern to identify expressions [operator, variable-list] in template
URITemplate.EXPRESSION_PATTERN = /\{([^a-zA-Z0-9%_]?)([^\}]+)(\}|$)/g;
// pattern to identify variables [name, explode, maxlength] in variable-list
URITemplate.VARIABLE_PATTERN = /^([^*:.](?:\.?[^*:.])*)((\*)|:(\d+))?$/;
// pattern to verify variable name integrity
URITemplate.VARIABLE_NAME_PATTERN = /[^a-zA-Z0-9%_.]/;
// pattern to verify literal integrity
URITemplate.LITERAL_PATTERN = /[<>{}"`^| \\]/;
// expand parsed expression (expression, not template!)
URITemplate.expand = function(expression, data, opts) {
// container for defined options for the given operator
var options = operators[expression.operator];
// expansion type (include keys or not)
var type = options.named ? 'Named' : 'Unnamed';
// list of variables within the expression
var variables = expression.variables;
// result buffer for evaluating the expression
var buffer = [];
var d, variable, i;
for (i = 0; (variable = variables[i]); i++) {
// fetch simplified data source
d = data.get(variable.name);
if (d.type === 0 && opts && opts.strict) {
throw new Error('Missing expansion value for variable "' + variable.name + '"');
}
if (!d.val.length) {
if (d.type) {
// empty variables (empty string)
// still lead to a separator being appended!
buffer.push('');
}
// no data, no action
continue;
}
if (d.type > 1 && variable.maxlength) {
// composite variable cannot specify maxlength
throw new Error('Invalid expression: Prefix modifier not applicable to variable "' + variable.name + '"');
}
// expand the given variable
buffer.push(URITemplate['expand' + type](
d,
options,
variable.explode,
variable.explode && options.separator || ',',
variable.maxlength,
variable.name
));
}
if (buffer.length) {
return options.prefix + buffer.join(options.separator);
} else {
// prefix is not prepended for empty expressions
return '';
}
};
// expand a named variable
URITemplate.expandNamed = function(d, options, explode, separator, length, name) {
// variable result buffer
var result = '';
// peformance crap
var encode = options.encode;
var empty_name_separator = options.empty_name_separator;
// flag noting if values are already encoded
var _encode = !d[encode].length;
// key for named expansion
var _name = d.type === 2 ? '': URI[encode](name);
var _value, i, l;
// for each found value
for (i = 0, l = d.val.length; i < l; i++) {
if (length) {
// maxlength must be determined before encoding can happen
_value = URI[encode](d.val[i][1].substring(0, length));
if (d.type === 2) {
// apply maxlength to keys of objects as well
_name = URI[encode](d.val[i][0].substring(0, length));
}
} else if (_encode) {
// encode value
_value = URI[encode](d.val[i][1]);
if (d.type === 2) {
// encode name and cache encoded value
_name = URI[encode](d.val[i][0]);
d[encode].push([_name, _value]);
} else {
// cache encoded value
d[encode].push([undefined, _value]);
}
} else {
// values are already encoded and can be pulled from cache
_value = d[encode][i][1];
if (d.type === 2) {
_name = d[encode][i][0];
}
}
if (result) {
// unless we're the first value, prepend the separator
result += separator;
}
if (!explode) {
if (!i) {
// first element, so prepend variable name
result += URI[encode](name) + (empty_name_separator || _value ? '=' : '');
}
if (d.type === 2) {
// without explode-modifier, keys of objects are returned comma-separated
result += _name + ',';
}
result += _value;
} else {
// only add the = if it is either default (?&) or there actually is a value (;)
result += _name + (empty_name_separator || _value ? '=' : '') + _value;
}
}
return result;
};
// expand an unnamed variable
URITemplate.expandUnnamed = function(d, options, explode, separator, length) {
// variable result buffer
var result = '';
// performance crap
var encode = options.encode;
var empty_name_separator = options.empty_name_separator;
// flag noting if values are already encoded
var _encode = !d[encode].length;
var _name, _value, i, l;
// for each found value
for (i = 0, l = d.val.length; i < l; i++) {
if (length) {
// maxlength must be determined before encoding can happen
_value = URI[encode](d.val[i][1].substring(0, length));
} else if (_encode) {
// encode and cache value
_value = URI[encode](d.val[i][1]);
d[encode].push([
d.type === 2 ? URI[encode](d.val[i][0]) : undefined,
_value
]);
} else {
// value already encoded, pull from cache
_value = d[encode][i][1];
}
if (result) {
// unless we're the first value, prepend the separator
result += separator;
}
if (d.type === 2) {
if (length) {
// maxlength also applies to keys of objects
_name = URI[encode](d.val[i][0].substring(0, length));
} else {
// at this point the name must already be encoded
_name = d[encode][i][0];
}
result += _name;
if (explode) {
// explode-modifier separates name and value by "="
result += (empty_name_separator || _value ? '=' : '');
} else {
// no explode-modifier separates name and value by ","
result += ',';
}
}
result += _value;
}
return result;
};
URITemplate.noConflict = function() {
if (root.URITemplate === URITemplate) {
root.URITemplate = _URITemplate;
}
return URITemplate;
};
// expand template through given data map
p.expand = function(data, opts) {
var result = '';
if (!this.parts || !this.parts.length) {
// lazilyy parse the template
this.parse();
}
if (!(data instanceof Data)) {
// make given data available through the
// optimized data handling thingie
data = new Data(data);
}
for (var i = 0, l = this.parts.length; i < l; i++) {
/*jshint laxbreak: true */
result += typeof this.parts[i] === 'string'
// literal string
? this.parts[i]
// expression
: URITemplate.expand(this.parts[i], data, opts);
/*jshint laxbreak: false */
}
return result;
};
// parse template into action tokens
p.parse = function() {
// performance crap
var expression = this.expression;
var ePattern = URITemplate.EXPRESSION_PATTERN;
var vPattern = URITemplate.VARIABLE_PATTERN;
var nPattern = URITemplate.VARIABLE_NAME_PATTERN;
var lPattern = URITemplate.LITERAL_PATTERN;
// token result buffer
var parts = [];
// position within source template
var pos = 0;
var variables, eMatch, vMatch;
var checkLiteral = function(literal) {
if (literal.match(lPattern)) {
throw new Error('Invalid Literal "' + literal + '"');
}
return literal;
};
// RegExp is shared accross all templates,
// which requires a manual reset
ePattern.lastIndex = 0;
// I don't like while(foo = bar()) loops,
// to make things simpler I go while(true) and break when required
while (true) {
eMatch = ePattern.exec(expression);
if (eMatch === null) {
// push trailing literal
parts.push(checkLiteral(expression.substring(pos)));
break;
} else {
// push leading literal
parts.push(checkLiteral(expression.substring(pos, eMatch.index)));
pos = eMatch.index + eMatch[0].length;
}
if (!operators[eMatch[1]]) {
throw new Error('Unknown Operator "' + eMatch[1] + '" in "' + eMatch[0] + '"');
} else if (!eMatch[3]) {
throw new Error('Unclosed Expression "' + eMatch[0] + '"');
}
// parse variable-list
variables = eMatch[2].split(',');
for (var i = 0, l = variables.length; i < l; i++) {
vMatch = variables[i].match(vPattern);
if (vMatch === null) {
throw new Error('Invalid Variable "' + variables[i] + '" in "' + eMatch[0] + '"');
} else if (vMatch[1].match(nPattern)) {
throw new Error('Invalid Variable Name "' + vMatch[1] + '" in "' + eMatch[0] + '"');
}
variables[i] = {
name: vMatch[1],
explode: !!vMatch[3],
maxlength: vMatch[4] && parseInt(vMatch[4], 10)
};
}
if (!variables.length) {
throw new Error('Expression Missing Variable(s) "' + eMatch[0] + '"');
}
parts.push({
expression: eMatch[0],
operator: eMatch[1],
variables: variables
});
}
if (!parts.length) {
// template doesn't contain any expressions
// so it is a simple literal string
// this probably should fire a warning or something?
parts.push(checkLiteral(expression));
}
this.parts = parts;
return this;
};
// simplify data structures
Data.prototype.get = function(key) {
// performance crap
var data = this.data;
// cache for processed data-point
var d = {
// type of data 0: undefined/null, 1: string, 2: object, 3: array
type: 0,
// original values (except undefined/null)
val: [],
// cache for encoded values (only for non-maxlength expansion)
encode: [],
encodeReserved: []
};
var i, l, value;
if (this.cache[key] !== undefined) {
// we've already processed this key
return this.cache[key];
}
this.cache[key] = d;
if (String(Object.prototype.toString.call(data)) === '[object Function]') {
// data itself is a callback (global callback)
value = data(key);
} else if (String(Object.prototype.toString.call(data[key])) === '[object Function]') {
// data is a map of callbacks (local callback)
value = data[key](key);
} else {
// data is a map of data
value = data[key];
}
// generalize input into [ [name1, value1], [name2, value2], … ]
// so expansion has to deal with a single data structure only
if (value === undefined || value === null) {
// undefined and null values are to be ignored completely
return d;
} else if (String(Object.prototype.toString.call(value)) === '[object Array]') {
for (i = 0, l = value.length; i < l; i++) {
if (value[i] !== undefined && value[i] !== null) {
// arrays don't have names
d.val.push([undefined, String(value[i])]);
}
}
if (d.val.length) {
// only treat non-empty arrays as arrays
d.type = 3; // array
}
} else if (String(Object.prototype.toString.call(value)) === '[object Object]') {
for (i in value) {
if (hasOwn.call(value, i) && value[i] !== undefined && value[i] !== null) {
// objects have keys, remember them for named expansion
d.val.push([i, String(value[i])]);
}
}
if (d.val.length) {
// only treat non-empty objects as objects
d.type = 2; // object
}
} else {
d.type = 1; // primitive string (could've been string, number, boolean and objects with a toString())
// arrays don't have names
d.val.push([undefined, String(value)]);
}
return d;
};
// hook into URI for fluid access
URI.expand = function(expression, data) {
var template = new URITemplate(expression);
var expansion = template.expand(data);
return new URI(expansion);
};
return URITemplate;
}));
/***/ }),
/* 374 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(10);
var bind = __webpack_require__(156);
var Axios = __webpack_require__(375);
var mergeConfig = __webpack_require__(162);
var defaults = __webpack_require__(62);
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
* @return {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios.prototype, context);
// Copy context to instance
utils.extend(instance, context);
// Factory for creating new instances
instance.create = function create(instanceConfig) {
return createInstance(mergeConfig(defaultConfig, instanceConfig));
};
return instance;
}
// Create the default instance to be exported
var axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Expose Cancel & CancelToken
axios.Cancel = __webpack_require__(63);
axios.CancelToken = __webpack_require__(388);
axios.isCancel = __webpack_require__(161);
axios.VERSION = __webpack_require__(163).version;
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = __webpack_require__(389);
// Expose isAxiosError
axios.isAxiosError = __webpack_require__(390);
module.exports = axios;
// Allow use of default import syntax in TypeScript
module.exports.default = axios;
/***/ }),
/* 375 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(10);
var buildURL = __webpack_require__(157);
var InterceptorManager = __webpack_require__(376);
var dispatchRequest = __webpack_require__(377);
var mergeConfig = __webpack_require__(162);
var validator = __webpack_require__(387);
var validators = validator.validators;
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*/
function Axios(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
/**
* Dispatch a request
*
* @param {Object} config The config specific for this request (merged with this.defaults)
*/
Axios.prototype.request = function request(configOrUrl, config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof configOrUrl === 'string') {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
}
if (!config.url) {
throw new Error('Provided config url is not valid');
}
config = mergeConfig(this.defaults, config);
// Set config.method
if (config.method) {
config.method = config.method.toLowerCase();
} else if (this.defaults.method) {
config.method = this.defaults.method.toLowerCase();
} else {
config.method = 'get';
}
var transitional = config.transitional;
if (transitional !== undefined) {
validator.assertOptions(transitional, {
silentJSONParsing: validators.transitional(validators.boolean),
forcedJSONParsing: validators.transitional(validators.boolean),
clarifyTimeoutError: validators.transitional(validators.boolean)
}, false);
}
// filter out skipped interceptors
var requestInterceptorChain = [];
var synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
});
var responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
var promise;
if (!synchronousRequestInterceptors) {
var chain = [dispatchRequest, undefined];
Array.prototype.unshift.apply(chain, requestInterceptorChain);
chain = chain.concat(responseInterceptorChain);
promise = Promise.resolve(config);
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
}
var newConfig = config;
while (requestInterceptorChain.length) {
var onFulfilled = requestInterceptorChain.shift();
var onRejected = requestInterceptorChain.shift();
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected(error);
break;
}
}
try {
promise = dispatchRequest(newConfig);
} catch (error) {
return Promise.reject(error);
}
while (responseInterceptorChain.length) {
promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
}
return promise;
};
Axios.prototype.getUri = function getUri(config) {
if (!config.url) {
throw new Error('Provided config url is not valid');
}
config = mergeConfig(this.defaults, config);
return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
};
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(mergeConfig(config || {}, {
method: method,
url: url,
data: (config || {}).data
}));
};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, data, config) {
return this.request(mergeConfig(config || {}, {
method: method,
url: url,
data: data
}));
};
});
module.exports = Axios;
/***/ }),
/* 376 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(10);
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
module.exports = InterceptorManager;
/***/ }),
/* 377 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(10);
var transformData = __webpack_require__(378);
var isCancel = __webpack_require__(161);
var defaults = __webpack_require__(62);
var Cancel = __webpack_require__(63);
/**
* Throws a `Cancel` if cancellation has been requested.
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
if (config.signal && config.signal.aborted) {
throw new Cancel('canceled');
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
* @returns {Promise} The Promise to be fulfilled
*/
module.exports = function dispatchRequest(config) {
throwIfCancellationRequested(config);
// Ensure headers exist
config.headers = config.headers || {};
// Transform request data
config.data = transformData.call(
config,
config.data,
config.headers,
config.transformRequest
);
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
var adapter = config.adapter || defaults.adapter;
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Transform response data
response.data = transformData.call(
config,
response.data,
response.headers,
config.transformResponse
);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
reason.response.data = transformData.call(
config,
reason.response.data,
reason.response.headers,
config.transformResponse
);
}
}
return Promise.reject(reason);
});
};
/***/ }),
/* 378 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(10);
var defaults = __webpack_require__(62);
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Array|Function} fns A single function or Array of functions
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, fns) {
var context = this || defaults;
/*eslint no-param-reassign:0*/
utils.forEach(fns, function transform(fn) {
data = fn.call(context, data, headers);
});
return data;
};
/***/ }),
/* 379 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(10);
module.exports = function normalizeHeaderName(headers, normalizedName) {
utils.forEach(headers, function processHeader(value, name) {
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
headers[normalizedName] = value;
delete headers[name];
}
});
};
/***/ }),
/* 380 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var createError = __webpack_require__(160);
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(createError(
'Request failed with status code ' + response.status,
response.config,
null,
response.request,
response
));
}
};
/***/ }),
/* 381 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(10);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
/***/ }),
/* 382 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var isAbsoluteURL = __webpack_require__(383);
var combineURLs = __webpack_require__(384);
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
* @returns {string} The combined full path
*/
module.exports = function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
};
/***/ }),
/* 383 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
module.exports = function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
};
/***/ }),
/* 384 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
* @returns {string} The combined URL
*/
module.exports = function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
};
/***/ }),
/* 385 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(10);
// Headers whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
var ignoreDuplicateOf = [
'age', 'authorization', 'content-length', 'content-type', 'etag',
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
'referer', 'retry-after', 'user-agent'
];
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} headers Headers needing to be parsed
* @returns {Object} Headers parsed into an object
*/
module.exports = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
if (!headers) { return parsed; }
utils.forEach(headers.split('\n'), function parser(line) {
i = line.indexOf(':');
key = utils.trim(line.substr(0, i)).toLowerCase();
val = utils.trim(line.substr(i + 1));
if (key) {
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
return;
}
if (key === 'set-cookie') {
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
}
});
return parsed;
};
/***/ }),
/* 386 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(10);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement('a');
var originURL;
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
var href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})()
);
/***/ }),
/* 387 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var VERSION = __webpack_require__(163).version;
var validators = {};
// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {
validators[type] = function validator(thing) {
return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
};
});
var deprecatedWarnings = {};
/**
* Transitional option validator
* @param {function|boolean?} validator - set to false if the transitional option has been removed
* @param {string?} version - deprecated version / removed since version
* @param {string?} message - some message with additional info
* @returns {function}
*/
validators.transitional = function transitional(validator, version, message) {
function formatMessage(opt, desc) {
return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
}
// eslint-disable-next-line func-names
return function(value, opt, opts) {
if (validator === false) {
throw new Error(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')));
}
if (version && !deprecatedWarnings[opt]) {
deprecatedWarnings[opt] = true;
// eslint-disable-next-line no-console
console.warn(
formatMessage(
opt,
' has been deprecated since v' + version + ' and will be removed in the near future'
)
);
}
return validator ? validator(value, opt, opts) : true;
};
};
/**
* Assert object's properties type
* @param {object} options
* @param {object} schema
* @param {boolean?} allowUnknown
*/
function assertOptions(options, schema, allowUnknown) {
if (typeof options !== 'object') {
throw new TypeError('options must be an object');
}
var keys = Object.keys(options);
var i = keys.length;
while (i-- > 0) {
var opt = keys[i];
var validator = schema[opt];
if (validator) {
var value = options[opt];
var result = value === undefined || validator(value, opt, options);
if (result !== true) {
throw new TypeError('option ' + opt + ' must be ' + result);
}
continue;
}
if (allowUnknown !== true) {
throw Error('Unknown option ' + opt);
}
}
}
module.exports = {
assertOptions: assertOptions,
validators: validators
};
/***/ }),
/* 388 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Cancel = __webpack_require__(63);
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @class
* @param {Function} executor The executor function.
*/
function CancelToken(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
// eslint-disable-next-line func-names
this.promise.then(function(cancel) {
if (!token._listeners) return;
var i;
var l = token._listeners.length;
for (i = 0; i < l; i++) {
token._listeners[i](cancel);
}
token._listeners = null;
});
// eslint-disable-next-line func-names
this.promise.then = function(onfulfilled) {
var _resolve;
// eslint-disable-next-line func-names
var promise = new Promise(function(resolve) {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
executor(function cancel(message) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new Cancel(message);
resolvePromise(token.reason);
});
}
/**
* Throws a `Cancel` if cancellation has been requested.
*/
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
};
/**
* Subscribe to the cancel signal
*/
CancelToken.prototype.subscribe = function subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
};
/**
* Unsubscribe from the cancel signal
*/
CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
if (!this._listeners) {
return;
}
var index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
};
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token: token,
cancel: cancel
};
};
module.exports = CancelToken;
/***/ }),
/* 389 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* var args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
* @returns {Function}
*/
module.exports = function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
/***/ }),
/* 390 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(10);
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
module.exports = function isAxiosError(payload) {
return utils.isObject(payload) && (payload.isAxiosError === true);
};
/***/ }),
/* 391 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var parse = __webpack_require__(392);
/**
* Transform an URL to a valid origin value.
*
* @param {String|Object} url URL to transform to it's origin.
* @returns {String} The origin.
* @api public
*/
function origin(url) {
if ('string' === typeof url) url = parse(url);
//
// 6.2. ASCII Serialization of an Origin
// http://tools.ietf.org/html/rfc6454#section-6.2
//
if (!url.protocol || !url.hostname) return 'null';
//
// 4. Origin of a URI
// http://tools.ietf.org/html/rfc6454#section-4
//
// States that url.scheme, host should be converted to lower case. This also
// makes it easier to match origins as everything is just lower case.
//
return (url.protocol +'//'+ url.host).toLowerCase();
}
/**
* Check if the origins are the same.
*
* @param {String} a URL or origin of a.
* @param {String} b URL or origin of b.
* @returns {Boolean}
* @api public
*/
origin.same = function same(a, b) {
return origin(a) === origin(b);
};
//
// Expose the origin
//
module.exports = origin;
/***/ }),
/* 392 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {
var required = __webpack_require__(393)
, qs = __webpack_require__(394)
, controlOrWhitespace = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/
, CRHTLF = /[\n\r\t]/g
, slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//
, port = /:\d+$/
, protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i
, windowsDriveLetter = /^[a-zA-Z]:/;
/**
* Remove control characters and whitespace from the beginning of a string.
*
* @param {Object|String} str String to trim.
* @returns {String} A new string representing `str` stripped of control
* characters and whitespace from its beginning.
* @public
*/
function trimLeft(str) {
return (str ? str : '').toString().replace(controlOrWhitespace, '');
}
/**
* These are the parse rules for the URL parser, it informs the parser
* about:
*
* 0. The char it Needs to parse, if it's a string it should be done using
* indexOf, RegExp using exec and NaN means set as current value.
* 1. The property we should set when parsing this value.
* 2. Indication if it's backwards or forward parsing, when set as number it's
* the value of extra chars that should be split off.
* 3. Inherit from location if non existing in the parser.
* 4. `toLowerCase` the resulting value.
*/
var rules = [
['#', 'hash'], // Extract from the back.
['?', 'query'], // Extract from the back.
function sanitize(address, url) { // Sanitize what is left of the address
return isSpecial(url.protocol) ? address.replace(/\\/g, '/') : address;
},
['/', 'pathname'], // Extract from the back.
['@', 'auth', 1], // Extract from the front.
[NaN, 'host', undefined, 1, 1], // Set left over value.
[/:(\d*)$/, 'port', undefined, 1], // RegExp the back.
[NaN, 'hostname', undefined, 1, 1] // Set left over.
];
/**
* These properties should not be copied or inherited from. This is only needed
* for all non blob URL's as a blob URL does not include a hash, only the
* origin.
*
* @type {Object}
* @private
*/
var ignore = { hash: 1, query: 1 };
/**
* The location object differs when your code is loaded through a normal page,
* Worker or through a worker using a blob. And with the blobble begins the
* trouble as the location object will contain the URL of the blob, not the
* location of the page where our code is loaded in. The actual origin is
* encoded in the `pathname` so we can thankfully generate a good "default"
* location from it so we can generate proper relative URL's again.
*
* @param {Object|String} loc Optional default location object.
* @returns {Object} lolcation object.
* @public
*/
function lolcation(loc) {
var globalVar;
if (typeof window !== 'undefined') globalVar = window;
else if (typeof global !== 'undefined') globalVar = global;
else if (typeof self !== 'undefined') globalVar = self;
else globalVar = {};
var location = globalVar.location || {};
loc = loc || location;
var finaldestination = {}
, type = typeof loc
, key;
if ('blob:' === loc.protocol) {
finaldestination = new Url(unescape(loc.pathname), {});
} else if ('string' === type) {
finaldestination = new Url(loc, {});
for (key in ignore) delete finaldestination[key];
} else if ('object' === type) {
for (key in loc) {
if (key in ignore) continue;
finaldestination[key] = loc[key];
}
if (finaldestination.slashes === undefined) {
finaldestination.slashes = slashes.test(loc.href);
}
}
return finaldestination;
}
/**
* Check whether a protocol scheme is special.
*
* @param {String} The protocol scheme of the URL
* @return {Boolean} `true` if the protocol scheme is special, else `false`
* @private
*/
function isSpecial(scheme) {
return (
scheme === 'file:' ||
scheme === 'ftp:' ||
scheme === 'http:' ||
scheme === 'https:' ||
scheme === 'ws:' ||
scheme === 'wss:'
);
}
/**
* @typedef ProtocolExtract
* @type Object
* @property {String} protocol Protocol matched in the URL, in lowercase.
* @property {Boolean} slashes `true` if protocol is followed by "//", else `false`.
* @property {String} rest Rest of the URL that is not part of the protocol.
*/
/**
* Extract protocol information from a URL with/without double slash ("//").
*
* @param {String} address URL we want to extract from.
* @param {Object} location
* @return {ProtocolExtract} Extracted information.
* @private
*/
function extractProtocol(address, location) {
address = trimLeft(address);
address = address.replace(CRHTLF, '');
location = location || {};
var match = protocolre.exec(address);
var protocol = match[1] ? match[1].toLowerCase() : '';
var forwardSlashes = !!match[2];
var otherSlashes = !!match[3];
var slashesCount = 0;
var rest;
if (forwardSlashes) {
if (otherSlashes) {
rest = match[2] + match[3] + match[4];
slashesCount = match[2].length + match[3].length;
} else {
rest = match[2] + match[4];
slashesCount = match[2].length;
}
} else {
if (otherSlashes) {
rest = match[3] + match[4];
slashesCount = match[3].length;
} else {
rest = match[4]
}
}
if (protocol === 'file:') {
if (slashesCount >= 2) {
rest = rest.slice(2);
}
} else if (isSpecial(protocol)) {
rest = match[4];
} else if (protocol) {
if (forwardSlashes) {
rest = rest.slice(2);
}
} else if (slashesCount >= 2 && isSpecial(location.protocol)) {
rest = match[4];
}
return {
protocol: protocol,
slashes: forwardSlashes || isSpecial(protocol),
slashesCount: slashesCount,
rest: rest
};
}
/**
* Resolve a relative URL pathname against a base URL pathname.
*
* @param {String} relative Pathname of the relative URL.
* @param {String} base Pathname of the base URL.
* @return {String} Resolved pathname.
* @private
*/
function resolve(relative, base) {
if (relative === '') return base;
var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
, i = path.length
, last = path[i - 1]
, unshift = false
, up = 0;
while (i--) {
if (path[i] === '.') {
path.splice(i, 1);
} else if (path[i] === '..') {
path.splice(i, 1);
up++;
} else if (up) {
if (i === 0) unshift = true;
path.splice(i, 1);
up--;
}
}
if (unshift) path.unshift('');
if (last === '.' || last === '..') path.push('');
return path.join('/');
}
/**
* The actual URL instance. Instead of returning an object we've opted-in to
* create an actual constructor as it's much more memory efficient and
* faster and it pleases my OCD.
*
* It is worth noting that we should not use `URL` as class name to prevent
* clashes with the global URL instance that got introduced in browsers.
*
* @constructor
* @param {String} address URL we want to parse.
* @param {Object|String} [location] Location defaults for relative paths.
* @param {Boolean|Function} [parser] Parser for the query string.
* @private
*/
function Url(address, location, parser) {
address = trimLeft(address);
address = address.replace(CRHTLF, '');
if (!(this instanceof Url)) {
return new Url(address, location, parser);
}
var relative, extracted, parse, instruction, index, key
, instructions = rules.slice()
, type = typeof location
, url = this
, i = 0;
//
// The following if statements allows this module two have compatibility with
// 2 different API:
//
// 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
// where the boolean indicates that the query string should also be parsed.
//
// 2. The `URL` interface of the browser which accepts a URL, object as
// arguments. The supplied object will be used as default values / fall-back
// for relative paths.
//
if ('object' !== type && 'string' !== type) {
parser = location;
location = null;
}
if (parser && 'function' !== typeof parser) parser = qs.parse;
location = lolcation(location);
//
// Extract protocol information before running the instructions.
//
extracted = extractProtocol(address || '', location);
relative = !extracted.protocol && !extracted.slashes;
url.slashes = extracted.slashes || relative && location.slashes;
url.protocol = extracted.protocol || location.protocol || '';
address = extracted.rest;
//
// When the authority component is absent the URL starts with a path
// component.
//
if (
extracted.protocol === 'file:' && (
extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||
(!extracted.slashes &&
(extracted.protocol ||
extracted.slashesCount < 2 ||
!isSpecial(url.protocol)))
) {
instructions[3] = [/(.*)/, 'pathname'];
}
for (; i < instructions.length; i++) {
instruction = instructions[i];
if (typeof instruction === 'function') {
address = instruction(address, url);
continue;
}
parse = instruction[0];
key = instruction[1];
if (parse !== parse) {
url[key] = address;
} else if ('string' === typeof parse) {
index = parse === '@'
? address.lastIndexOf(parse)
: address.indexOf(parse);
if (~index) {
if ('number' === typeof instruction[2]) {
url[key] = address.slice(0, index);
address = address.slice(index + instruction[2]);
} else {
url[key] = address.slice(index);
address = address.slice(0, index);
}
}
} else if ((index = parse.exec(address))) {
url[key] = index[1];
address = address.slice(0, index.index);
}
url[key] = url[key] || (
relative && instruction[3] ? location[key] || '' : ''
);
//
// Hostname, host and protocol should be lowercased so they can be used to
// create a proper `origin`.
//
if (instruction[4]) url[key] = url[key].toLowerCase();
}
//
// Also parse the supplied query string in to an object. If we're supplied
// with a custom parser as function use that instead of the default build-in
// parser.
//
if (parser) url.query = parser(url.query);
//
// If the URL is relative, resolve the pathname against the base URL.
//
if (
relative
&& location.slashes
&& url.pathname.charAt(0) !== '/'
&& (url.pathname !== '' || location.pathname !== '')
) {
url.pathname = resolve(url.pathname, location.pathname);
}
//
// Default to a / for pathname if none exists. This normalizes the URL
// to always have a /
//
if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {
url.pathname = '/' + url.pathname;
}
//
// We should not add port numbers if they are already the default port number
// for a given protocol. As the host also contains the port number we're going
// override it with the hostname which contains no port number.
//
if (!required(url.port, url.protocol)) {
url.host = url.hostname;
url.port = '';
}
//
// Parse down the `auth` for the username and password.
//
url.username = url.password = '';
if (url.auth) {
index = url.auth.indexOf(':');
if (~index) {
url.username = url.auth.slice(0, index);
url.username = encodeURIComponent(decodeURIComponent(url.username));
url.password = url.auth.slice(index + 1);
url.password = encodeURIComponent(decodeURIComponent(url.password))
} else {
url.username = encodeURIComponent(decodeURIComponent(url.auth));
}
url.auth = url.password ? url.username +':'+ url.password : url.username;
}
url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host
? url.protocol +'//'+ url.host
: 'null';
//
// The href is just the compiled result.
//
url.href = url.toString();
}
/**
* This is convenience method for changing properties in the URL instance to
* insure that they all propagate correctly.
*
* @param {String} part Property we need to adjust.
* @param {Mixed} value The newly assigned value.
* @param {Boolean|Function} fn When setting the query, it will be the function
* used to parse the query.
* When setting the protocol, double slash will be
* removed from the final url if it is true.
* @returns {URL} URL instance for chaining.
* @public
*/
function set(part, value, fn) {
var url = this;
switch (part) {
case 'query':
if ('string' === typeof value && value.length) {
value = (fn || qs.parse)(value);
}
url[part] = value;
break;
case 'port':
url[part] = value;
if (!required(value, url.protocol)) {
url.host = url.hostname;
url[part] = '';
} else if (value) {
url.host = url.hostname +':'+ value;
}
break;
case 'hostname':
url[part] = value;
if (url.port) value += ':'+ url.port;
url.host = value;
break;
case 'host':
url[part] = value;
if (port.test(value)) {
value = value.split(':');
url.port = value.pop();
url.hostname = value.join(':');
} else {
url.hostname = value;
url.port = '';
}
break;
case 'protocol':
url.protocol = value.toLowerCase();
url.slashes = !fn;
break;
case 'pathname':
case 'hash':
if (value) {
var char = part === 'pathname' ? '/' : '#';
url[part] = value.charAt(0) !== char ? char + value : value;
} else {
url[part] = value;
}
break;
case 'username':
case 'password':
url[part] = encodeURIComponent(value);
break;
case 'auth':
var index = value.indexOf(':');
if (~index) {
url.username = value.slice(0, index);
url.username = encodeURIComponent(decodeURIComponent(url.username));
url.password = value.slice(index + 1);
url.password = encodeURIComponent(decodeURIComponent(url.password));
} else {
url.username = encodeURIComponent(decodeURIComponent(value));
}
}
for (var i = 0; i < rules.length; i++) {
var ins = rules[i];
if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();
}
url.auth = url.password ? url.username +':'+ url.password : url.username;
url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host
? url.protocol +'//'+ url.host
: 'null';
url.href = url.toString();
return url;
}
/**
* Transform the properties back in to a valid and full URL string.
*
* @param {Function} stringify Optional query stringify function.
* @returns {String} Compiled version of the URL.
* @public
*/
function toString(stringify) {
if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;
var query
, url = this
, host = url.host
, protocol = url.protocol;
if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';
var result =
protocol +
((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');
if (url.username) {
result += url.username;
if (url.password) result += ':'+ url.password;
result += '@';
} else if (url.password) {
result += ':'+ url.password;
result += '@';
} else if (
url.protocol !== 'file:' &&
isSpecial(url.protocol) &&
!host &&
url.pathname !== '/'
) {
//
// Add back the empty userinfo, otherwise the original invalid URL
// might be transformed into a valid one with `url.pathname` as host.
//
result += '@';
}
//
// Trailing colon is removed from `url.host` when it is parsed. If it still
// ends with a colon, then add back the trailing colon that was removed. This
// prevents an invalid URL from being transformed into a valid one.
//
if (host[host.length - 1] === ':' || (port.test(url.hostname) && !url.port)) {
host += ':';
}
result += host + url.pathname;
query = 'object' === typeof url.query ? stringify(url.query) : url.query;
if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;
if (url.hash) result += url.hash;
return result;
}
Url.prototype = { set: set, toString: toString };
//
// Expose the URL parser and some additional properties that might be useful for
// others or testing.
//
Url.extractProtocol = extractProtocol;
Url.location = lolcation;
Url.trimLeft = trimLeft;
Url.qs = qs;
module.exports = Url;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5)))
/***/ }),
/* 393 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Check if we're required to add a port number.
*
* @see https://url.spec.whatwg.org/#default-port
* @param {Number|String} port Port number we need to check
* @param {String} protocol Protocol we need to check against.
* @returns {Boolean} Is it a default port for the given protocol
* @api private
*/
module.exports = function required(port, protocol) {
protocol = protocol.split(':')[0];
port = +port;
if (!port) return false;
switch (protocol) {
case 'http':
case 'ws':
return port !== 80;
case 'https':
case 'wss':
return port !== 443;
case 'ftp':
return port !== 21;
case 'gopher':
return port !== 70;
case 'file':
return false;
}
return port !== 0;
};
/***/ }),
/* 394 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var has = Object.prototype.hasOwnProperty
, undef;
/**
* Decode a URI encoded string.
*
* @param {String} input The URI encoded string.
* @returns {String|Null} The decoded string.
* @api private
*/
function decode(input) {
try {
return decodeURIComponent(input.replace(/\+/g, ' '));
} catch (e) {
return null;
}
}
/**
* Attempts to encode a given input.
*
* @param {String} input The string that needs to be encoded.
* @returns {String|Null} The encoded string.
* @api private
*/
function encode(input) {
try {
return encodeURIComponent(input);
} catch (e) {
return null;
}
}
/**
* Simple query string parser.
*
* @param {String} query The query string that needs to be parsed.
* @returns {Object}
* @api public
*/
function querystring(query) {
var parser = /([^=?#&]+)=?([^&]*)/g
, result = {}
, part;
while (part = parser.exec(query)) {
var key = decode(part[1])
, value = decode(part[2]);
//
// Prevent overriding of existing properties. This ensures that build-in
// methods like `toString` or __proto__ are not overriden by malicious
// querystrings.
//
// In the case if failed decoding, we want to omit the key/value pairs
// from the result.
//
if (key === null || value === null || key in result) continue;
result[key] = value;
}
return result;
}
/**
* Transform a query string to an object.
*
* @param {Object} obj Object that should be transformed.
* @param {String} prefix Optional prefix.
* @returns {String}
* @api public
*/
function querystringify(obj, prefix) {
prefix = prefix || '';
var pairs = []
, value
, key;
//
// Optionally prefix with a '?' if needed
//
if ('string' !== typeof prefix) prefix = '?';
for (key in obj) {
if (has.call(obj, key)) {
value = obj[key];
//
// Edge cases where we actually want to encode the value to an empty
// string instead of the stringified value.
//
if (!value && (value === null || value === undef || isNaN(value))) {
value = '';
}
key = encode(key);
value = encode(value);
//
// If we failed to encode the strings, we should bail out as we don't
// want to add invalid strings to the query.
//
if (key === null || value === null) continue;
pairs.push(key +'='+ value);
}
}
return pairs.length ? prefix + pairs.join('&') : '';
}
//
// Expose the module.
//
exports.stringify = querystringify;
exports.parse = querystring;
/***/ }),
/* 395 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.1 by @mathias */
;(function(root) {
/** Detect free variables */
var freeExports = true && exports &&
!exports.nodeType && exports;
var freeModule = true && module &&
!module.nodeType && module;
var freeGlobal = typeof global == 'object' && global;
if (
freeGlobal.global === freeGlobal ||
freeGlobal.window === freeGlobal ||
freeGlobal.self === freeGlobal
) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
var result = [];
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
var parts = string.split('@');
var result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
string = string.replace(regexSeparators, '\x2E');
var labels = string.split('.');
var encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
function toASCII(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.4.1',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
true
) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
return punycode;
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {}
}(this));
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(41)(module), __webpack_require__(5)))
/***/ }),
/* 396 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = {
isString: function(arg) {
return typeof(arg) === 'string';
},
isObject: function(arg) {
return typeof(arg) === 'object' && arg !== null;
},
isNull: function(arg) {
return arg === null;
},
isNullOrUndefined: function(arg) {
return arg == null;
}
};
/***/ }),
/* 397 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.decode = exports.parse = __webpack_require__(398);
exports.encode = exports.stringify = __webpack_require__(399);
/***/ }),
/* 398 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 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.
// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = function(qs, sep, eq, options) {
sep = sep || '&';
eq = eq || '=';
var obj = {};
if (typeof qs !== 'string' || qs.length === 0) {
return obj;
}
var regexp = /\+/g;
qs = qs.split(sep);
var maxKeys = 1000;
if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys;
}
var len = qs.length;
// maxKeys <= 0 means that we should not limit keys count
if (maxKeys > 0 && len > maxKeys) {
len = maxKeys;
}
for (var i = 0; i < len; ++i) {
var x = qs[i].replace(regexp, '%20'),
idx = x.indexOf(eq),
kstr, vstr, k, v;
if (idx >= 0) {
kstr = x.substr(0, idx);
vstr = x.substr(idx + 1);
} else {
kstr = x;
vstr = '';
}
k = decodeURIComponent(kstr);
v = decodeURIComponent(vstr);
if (!hasOwnProperty(obj, k)) {
obj[k] = v;
} else if (isArray(obj[k])) {
obj[k].push(v);
} else {
obj[k] = [obj[k], v];
}
}
return obj;
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
/***/ }),
/* 399 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 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 stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
/***/ }),
/* 400 */
/***/ (function(module, exports, __webpack_require__) {
var http = __webpack_require__(165)
var url = __webpack_require__(92)
var https = module.exports
for (var key in http) {
if (http.hasOwnProperty(key)) https[key] = http[key]
}
https.request = function (params, cb) {
params = validateParams(params)
return http.request.call(this, params, cb)
}
https.get = function (params, cb) {
params = validateParams(params)
return http.get.call(this, params, cb)
}
function validateParams (params) {
if (typeof params === 'string') {
params = url.parse(params)
}
if (!params.protocol) {
params.protocol = 'https:'
}
if (params.protocol !== 'https:') {
throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"')
}
return params
}
/***/ }),
/* 401 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(Buffer, global, process) {var capability = __webpack_require__(166)
var inherits = __webpack_require__(11)
var response = __webpack_require__(167)
var stream = __webpack_require__(168)
var toArrayBuffer = __webpack_require__(409)
var IncomingMessage = response.IncomingMessage
var rStates = response.readyStates
function decideMode (preferBinary, useFetch) {
if (capability.fetch && useFetch) {
return 'fetch'
} else if (capability.mozchunkedarraybuffer) {
return 'moz-chunked-arraybuffer'
} else if (capability.msstream) {
return 'ms-stream'
} else if (capability.arraybuffer && preferBinary) {
return 'arraybuffer'
} else if (capability.vbArray && preferBinary) {
return 'text:vbarray'
} else {
return 'text'
}
}
var ClientRequest = module.exports = function (opts) {
var self = this
stream.Writable.call(self)
self._opts = opts
self._body = []
self._headers = {}
if (opts.auth)
self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64'))
Object.keys(opts.headers).forEach(function (name) {
self.setHeader(name, opts.headers[name])
})
var preferBinary
var useFetch = true
if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) {
// If the use of XHR should be preferred. Not typically needed.
useFetch = false
preferBinary = true
} else if (opts.mode === 'prefer-streaming') {
// If streaming is a high priority but binary compatibility and
// the accuracy of the 'content-type' header aren't
preferBinary = false
} else if (opts.mode === 'allow-wrong-content-type') {
// If streaming is more important than preserving the 'content-type' header
preferBinary = !capability.overrideMimeType
} else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
// Use binary if text streaming may corrupt data or the content-type header, or for speed
preferBinary = true
} else {
throw new Error('Invalid value for opts.mode')
}
self._mode = decideMode(preferBinary, useFetch)
self._fetchTimer = null
self.on('finish', function () {
self._onFinish()
})
}
inherits(ClientRequest, stream.Writable)
ClientRequest.prototype.setHeader = function (name, value) {
var self = this
var lowerName = name.toLowerCase()
// This check is not necessary, but it prevents warnings from browsers about setting unsafe
// headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
// http-browserify did it, so I will too.
if (unsafeHeaders.indexOf(lowerName) !== -1)
return
self._headers[lowerName] = {
name: name,
value: value
}
}
ClientRequest.prototype.getHeader = function (name) {
var header = this._headers[name.toLowerCase()]
if (header)
return header.value
return null
}
ClientRequest.prototype.removeHeader = function (name) {
var self = this
delete self._headers[name.toLowerCase()]
}
ClientRequest.prototype._onFinish = function () {
var self = this
if (self._destroyed)
return
var opts = self._opts
var headersObj = self._headers
var body = null
if (opts.method !== 'GET' && opts.method !== 'HEAD') {
if (capability.arraybuffer) {
body = toArrayBuffer(Buffer.concat(self._body))
} else if (capability.blobConstructor) {
body = new global.Blob(self._body.map(function (buffer) {
return toArrayBuffer(buffer)
}), {
type: (headersObj['content-type'] || {}).value || ''
})
} else {
// get utf8 string
body = Buffer.concat(self._body).toString()
}
}
// create flattened list of headers
var headersList = []
Object.keys(headersObj).forEach(function (keyName) {
var name = headersObj[keyName].name
var value = headersObj[keyName].value
if (Array.isArray(value)) {
value.forEach(function (v) {
headersList.push([name, v])
})
} else {
headersList.push([name, value])
}
})
if (self._mode === 'fetch') {
var signal = null
var fetchTimer = null
if (capability.abortController) {
var controller = new AbortController()
signal = controller.signal
self._fetchAbortController = controller
if ('requestTimeout' in opts && opts.requestTimeout !== 0) {
self._fetchTimer = global.setTimeout(function () {
self.emit('requestTimeout')
if (self._fetchAbortController)
self._fetchAbortController.abort()
}, opts.requestTimeout)
}
}
global.fetch(self._opts.url, {
method: self._opts.method,
headers: headersList,
body: body || undefined,
mode: 'cors',
credentials: opts.withCredentials ? 'include' : 'same-origin',
signal: signal
}).then(function (response) {
self._fetchResponse = response
self._connect()
}, function (reason) {
global.clearTimeout(self._fetchTimer)
if (!self._destroyed)
self.emit('error', reason)
})
} else {
var xhr = self._xhr = new global.XMLHttpRequest()
try {
xhr.open(self._opts.method, self._opts.url, true)
} catch (err) {
process.nextTick(function () {
self.emit('error', err)
})
return
}
// Can't set responseType on really old browsers
if ('responseType' in xhr)
xhr.responseType = self._mode.split(':')[0]
if ('withCredentials' in xhr)
xhr.withCredentials = !!opts.withCredentials
if (self._mode === 'text' && 'overrideMimeType' in xhr)
xhr.overrideMimeType('text/plain; charset=x-user-defined')
if ('requestTimeout' in opts) {
xhr.timeout = opts.requestTimeout
xhr.ontimeout = function () {
self.emit('requestTimeout')
}
}
headersList.forEach(function (header) {
xhr.setRequestHeader(header[0], header[1])
})
self._response = null
xhr.onreadystatechange = function () {
switch (xhr.readyState) {
case rStates.LOADING:
case rStates.DONE:
self._onXHRProgress()
break
}
}
// Necessary for streaming in Firefox, since xhr.response is ONLY defined
// in onprogress, not in onreadystatechange with xhr.readyState = 3
if (self._mode === 'moz-chunked-arraybuffer') {
xhr.onprogress = function () {
self._onXHRProgress()
}
}
xhr.onerror = function () {
if (self._destroyed)
return
self.emit('error', new Error('XHR error'))
}
try {
xhr.send(body)
} catch (err) {
process.nextTick(function () {
self.emit('error', err)
})
return
}
}
}
/**
* Checks if xhr.status is readable and non-zero, indicating no error.
* Even though the spec says it should be available in readyState 3,
* accessing it throws an exception in IE8
*/
function statusValid (xhr) {
try {
var status = xhr.status
return (status !== null && status !== 0)
} catch (e) {
return false
}
}
ClientRequest.prototype._onXHRProgress = function () {
var self = this
if (!statusValid(self._xhr) || self._destroyed)
return
if (!self._response)
self._connect()
self._response._onXHRProgress()
}
ClientRequest.prototype._connect = function () {
var self = this
if (self._destroyed)
return
self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._fetchTimer)
self._response.on('error', function(err) {
self.emit('error', err)
})
self.emit('response', self._response)
}
ClientRequest.prototype._write = function (chunk, encoding, cb) {
var self = this
self._body.push(chunk)
cb()
}
ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
var self = this
self._destroyed = true
global.clearTimeout(self._fetchTimer)
if (self._response)
self._response._destroyed = true
if (self._xhr)
self._xhr.abort()
else if (self._fetchAbortController)
self._fetchAbortController.abort()
}
ClientRequest.prototype.end = function (data, encoding, cb) {
var self = this
if (typeof data === 'function') {
cb = data
data = undefined
}
stream.Writable.prototype.end.call(self, data, encoding, cb)
}
ClientRequest.prototype.flushHeaders = function () {}
ClientRequest.prototype.setTimeout = function () {}
ClientRequest.prototype.setNoDelay = function () {}
ClientRequest.prototype.setSocketKeepAlive = function () {}
// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
var unsafeHeaders = [
'accept-charset',
'accept-encoding',
'access-control-request-headers',
'access-control-request-method',
'connection',
'content-length',
'cookie',
'cookie2',
'date',
'dnt',
'expect',
'host',
'keep-alive',
'origin',
'referer',
'te',
'trailer',
'transfer-encoding',
'upgrade',
'via'
]
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer, __webpack_require__(5), __webpack_require__(13)))
/***/ }),
/* 402 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 403 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Buffer = __webpack_require__(94).Buffer;
var util = __webpack_require__(404);
function copyBuffer(src, target, offset) {
src.copy(target, offset);
}
module.exports = function () {
function BufferList() {
_classCallCheck(this, BufferList);
this.head = null;
this.tail = null;
this.length = 0;
}
BufferList.prototype.push = function push(v) {
var entry = { data: v, next: null };
if (this.length > 0) this.tail.next = entry;else this.head = entry;
this.tail = entry;
++this.length;
};
BufferList.prototype.unshift = function unshift(v) {
var entry = { data: v, next: this.head };
if (this.length === 0) this.tail = entry;
this.head = entry;
++this.length;
};
BufferList.prototype.shift = function shift() {
if (this.length === 0) return;
var ret = this.head.data;
if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
--this.length;
return ret;
};
BufferList.prototype.clear = function clear() {
this.head = this.tail = null;
this.length = 0;
};
BufferList.prototype.join = function join(s) {
if (this.length === 0) return '';
var p = this.head;
var ret = '' + p.data;
while (p = p.next) {
ret += s + p.data;
}return ret;
};
BufferList.prototype.concat = function concat(n) {
if (this.length === 0) return Buffer.alloc(0);
if (this.length === 1) return this.head.data;
var ret = Buffer.allocUnsafe(n >>> 0);
var p = this.head;
var i = 0;
while (p) {
copyBuffer(p.data, ret, i);
i += p.data.length;
p = p.next;
}
return ret;
};
return BufferList;
}();
if (util && util.inspect && util.inspect.custom) {
module.exports.prototype[util.inspect.custom] = function () {
var obj = util.inspect({ length: this.length });
return this.constructor.name + ' ' + obj;
};
}
/***/ }),
/* 404 */
/***/ (function(module, exports) {
/* (ignored) */
/***/ }),
/* 405 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
(typeof self !== "undefined" && self) ||
window;
var apply = Function.prototype.apply;
// DOM APIs, for completeness
exports.setTimeout = function() {
return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
};
exports.setInterval = function() {
return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) {
if (timeout) {
timeout.close();
}
};
function Timeout(id, clearFn) {
this._id = id;
this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
this._clearFn.call(scope, this._id);
};
// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = msecs;
};
exports.unenroll = function(item) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = -1;
};
exports._unrefActive = exports.active = function(item) {
clearTimeout(item._idleTimeoutId);
var msecs = item._idleTimeout;
if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout)
item._onTimeout();
}, msecs);
}
};
// setimmediate attaches itself to the global object
__webpack_require__(406);
// On some exotic environments, it's not clear which object `setimmediate` was
// able to install onto. Search each possibility in the same order as the
// `setimmediate` library.
exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
(typeof global !== "undefined" && global.setImmediate) ||
(this && this.setImmediate);
exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
(typeof global !== "undefined" && global.clearImmediate) ||
(this && this.clearImmediate);
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5)))
/***/ }),
/* 406 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
"use strict";
if (global.setImmediate) {
return;
}
var nextHandle = 1; // Spec says greater than zero
var tasksByHandle = {};
var currentlyRunningATask = false;
var doc = global.document;
var registerImmediate;
function setImmediate(callback) {
// Callback can either be a function or a string
if (typeof callback !== "function") {
callback = new Function("" + callback);
}
// Copy function arguments
var args = new Array(arguments.length - 1);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i + 1];
}
// Store and register the task
var task = { callback: callback, args: args };
tasksByHandle[nextHandle] = task;
registerImmediate(nextHandle);
return nextHandle++;
}
function clearImmediate(handle) {
delete tasksByHandle[handle];
}
function run(task) {
var callback = task.callback;
var args = task.args;
switch (args.length) {
case 0:
callback();
break;
case 1:
callback(args[0]);
break;
case 2:
callback(args[0], args[1]);
break;
case 3:
callback(args[0], args[1], args[2]);
break;
default:
callback.apply(undefined, args);
break;
}
}
function runIfPresent(handle) {
// From the spec: "Wait until any invocations of this algorithm started before this one have completed."
// So if we're currently running a task, we'll need to delay this invocation.
if (currentlyRunningATask) {
// Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
// "too much recursion" error.
setTimeout(runIfPresent, 0, handle);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunningATask = true;
try {
run(task);
} finally {
clearImmediate(handle);
currentlyRunningATask = false;
}
}
}
}
function installNextTickImplementation() {
registerImmediate = function(handle) {
process.nextTick(function () { runIfPresent(handle); });
};
}
function canUsePostMessage() {
// The test against `importScripts` prevents this implementation from being installed inside a web worker,
// where `global.postMessage` means something completely different and can't be used for this purpose.
if (global.postMessage && !global.importScripts) {
var postMessageIsAsynchronous = true;
var oldOnMessage = global.onmessage;
global.onmessage = function() {
postMessageIsAsynchronous = false;
};
global.postMessage("", "*");
global.onmessage = oldOnMessage;
return postMessageIsAsynchronous;
}
}
function installPostMessageImplementation() {
// Installs an event handler on `global` for the `message` event: see
// * https://developer.mozilla.org/en/DOM/window.postMessage
// * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
var messagePrefix = "setImmediate$" + Math.random() + "$";
var onGlobalMessage = function(event) {
if (event.source === global &&
typeof event.data === "string" &&
event.data.indexOf(messagePrefix) === 0) {
runIfPresent(+event.data.slice(messagePrefix.length));
}
};
if (global.addEventListener) {
global.addEventListener("message", onGlobalMessage, false);
} else {
global.attachEvent("onmessage", onGlobalMessage);
}
registerImmediate = function(handle) {
global.postMessage(messagePrefix + handle, "*");
};
}
function installMessageChannelImplementation() {
var channel = new MessageChannel();
channel.port1.onmessage = function(event) {
var handle = event.data;
runIfPresent(handle);
};
registerImmediate = function(handle) {
channel.port2.postMessage(handle);
};
}
function installReadyStateChangeImplementation() {
var html = doc.documentElement;
registerImmediate = function(handle) {
// Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
// into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
var script = doc.createElement("script");
script.onreadystatechange = function () {
runIfPresent(handle);
script.onreadystatechange = null;
html.removeChild(script);
script = null;
};
html.appendChild(script);
};
}
function installSetTimeoutImplementation() {
registerImmediate = function(handle) {
setTimeout(runIfPresent, 0, handle);
};
}
// If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
// Don't get fooled by e.g. browserify environments.
if ({}.toString.call(global.process) === "[object process]") {
// For Node.js before 0.9
installNextTickImplementation();
} else if (canUsePostMessage()) {
// For non-IE10 modern browsers
installPostMessageImplementation();
} else if (global.MessageChannel) {
// For web workers, where supported
installMessageChannelImplementation();
} else if (doc && "onreadystatechange" in doc.createElement("script")) {
// For IE 6–8
installReadyStateChangeImplementation();
} else {
// For older browsers
installSetTimeoutImplementation();
}
attachTo.setImmediate = setImmediate;
attachTo.clearImmediate = clearImmediate;
}(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5), __webpack_require__(13)))
/***/ }),
/* 407 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {
/**
* Module exports.
*/
module.exports = deprecate;
/**
* Mark that a method should not be used.
* Returns a modified function which warns once by default.
*
* If `localStorage.noDeprecation = true` is set, then it is a no-op.
*
* If `localStorage.throwDeprecation = true` is set, then deprecated functions
* will throw an Error when invoked.
*
* If `localStorage.traceDeprecation = true` is set, then deprecated functions
* will invoke `console.trace()` instead of `console.error()`.
*
* @param {Function} fn - the function to deprecate
* @param {String} msg - the string to print to the console when `fn` is invoked
* @returns {Function} a new "deprecated" version of `fn`
* @api public
*/
function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
}
/**
* Checks `localStorage` for boolean values for the given `name`.
*
* @param {String} name
* @returns {Boolean}
* @api private
*/
function config (name) {
// accessing global.localStorage can trigger a DOMException in sandboxed iframes
try {
if (!global.localStorage) return false;
} catch (_) {
return false;
}
var val = global.localStorage[name];
if (null == val) return false;
return String(val).toLowerCase() === 'true';
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5)))
/***/ }),
/* 408 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// 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.
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
module.exports = PassThrough;
var Transform = __webpack_require__(174);
/*<replacement>*/
var util = Object.create(__webpack_require__(45));
util.inherits = __webpack_require__(11);
/*</replacement>*/
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough)) return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function (chunk, encoding, cb) {
cb(null, chunk);
};
/***/ }),
/* 409 */
/***/ (function(module, exports, __webpack_require__) {
var Buffer = __webpack_require__(1).Buffer
module.exports = function (buf) {
// If the buffer is backed by a Uint8Array, a faster version will work
if (buf instanceof Uint8Array) {
// If the buffer isn't a subarray, return the underlying ArrayBuffer
if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
return buf.buffer
} else if (typeof buf.buffer.slice === 'function') {
// Otherwise we need to get a proper copy
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
}
}
if (Buffer.isBuffer(buf)) {
// This is the slow version that will work with any Buffer
// implementation (even in old browsers)
var arrayCopy = new Uint8Array(buf.length)
var len = buf.length
for (var i = 0; i < len; i++) {
arrayCopy[i] = buf[i]
}
return arrayCopy.buffer
} else {
throw new Error('Argument must be a Buffer')
}
}
/***/ }),
/* 410 */
/***/ (function(module, exports) {
module.exports = extend
var hasOwnProperty = Object.prototype.hasOwnProperty;
function extend() {
var target = {}
for (var i = 0; i < arguments.length; i++) {
var source = arguments[i]
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
target[key] = source[key]
}
}
}
return target
}
/***/ }),
/* 411 */
/***/ (function(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"
}
/***/ }),
/* 412 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {// 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 getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
function getOwnPropertyDescriptors(obj) {
var keys = Object.keys(obj);
var descriptors = {};
for (var i = 0; i < keys.length; i++) {
descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
}
return descriptors;
};
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
if (typeof process !== 'undefined' && process.noDeprecation === true) {
return fn;
}
// Allow for deprecating things in the process of starting up.
if (typeof process === 'undefined') {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
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 isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(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 = __webpack_require__(413);
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = __webpack_require__(414);
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;
exports.promisify = function promisify(original) {
if (typeof original !== 'function')
throw new TypeError('The "original" argument must be of type Function');
if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
var fn = original[kCustomPromisifiedSymbol];
if (typeof fn !== 'function') {
throw new TypeError('The "util.promisify.custom" argument must be of type Function');
}
Object.defineProperty(fn, kCustomPromisifiedSymbol, {
value: fn, enumerable: false, writable: false, configurable: true
});
return fn;
}
function fn() {
var promiseResolve, promiseReject;
var promise = new Promise(function (resolve, reject) {
promiseResolve = resolve;
promiseReject = reject;
});
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
args.push(function (err, value) {
if (err) {
promiseReject(err);
} else {
promiseResolve(value);
}
});
try {
original.apply(this, args);
} catch (err) {
promiseReject(err);
}
return promise;
}
Object.setPrototypeOf(fn, Object.getPrototypeOf(original));
if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
value: fn, enumerable: false, writable: false, configurable: true
});
return Object.defineProperties(
fn,
getOwnPropertyDescriptors(original)
);
}
exports.promisify.custom = kCustomPromisifiedSymbol
function callbackifyOnRejected(reason, cb) {
// `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
// Because `null` is a special error value in callbacks which means "no error
// occurred", we error-wrap so the callback consumer can distinguish between
// "the promise rejected with null" or "the promise fulfilled with undefined".
if (!reason) {
var newReason = new Error('Promise was rejected with a falsy value');
newReason.reason = reason;
reason = newReason;
}
return cb(reason);
}
function callbackify(original) {
if (typeof original !== 'function') {
throw new TypeError('The "original" argument must be of type Function');
}
// We DO NOT return the promise as it gives the user a false sense that
// the promise is actually somehow related to the callback's execution
// and that the callback throwing will reject the promise.
function callbackified() {
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
var maybeCb = args.pop();
if (typeof maybeCb !== 'function') {
throw new TypeError('The last argument must be of type Function');
}
var self = this;
var cb = function() {
return maybeCb.apply(self, arguments);
};
// In true node style we process the callback on `nextTick` with all the
// implications (stack, `uncaughtException`, `async_hooks`)
original.apply(this, args)
.then(function(ret) { process.nextTick(cb, null, ret) },
function(rej) { process.nextTick(callbackifyOnRejected, rej, cb) });
}
Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
Object.defineProperties(callbackified,
getOwnPropertyDescriptors(original));
return callbackified;
}
exports.callbackify = callbackify;
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(13)))
/***/ }),
/* 413 */
/***/ (function(module, exports) {
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
/***/ }),
/* 414 */
/***/ (function(module, exports) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
/***/ }),
/* 415 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AccountCallBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var call_builder_1 = __webpack_require__(6);
var AccountCallBuilder = (function (_super) {
tslib_1.__extends(AccountCallBuilder, _super);
function AccountCallBuilder(serverUrl) {
var _this = _super.call(this, serverUrl) || this;
_this.url.segment("accounts");
return _this;
}
AccountCallBuilder.prototype.accountId = function (id) {
var builder = new call_builder_1.CallBuilder(this.url.clone());
builder.filter.push([id]);
return builder;
};
AccountCallBuilder.prototype.forSigner = function (id) {
this.url.setQuery("signer", id);
return this;
};
AccountCallBuilder.prototype.forAsset = function (asset) {
this.url.setQuery("asset", "" + asset);
return this;
};
AccountCallBuilder.prototype.sponsor = function (id) {
this.url.setQuery("sponsor", id);
return this;
};
AccountCallBuilder.prototype.forLiquidityPool = function (id) {
this.url.setQuery("liquidity_pool", id);
return this;
};
return AccountCallBuilder;
}(call_builder_1.CallBuilder));
exports.AccountCallBuilder = AccountCallBuilder;
/***/ }),
/* 416 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AssetsCallBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var call_builder_1 = __webpack_require__(6);
var AssetsCallBuilder = (function (_super) {
tslib_1.__extends(AssetsCallBuilder, _super);
function AssetsCallBuilder(serverUrl) {
var _this = _super.call(this, serverUrl) || this;
_this.url.segment("assets");
return _this;
}
AssetsCallBuilder.prototype.forCode = function (value) {
this.url.setQuery("asset_code", value);
return this;
};
AssetsCallBuilder.prototype.forIssuer = function (value) {
this.url.setQuery("asset_issuer", value);
return this;
};
return AssetsCallBuilder;
}(call_builder_1.CallBuilder));
exports.AssetsCallBuilder = AssetsCallBuilder;
/***/ }),
/* 417 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClaimableBalanceCallBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var call_builder_1 = __webpack_require__(6);
var ClaimableBalanceCallBuilder = (function (_super) {
tslib_1.__extends(ClaimableBalanceCallBuilder, _super);
function ClaimableBalanceCallBuilder(serverUrl) {
var _this = _super.call(this, serverUrl) || this;
_this.url.segment("claimable_balances");
return _this;
}
ClaimableBalanceCallBuilder.prototype.claimableBalance = function (claimableBalanceId) {
var builder = new call_builder_1.CallBuilder(this.url.clone());
builder.filter.push([claimableBalanceId]);
return builder;
};
ClaimableBalanceCallBuilder.prototype.sponsor = function (sponsor) {
this.url.setQuery("sponsor", sponsor);
return this;
};
ClaimableBalanceCallBuilder.prototype.claimant = function (claimant) {
this.url.setQuery("claimant", claimant);
return this;
};
ClaimableBalanceCallBuilder.prototype.asset = function (asset) {
this.url.setQuery("asset", asset.toString());
return this;
};
return ClaimableBalanceCallBuilder;
}(call_builder_1.CallBuilder));
exports.ClaimableBalanceCallBuilder = ClaimableBalanceCallBuilder;
/***/ }),
/* 418 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.EffectCallBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var call_builder_1 = __webpack_require__(6);
var EffectCallBuilder = (function (_super) {
tslib_1.__extends(EffectCallBuilder, _super);
function EffectCallBuilder(serverUrl) {
var _this = _super.call(this, serverUrl, "effects") || this;
_this.url.segment("effects");
return _this;
}
EffectCallBuilder.prototype.forAccount = function (accountId) {
return this.forEndpoint("accounts", accountId);
};
EffectCallBuilder.prototype.forLedger = function (sequence) {
return this.forEndpoint("ledgers", sequence.toString());
};
EffectCallBuilder.prototype.forTransaction = function (transactionId) {
return this.forEndpoint("transactions", transactionId);
};
EffectCallBuilder.prototype.forOperation = function (operationId) {
return this.forEndpoint("operations", operationId);
};
EffectCallBuilder.prototype.forLiquidityPool = function (poolId) {
return this.forEndpoint("liquidity_pools", poolId);
};
return EffectCallBuilder;
}(call_builder_1.CallBuilder));
exports.EffectCallBuilder = EffectCallBuilder;
/***/ }),
/* 419 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FriendbotBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var call_builder_1 = __webpack_require__(6);
var FriendbotBuilder = (function (_super) {
tslib_1.__extends(FriendbotBuilder, _super);
function FriendbotBuilder(serverUrl, address) {
var _this = _super.call(this, serverUrl) || this;
_this.url.segment("friendbot");
_this.url.setQuery("addr", address);
return _this;
}
return FriendbotBuilder;
}(call_builder_1.CallBuilder));
exports.FriendbotBuilder = FriendbotBuilder;
/***/ }),
/* 420 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LedgerCallBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var call_builder_1 = __webpack_require__(6);
var LedgerCallBuilder = (function (_super) {
tslib_1.__extends(LedgerCallBuilder, _super);
function LedgerCallBuilder(serverUrl) {
var _this = _super.call(this, serverUrl) || this;
_this.url.segment("ledgers");
return _this;
}
LedgerCallBuilder.prototype.ledger = function (sequence) {
this.filter.push(["ledgers", sequence.toString()]);
return this;
};
return LedgerCallBuilder;
}(call_builder_1.CallBuilder));
exports.LedgerCallBuilder = LedgerCallBuilder;
/***/ }),
/* 421 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LiquidityPoolCallBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var call_builder_1 = __webpack_require__(6);
var LiquidityPoolCallBuilder = (function (_super) {
tslib_1.__extends(LiquidityPoolCallBuilder, _super);
function LiquidityPoolCallBuilder(serverUrl) {
var _this = _super.call(this, serverUrl) || this;
_this.url.segment("liquidity_pools");
return _this;
}
LiquidityPoolCallBuilder.prototype.forAssets = function () {
var assets = [];
for (var _i = 0; _i < arguments.length; _i++) {
assets[_i] = arguments[_i];
}
var assetList = assets
.map(function (asset) { return asset.toString(); })
.join(",");
this.url.setQuery("reserves", assetList);
return this;
};
LiquidityPoolCallBuilder.prototype.forAccount = function (id) {
this.url.setQuery("account", id);
return this;
};
LiquidityPoolCallBuilder.prototype.liquidityPoolId = function (id) {
if (!id.match(/[a-fA-F0-9]{64}/)) {
throw new TypeError(id + " does not look like a liquidity pool ID");
}
var builder = new call_builder_1.CallBuilder(this.url.clone());
builder.filter.push([id.toLowerCase()]);
return builder;
};
return LiquidityPoolCallBuilder;
}(call_builder_1.CallBuilder));
exports.LiquidityPoolCallBuilder = LiquidityPoolCallBuilder;
/***/ }),
/* 422 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OfferCallBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var call_builder_1 = __webpack_require__(6);
var OfferCallBuilder = (function (_super) {
tslib_1.__extends(OfferCallBuilder, _super);
function OfferCallBuilder(serverUrl) {
var _this = _super.call(this, serverUrl, "offers") || this;
_this.url.segment("offers");
return _this;
}
OfferCallBuilder.prototype.offer = function (offerId) {
var builder = new call_builder_1.CallBuilder(this.url.clone());
builder.filter.push([offerId]);
return builder;
};
OfferCallBuilder.prototype.forAccount = function (id) {
return this.forEndpoint("accounts", id);
};
OfferCallBuilder.prototype.buying = function (asset) {
if (!asset.isNative()) {
this.url.setQuery("buying_asset_type", asset.getAssetType());
this.url.setQuery("buying_asset_code", asset.getCode());
this.url.setQuery("buying_asset_issuer", asset.getIssuer());
}
else {
this.url.setQuery("buying_asset_type", "native");
}
return this;
};
OfferCallBuilder.prototype.selling = function (asset) {
if (!asset.isNative()) {
this.url.setQuery("selling_asset_type", asset.getAssetType());
this.url.setQuery("selling_asset_code", asset.getCode());
this.url.setQuery("selling_asset_issuer", asset.getIssuer());
}
else {
this.url.setQuery("selling_asset_type", "native");
}
return this;
};
OfferCallBuilder.prototype.sponsor = function (id) {
this.url.setQuery("sponsor", id);
return this;
};
OfferCallBuilder.prototype.seller = function (seller) {
this.url.setQuery("seller", seller);
return this;
};
return OfferCallBuilder;
}(call_builder_1.CallBuilder));
exports.OfferCallBuilder = OfferCallBuilder;
/***/ }),
/* 423 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OperationCallBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var call_builder_1 = __webpack_require__(6);
var OperationCallBuilder = (function (_super) {
tslib_1.__extends(OperationCallBuilder, _super);
function OperationCallBuilder(serverUrl) {
var _this = _super.call(this, serverUrl, "operations") || this;
_this.url.segment("operations");
return _this;
}
OperationCallBuilder.prototype.operation = function (operationId) {
var builder = new call_builder_1.CallBuilder(this.url.clone());
builder.filter.push([operationId]);
return builder;
};
OperationCallBuilder.prototype.forAccount = function (accountId) {
return this.forEndpoint("accounts", accountId);
};
OperationCallBuilder.prototype.forClaimableBalance = function (claimableBalanceId) {
return this.forEndpoint("claimable_balances", claimableBalanceId);
};
OperationCallBuilder.prototype.forLedger = function (sequence) {
return this.forEndpoint("ledgers", sequence.toString());
};
OperationCallBuilder.prototype.forTransaction = function (transactionId) {
return this.forEndpoint("transactions", transactionId);
};
OperationCallBuilder.prototype.forLiquidityPool = function (poolId) {
return this.forEndpoint("liquidity_pools", poolId);
};
OperationCallBuilder.prototype.includeFailed = function (value) {
this.url.setQuery("include_failed", value.toString());
return this;
};
return OperationCallBuilder;
}(call_builder_1.CallBuilder));
exports.OperationCallBuilder = OperationCallBuilder;
/***/ }),
/* 424 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OrderbookCallBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var call_builder_1 = __webpack_require__(6);
var OrderbookCallBuilder = (function (_super) {
tslib_1.__extends(OrderbookCallBuilder, _super);
function OrderbookCallBuilder(serverUrl, selling, buying) {
var _this = _super.call(this, serverUrl) || this;
_this.url.segment("order_book");
if (!selling.isNative()) {
_this.url.setQuery("selling_asset_type", selling.getAssetType());
_this.url.setQuery("selling_asset_code", selling.getCode());
_this.url.setQuery("selling_asset_issuer", selling.getIssuer());
}
else {
_this.url.setQuery("selling_asset_type", "native");
}
if (!buying.isNative()) {
_this.url.setQuery("buying_asset_type", buying.getAssetType());
_this.url.setQuery("buying_asset_code", buying.getCode());
_this.url.setQuery("buying_asset_issuer", buying.getIssuer());
}
else {
_this.url.setQuery("buying_asset_type", "native");
}
return _this;
}
return OrderbookCallBuilder;
}(call_builder_1.CallBuilder));
exports.OrderbookCallBuilder = OrderbookCallBuilder;
/***/ }),
/* 425 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PaymentCallBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var call_builder_1 = __webpack_require__(6);
var PaymentCallBuilder = (function (_super) {
tslib_1.__extends(PaymentCallBuilder, _super);
function PaymentCallBuilder(serverUrl) {
var _this = _super.call(this, serverUrl, "payments") || this;
_this.url.segment("payments");
return _this;
}
PaymentCallBuilder.prototype.forAccount = function (accountId) {
return this.forEndpoint("accounts", accountId);
};
PaymentCallBuilder.prototype.forLedger = function (sequence) {
return this.forEndpoint("ledgers", sequence.toString());
};
PaymentCallBuilder.prototype.forTransaction = function (transactionId) {
return this.forEndpoint("transactions", transactionId);
};
return PaymentCallBuilder;
}(call_builder_1.CallBuilder));
exports.PaymentCallBuilder = PaymentCallBuilder;
/***/ }),
/* 426 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StrictReceivePathCallBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var call_builder_1 = __webpack_require__(6);
var StrictReceivePathCallBuilder = (function (_super) {
tslib_1.__extends(StrictReceivePathCallBuilder, _super);
function StrictReceivePathCallBuilder(serverUrl, source, destinationAsset, destinationAmount) {
var _this = _super.call(this, serverUrl) || this;
_this.url.segment("paths/strict-receive");
if (typeof source === "string") {
_this.url.setQuery("source_account", source);
}
else {
var assets = source
.map(function (asset) {
if (asset.isNative()) {
return "native";
}
return asset.getCode() + ":" + asset.getIssuer();
})
.join(",");
_this.url.setQuery("source_assets", assets);
}
_this.url.setQuery("destination_amount", destinationAmount);
if (!destinationAsset.isNative()) {
_this.url.setQuery("destination_asset_type", destinationAsset.getAssetType());
_this.url.setQuery("destination_asset_code", destinationAsset.getCode());
_this.url.setQuery("destination_asset_issuer", destinationAsset.getIssuer());
}
else {
_this.url.setQuery("destination_asset_type", "native");
}
return _this;
}
return StrictReceivePathCallBuilder;
}(call_builder_1.CallBuilder));
exports.StrictReceivePathCallBuilder = StrictReceivePathCallBuilder;
/***/ }),
/* 427 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StrictSendPathCallBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var call_builder_1 = __webpack_require__(6);
var StrictSendPathCallBuilder = (function (_super) {
tslib_1.__extends(StrictSendPathCallBuilder, _super);
function StrictSendPathCallBuilder(serverUrl, sourceAsset, sourceAmount, destination) {
var _this = _super.call(this, serverUrl) || this;
_this.url.segment("paths/strict-send");
if (sourceAsset.isNative()) {
_this.url.setQuery("source_asset_type", "native");
}
else {
_this.url.setQuery("source_asset_type", sourceAsset.getAssetType());
_this.url.setQuery("source_asset_code", sourceAsset.getCode());
_this.url.setQuery("source_asset_issuer", sourceAsset.getIssuer());
}
_this.url.setQuery("source_amount", sourceAmount);
if (typeof destination === "string") {
_this.url.setQuery("destination_account", destination);
}
else {
var assets = destination
.map(function (asset) {
if (asset.isNative()) {
return "native";
}
return asset.getCode() + ":" + asset.getIssuer();
})
.join(",");
_this.url.setQuery("destination_assets", assets);
}
return _this;
}
return StrictSendPathCallBuilder;
}(call_builder_1.CallBuilder));
exports.StrictSendPathCallBuilder = StrictSendPathCallBuilder;
/***/ }),
/* 428 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TradeAggregationCallBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var call_builder_1 = __webpack_require__(6);
var errors_1 = __webpack_require__(36);
var allowedResolutions = [
60000,
300000,
900000,
3600000,
86400000,
604800000,
];
var TradeAggregationCallBuilder = (function (_super) {
tslib_1.__extends(TradeAggregationCallBuilder, _super);
function TradeAggregationCallBuilder(serverUrl, base, counter, start_time, end_time, resolution, offset) {
var _this = _super.call(this, serverUrl) || this;
_this.url.segment("trade_aggregations");
if (!base.isNative()) {
_this.url.setQuery("base_asset_type", base.getAssetType());
_this.url.setQuery("base_asset_code", base.getCode());
_this.url.setQuery("base_asset_issuer", base.getIssuer());
}
else {
_this.url.setQuery("base_asset_type", "native");
}
if (!counter.isNative()) {
_this.url.setQuery("counter_asset_type", counter.getAssetType());
_this.url.setQuery("counter_asset_code", counter.getCode());
_this.url.setQuery("counter_asset_issuer", counter.getIssuer());
}
else {
_this.url.setQuery("counter_asset_type", "native");
}
if (typeof start_time !== "number" || typeof end_time !== "number") {
throw new errors_1.BadRequestError("Invalid time bounds", [start_time, end_time]);
}
else {
_this.url.setQuery("start_time", start_time.toString());
_this.url.setQuery("end_time", end_time.toString());
}
if (!_this.isValidResolution(resolution)) {
throw new errors_1.BadRequestError("Invalid resolution", resolution);
}
else {
_this.url.setQuery("resolution", resolution.toString());
}
if (!_this.isValidOffset(offset, resolution)) {
throw new errors_1.BadRequestError("Invalid offset", offset);
}
else {
_this.url.setQuery("offset", offset.toString());
}
return _this;
}
TradeAggregationCallBuilder.prototype.isValidResolution = function (resolution) {
for (var _i = 0, allowedResolutions_1 = allowedResolutions; _i < allowedResolutions_1.length; _i++) {
var allowed = allowedResolutions_1[_i];
if (allowed === resolution) {
return true;
}
}
return false;
};
TradeAggregationCallBuilder.prototype.isValidOffset = function (offset, resolution) {
var hour = 3600000;
return !(offset > resolution || offset >= 24 * hour || offset % hour !== 0);
};
return TradeAggregationCallBuilder;
}(call_builder_1.CallBuilder));
exports.TradeAggregationCallBuilder = TradeAggregationCallBuilder;
/***/ }),
/* 429 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TradesCallBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var call_builder_1 = __webpack_require__(6);
var TradesCallBuilder = (function (_super) {
tslib_1.__extends(TradesCallBuilder, _super);
function TradesCallBuilder(serverUrl) {
var _this = _super.call(this, serverUrl, "trades") || this;
_this.url.segment("trades");
return _this;
}
TradesCallBuilder.prototype.forAssetPair = function (base, counter) {
if (!base.isNative()) {
this.url.setQuery("base_asset_type", base.getAssetType());
this.url.setQuery("base_asset_code", base.getCode());
this.url.setQuery("base_asset_issuer", base.getIssuer());
}
else {
this.url.setQuery("base_asset_type", "native");
}
if (!counter.isNative()) {
this.url.setQuery("counter_asset_type", counter.getAssetType());
this.url.setQuery("counter_asset_code", counter.getCode());
this.url.setQuery("counter_asset_issuer", counter.getIssuer());
}
else {
this.url.setQuery("counter_asset_type", "native");
}
return this;
};
TradesCallBuilder.prototype.forOffer = function (offerId) {
this.url.setQuery("offer_id", offerId);
return this;
};
TradesCallBuilder.prototype.forType = function (tradeType) {
this.url.setQuery("trade_type", tradeType);
return this;
};
TradesCallBuilder.prototype.forAccount = function (accountId) {
return this.forEndpoint("accounts", accountId);
};
TradesCallBuilder.prototype.forLiquidityPool = function (liquidityPoolId) {
return this.forEndpoint("liquidity_pools", liquidityPoolId);
};
return TradesCallBuilder;
}(call_builder_1.CallBuilder));
exports.TradesCallBuilder = TradesCallBuilder;
/***/ }),
/* 430 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TransactionCallBuilder = void 0;
var tslib_1 = __webpack_require__(2);
var call_builder_1 = __webpack_require__(6);
var TransactionCallBuilder = (function (_super) {
tslib_1.__extends(TransactionCallBuilder, _super);
function TransactionCallBuilder(serverUrl) {
var _this = _super.call(this, serverUrl, "transactions") || this;
_this.url.segment("transactions");
return _this;
}
TransactionCallBuilder.prototype.transaction = function (transactionId) {
var builder = new call_builder_1.CallBuilder(this.url.clone());
builder.filter.push([transactionId]);
return builder;
};
TransactionCallBuilder.prototype.forAccount = function (accountId) {
return this.forEndpoint("accounts", accountId);
};
TransactionCallBuilder.prototype.forClaimableBalance = function (claimableBalanceId) {
return this.forEndpoint("claimable_balances", claimableBalanceId);
};
TransactionCallBuilder.prototype.forLedger = function (sequence) {
return this.forEndpoint("ledgers", sequence.toString());
};
TransactionCallBuilder.prototype.forLiquidityPool = function (poolId) {
return this.forEndpoint("liquidity_pools", poolId);
};
TransactionCallBuilder.prototype.includeFailed = function (value) {
this.url.setQuery("include_failed", value.toString());
return this;
};
return TransactionCallBuilder;
}(call_builder_1.CallBuilder));
exports.TransactionCallBuilder = TransactionCallBuilder;
/***/ }),
/* 431 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FederationServer = exports.FEDERATION_RESPONSE_MAX_SIZE = void 0;
var tslib_1 = __webpack_require__(2);
var axios_1 = tslib_1.__importDefault(__webpack_require__(61));
var stellar_base_1 = __webpack_require__(29);
var urijs_1 = tslib_1.__importDefault(__webpack_require__(37));
var config_1 = __webpack_require__(60);
var errors_1 = __webpack_require__(36);
var stellar_toml_resolver_1 = __webpack_require__(175);
exports.FEDERATION_RESPONSE_MAX_SIZE = 100 * 1024;
var FederationServer = (function () {
function FederationServer(serverURL, domain, opts) {
if (opts === void 0) { opts = {}; }
this.serverURL = urijs_1.default(serverURL);
this.domain = domain;
var allowHttp = typeof opts.allowHttp === "undefined"
? config_1.Config.isAllowHttp()
: opts.allowHttp;
this.timeout =
typeof opts.timeout === "undefined" ? config_1.Config.getTimeout() : opts.timeout;
if (this.serverURL.protocol() !== "https" && !allowHttp) {
throw new Error("Cannot connect to insecure federation server");
}
}
FederationServer.resolve = function (value, opts) {
if (opts === void 0) { opts = {}; }
return tslib_1.__awaiter(this, void 0, void 0, function () {
var addressParts, domain, federationServer;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0:
if (value.indexOf("*") < 0) {
if (!stellar_base_1.StrKey.isValidEd25519PublicKey(value)) {
return [2, Promise.reject(new Error("Invalid Account ID"))];
}
return [2, Promise.resolve({ account_id: value })];
}
addressParts = value.split("*");
domain = addressParts[1];
if (addressParts.length !== 2 || !domain) {
return [2, Promise.reject(new Error("Invalid Stellar address"))];
}
return [4, FederationServer.createForDomain(domain, opts)];
case 1:
federationServer = _a.sent();
return [2, federationServer.resolveAddress(value)];
}
});
});
};
FederationServer.createForDomain = function (domain, opts) {
if (opts === void 0) { opts = {}; }
return tslib_1.__awaiter(this, void 0, void 0, function () {
var tomlObject;
return tslib_1.__generator(this, function (_a) {
switch (_a.label) {
case 0: return [4, stellar_toml_resolver_1.StellarTomlResolver.resolve(domain, opts)];
case 1:
tomlObject = _a.sent();
if (!tomlObject.FEDERATION_SERVER) {
return [2, Promise.reject(new Error("stellar.toml does not contain FEDERATION_SERVER field"))];
}
return [2, new FederationServer(tomlObject.FEDERATION_SERVER, domain, opts)];
}
});
});
};
FederationServer.prototype.resolveAddress = function (address) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var stellarAddress, url;
return tslib_1.__generator(this, function (_a) {
stellarAddress = address;
if (address.indexOf("*") < 0) {
if (!this.domain) {
return [2, Promise.reject(new Error("Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object."))];
}
stellarAddress = address + "*" + this.domain;
}
url = this.serverURL.query({ type: "name", q: stellarAddress });
return [2, this._sendRequest(url)];
});
});
};
FederationServer.prototype.resolveAccountId = function (accountId) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url;
return tslib_1.__generator(this, function (_a) {
url = this.serverURL.query({ type: "id", q: accountId });
return [2, this._sendRequest(url)];
});
});
};
FederationServer.prototype.resolveTransactionId = function (transactionId) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var url;
return tslib_1.__generator(this, function (_a) {
url = this.serverURL.query({ type: "txid", q: transactionId });
return [2, this._sendRequest(url)];
});
});
};
FederationServer.prototype._sendRequest = function (url) {
return tslib_1.__awaiter(this, void 0, void 0, function () {
var timeout;
return tslib_1.__generator(this, function (_a) {
timeout = this.timeout;
return [2, axios_1.default
.get(url.toString(), {
maxContentLength: exports.FEDERATION_RESPONSE_MAX_SIZE,
timeout: timeout,
})
.then(function (response) {
if (typeof response.data.memo !== "undefined" &&
typeof response.data.memo !== "string") {
throw new Error("memo value should be of type string");
}
return response.data;
})
.catch(function (response) {
if (response instanceof Error) {
if (response.message.match(/^maxContentLength size/)) {
throw new Error("federation response exceeds allowed size of " + exports.FEDERATION_RESPONSE_MAX_SIZE);
}
else {
return Promise.reject(response);
}
}
else {
return Promise.reject(new errors_1.BadResponseError("Server query failed. Server responded: " + response.status + " " + response.statusText, response.data));
}
})];
});
});
};
return FederationServer;
}());
exports.FederationServer = FederationServer;
/***/ }),
/* 432 */
/***/ (function(module, exports, __webpack_require__) {
var parser = __webpack_require__(433);
var compiler = __webpack_require__(434);
module.exports = {
parse: function(input) {
var nodes = parser.parse(input.toString());
return compiler.compile(nodes);
}
};
/***/ }),
/* 433 */
/***/ (function(module, exports) {
module.exports = (function() {
/*
* Generated by PEG.js 0.8.0.
*
* http://pegjs.majda.cz/
*/
function peg$subclass(child, parent) {
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor();
}
function SyntaxError(message, expected, found, offset, line, column) {
this.message = message;
this.expected = expected;
this.found = found;
this.offset = offset;
this.line = line;
this.column = column;
this.name = "SyntaxError";
}
peg$subclass(SyntaxError, Error);
function parse(input) {
var options = arguments.length > 1 ? arguments[1] : {},
peg$FAILED = {},
peg$startRuleFunctions = { start: peg$parsestart },
peg$startRuleFunction = peg$parsestart,
peg$c0 = [],
peg$c1 = function() { return nodes },
peg$c2 = peg$FAILED,
peg$c3 = "#",
peg$c4 = { type: "literal", value: "#", description: "\"#\"" },
peg$c5 = void 0,
peg$c6 = { type: "any", description: "any character" },
peg$c7 = "[",
peg$c8 = { type: "literal", value: "[", description: "\"[\"" },
peg$c9 = "]",
peg$c10 = { type: "literal", value: "]", description: "\"]\"" },
peg$c11 = function(name) { addNode(node('ObjectPath', name, line, column)) },
peg$c12 = function(name) { addNode(node('ArrayPath', name, line, column)) },
peg$c13 = function(parts, name) { return parts.concat(name) },
peg$c14 = function(name) { return [name] },
peg$c15 = function(name) { return name },
peg$c16 = ".",
peg$c17 = { type: "literal", value: ".", description: "\".\"" },
peg$c18 = "=",
peg$c19 = { type: "literal", value: "=", description: "\"=\"" },
peg$c20 = function(key, value) { addNode(node('Assign', value, line, column, key)) },
peg$c21 = function(chars) { return chars.join('') },
peg$c22 = function(node) { return node.value },
peg$c23 = "\"\"\"",
peg$c24 = { type: "literal", value: "\"\"\"", description: "\"\\\"\\\"\\\"\"" },
peg$c25 = null,
peg$c26 = function(chars) { return node('String', chars.join(''), line, column) },
peg$c27 = "\"",
peg$c28 = { type: "literal", value: "\"", description: "\"\\\"\"" },
peg$c29 = "'''",
peg$c30 = { type: "literal", value: "'''", description: "\"'''\"" },
peg$c31 = "'",
peg$c32 = { type: "literal", value: "'", description: "\"'\"" },
peg$c33 = function(char) { return char },
peg$c34 = function(char) { return char},
peg$c35 = "\\",
peg$c36 = { type: "literal", value: "\\", description: "\"\\\\\"" },
peg$c37 = function() { return '' },
peg$c38 = "e",
peg$c39 = { type: "literal", value: "e", description: "\"e\"" },
peg$c40 = "E",
peg$c41 = { type: "literal", value: "E", description: "\"E\"" },
peg$c42 = function(left, right) { return node('Float', parseFloat(left + 'e' + right), line, column) },
peg$c43 = function(text) { return node('Float', parseFloat(text), line, column) },
peg$c44 = "+",
peg$c45 = { type: "literal", value: "+", description: "\"+\"" },
peg$c46 = function(digits) { return digits.join('') },
peg$c47 = "-",
peg$c48 = { type: "literal", value: "-", description: "\"-\"" },
peg$c49 = function(digits) { return '-' + digits.join('') },
peg$c50 = function(text) { return node('Integer', parseInt(text, 10), line, column) },
peg$c51 = "true",
peg$c52 = { type: "literal", value: "true", description: "\"true\"" },
peg$c53 = function() { return node('Boolean', true, line, column) },
peg$c54 = "false",
peg$c55 = { type: "literal", value: "false", description: "\"false\"" },
peg$c56 = function() { return node('Boolean', false, line, column) },
peg$c57 = function() { return node('Array', [], line, column) },
peg$c58 = function(value) { return node('Array', value ? [value] : [], line, column) },
peg$c59 = function(values) { return node('Array', values, line, column) },
peg$c60 = function(values, value) { return node('Array', values.concat(value), line, column) },
peg$c61 = function(value) { return value },
peg$c62 = ",",
peg$c63 = { type: "literal", value: ",", description: "\",\"" },
peg$c64 = "{",
peg$c65 = { type: "literal", value: "{", description: "\"{\"" },
peg$c66 = "}",
peg$c67 = { type: "literal", value: "}", description: "\"}\"" },
peg$c68 = function(values) { return node('InlineTable', values, line, column) },
peg$c69 = function(key, value) { return node('InlineTableValue', value, line, column, key) },
peg$c70 = function(digits) { return "." + digits },
peg$c71 = function(date) { return date.join('') },
peg$c72 = ":",
peg$c73 = { type: "literal", value: ":", description: "\":\"" },
peg$c74 = function(time) { return time.join('') },
peg$c75 = "T",
peg$c76 = { type: "literal", value: "T", description: "\"T\"" },
peg$c77 = "Z",
peg$c78 = { type: "literal", value: "Z", description: "\"Z\"" },
peg$c79 = function(date, time) { return node('Date', new Date(date + "T" + time + "Z"), line, column) },
peg$c80 = function(date, time) { return node('Date', new Date(date + "T" + time), line, column) },
peg$c81 = /^[ \t]/,
peg$c82 = { type: "class", value: "[ \\t]", description: "[ \\t]" },
peg$c83 = "\n",
peg$c84 = { type: "literal", value: "\n", description: "\"\\n\"" },
peg$c85 = "\r",
peg$c86 = { type: "literal", value: "\r", description: "\"\\r\"" },
peg$c87 = /^[0-9a-f]/i,
peg$c88 = { type: "class", value: "[0-9a-f]i", description: "[0-9a-f]i" },
peg$c89 = /^[0-9]/,
peg$c90 = { type: "class", value: "[0-9]", description: "[0-9]" },
peg$c91 = "_",
peg$c92 = { type: "literal", value: "_", description: "\"_\"" },
peg$c93 = function() { return "" },
peg$c94 = /^[A-Za-z0-9_\-]/,
peg$c95 = { type: "class", value: "[A-Za-z0-9_\\-]", description: "[A-Za-z0-9_\\-]" },
peg$c96 = function(d) { return d.join('') },
peg$c97 = "\\\"",
peg$c98 = { type: "literal", value: "\\\"", description: "\"\\\\\\\"\"" },
peg$c99 = function() { return '"' },
peg$c100 = "\\\\",
peg$c101 = { type: "literal", value: "\\\\", description: "\"\\\\\\\\\"" },
peg$c102 = function() { return '\\' },
peg$c103 = "\\b",
peg$c104 = { type: "literal", value: "\\b", description: "\"\\\\b\"" },
peg$c105 = function() { return '\b' },
peg$c106 = "\\t",
peg$c107 = { type: "literal", value: "\\t", description: "\"\\\\t\"" },
peg$c108 = function() { return '\t' },
peg$c109 = "\\n",
peg$c110 = { type: "literal", value: "\\n", description: "\"\\\\n\"" },
peg$c111 = function() { return '\n' },
peg$c112 = "\\f",
peg$c113 = { type: "literal", value: "\\f", description: "\"\\\\f\"" },
peg$c114 = function() { return '\f' },
peg$c115 = "\\r",
peg$c116 = { type: "literal", value: "\\r", description: "\"\\\\r\"" },
peg$c117 = function() { return '\r' },
peg$c118 = "\\U",
peg$c119 = { type: "literal", value: "\\U", description: "\"\\\\U\"" },
peg$c120 = function(digits) { return convertCodePoint(digits.join('')) },
peg$c121 = "\\u",
peg$c122 = { type: "literal", value: "\\u", description: "\"\\\\u\"" },
peg$currPos = 0,
peg$reportedPos = 0,
peg$cachedPos = 0,
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false },
peg$maxFailPos = 0,
peg$maxFailExpected = [],
peg$silentFails = 0,
peg$cache = {},
peg$result;
if ("startRule" in options) {
if (!(options.startRule in peg$startRuleFunctions)) {
throw new Error("Can't start parsing from rule \"" + options.startRule + "\".");
}
peg$startRuleFunction = peg$startRuleFunctions[options.startRule];
}
function text() {
return input.substring(peg$reportedPos, peg$currPos);
}
function offset() {
return peg$reportedPos;
}
function line() {
return peg$computePosDetails(peg$reportedPos).line;
}
function column() {
return peg$computePosDetails(peg$reportedPos).column;
}
function expected(description) {
throw peg$buildException(
null,
[{ type: "other", description: description }],
peg$reportedPos
);
}
function error(message) {
throw peg$buildException(message, null, peg$reportedPos);
}
function peg$computePosDetails(pos) {
function advance(details, startPos, endPos) {
var p, ch;
for (p = startPos; p < endPos; p++) {
ch = input.charAt(p);
if (ch === "\n") {
if (!details.seenCR) { details.line++; }
details.column = 1;
details.seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
details.line++;
details.column = 1;
details.seenCR = true;
} else {
details.column++;
details.seenCR = false;
}
}
}
if (peg$cachedPos !== pos) {
if (peg$cachedPos > pos) {
peg$cachedPos = 0;
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false };
}
advance(peg$cachedPosDetails, peg$cachedPos, pos);
peg$cachedPos = pos;
}
return peg$cachedPosDetails;
}
function peg$fail(expected) {
if (peg$currPos < peg$maxFailPos) { return; }
if (peg$currPos > peg$maxFailPos) {
peg$maxFailPos = peg$currPos;
peg$maxFailExpected = [];
}
peg$maxFailExpected.push(expected);
}
function peg$buildException(message, expected, pos) {
function cleanupExpected(expected) {
var i = 1;
expected.sort(function(a, b) {
if (a.description < b.description) {
return -1;
} else if (a.description > b.description) {
return 1;
} else {
return 0;
}
});
while (i < expected.length) {
if (expected[i - 1] === expected[i]) {
expected.splice(i, 1);
} else {
i++;
}
}
}
function buildMessage(expected, found) {
function stringEscape(s) {
function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); }
return s
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\x08/g, '\\b')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\f/g, '\\f')
.replace(/\r/g, '\\r')
.replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); })
.replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); })
.replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); })
.replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); });
}
var expectedDescs = new Array(expected.length),
expectedDesc, foundDesc, i;
for (i = 0; i < expected.length; i++) {
expectedDescs[i] = expected[i].description;
}
expectedDesc = expected.length > 1
? expectedDescs.slice(0, -1).join(", ")
+ " or "
+ expectedDescs[expected.length - 1]
: expectedDescs[0];
foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input";
return "Expected " + expectedDesc + " but " + foundDesc + " found.";
}
var posDetails = peg$computePosDetails(pos),
found = pos < input.length ? input.charAt(pos) : null;
if (expected !== null) {
cleanupExpected(expected);
}
return new SyntaxError(
message !== null ? message : buildMessage(expected, found),
expected,
found,
pos,
posDetails.line,
posDetails.column
);
}
function peg$parsestart() {
var s0, s1, s2;
var key = peg$currPos * 49 + 0,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parseline();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseline();
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c1();
}
s0 = s1;
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseline() {
var s0, s1, s2, s3, s4, s5, s6;
var key = peg$currPos * 49 + 1,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parseS();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseS();
}
if (s1 !== peg$FAILED) {
s2 = peg$parseexpression();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseS();
}
if (s3 !== peg$FAILED) {
s4 = [];
s5 = peg$parsecomment();
while (s5 !== peg$FAILED) {
s4.push(s5);
s5 = peg$parsecomment();
}
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$parseNL();
if (s6 !== peg$FAILED) {
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$parseNL();
}
} else {
s5 = peg$c2;
}
if (s5 === peg$FAILED) {
s5 = peg$parseEOF();
}
if (s5 !== peg$FAILED) {
s1 = [s1, s2, s3, s4, s5];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = [];
s2 = peg$parseS();
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseS();
}
} else {
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseNL();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseNL();
}
} else {
s2 = peg$c2;
}
if (s2 === peg$FAILED) {
s2 = peg$parseEOF();
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$parseNL();
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseexpression() {
var s0;
var key = peg$currPos * 49 + 2,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$parsecomment();
if (s0 === peg$FAILED) {
s0 = peg$parsepath();
if (s0 === peg$FAILED) {
s0 = peg$parsetablearray();
if (s0 === peg$FAILED) {
s0 = peg$parseassignment();
}
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsecomment() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 49 + 3,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 35) {
s1 = peg$c3;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c4); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$currPos;
peg$silentFails++;
s5 = peg$parseNL();
if (s5 === peg$FAILED) {
s5 = peg$parseEOF();
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c5;
} else {
peg$currPos = s4;
s4 = peg$c2;
}
if (s4 !== peg$FAILED) {
if (input.length > peg$currPos) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c6); }
}
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c2;
}
} else {
peg$currPos = s3;
s3 = peg$c2;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$currPos;
peg$silentFails++;
s5 = peg$parseNL();
if (s5 === peg$FAILED) {
s5 = peg$parseEOF();
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c5;
} else {
peg$currPos = s4;
s4 = peg$c2;
}
if (s4 !== peg$FAILED) {
if (input.length > peg$currPos) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c6); }
}
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c2;
}
} else {
peg$currPos = s3;
s3 = peg$c2;
}
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsepath() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 49 + 4,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 91) {
s1 = peg$c7;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseS();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseS();
}
if (s2 !== peg$FAILED) {
s3 = peg$parsetable_key();
if (s3 !== peg$FAILED) {
s4 = [];
s5 = peg$parseS();
while (s5 !== peg$FAILED) {
s4.push(s5);
s5 = peg$parseS();
}
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s5 = peg$c9;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c10); }
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c11(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsetablearray() {
var s0, s1, s2, s3, s4, s5, s6, s7;
var key = peg$currPos * 49 + 5,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 91) {
s1 = peg$c7;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 91) {
s2 = peg$c7;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseS();
}
if (s3 !== peg$FAILED) {
s4 = peg$parsetable_key();
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$parseS();
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$parseS();
}
if (s5 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s6 = peg$c9;
peg$currPos++;
} else {
s6 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c10); }
}
if (s6 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s7 = peg$c9;
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c10); }
}
if (s7 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c12(s4);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsetable_key() {
var s0, s1, s2;
var key = peg$currPos * 49 + 6,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parsedot_ended_table_key_part();
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parsedot_ended_table_key_part();
}
} else {
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
s2 = peg$parsetable_key_part();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c13(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsetable_key_part();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c14(s1);
}
s0 = s1;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsetable_key_part() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 49 + 7,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parseS();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseS();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsekey();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseS();
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c15(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = [];
s2 = peg$parseS();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseS();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsequoted_key();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseS();
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c15(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsedot_ended_table_key_part() {
var s0, s1, s2, s3, s4, s5, s6;
var key = peg$currPos * 49 + 8,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parseS();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseS();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsekey();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseS();
}
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c16;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$parseS();
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$parseS();
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c15(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = [];
s2 = peg$parseS();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseS();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsequoted_key();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseS();
}
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c16;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$parseS();
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$parseS();
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c15(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseassignment() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 49 + 9,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parsekey();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseS();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseS();
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s3 = peg$c18;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c19); }
}
if (s3 !== peg$FAILED) {
s4 = [];
s5 = peg$parseS();
while (s5 !== peg$FAILED) {
s4.push(s5);
s5 = peg$parseS();
}
if (s4 !== peg$FAILED) {
s5 = peg$parsevalue();
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c20(s1, s5);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsequoted_key();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseS();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseS();
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s3 = peg$c18;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c19); }
}
if (s3 !== peg$FAILED) {
s4 = [];
s5 = peg$parseS();
while (s5 !== peg$FAILED) {
s4.push(s5);
s5 = peg$parseS();
}
if (s4 !== peg$FAILED) {
s5 = peg$parsevalue();
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c20(s1, s5);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsekey() {
var s0, s1, s2;
var key = peg$currPos * 49 + 10,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parseASCII_BASIC();
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseASCII_BASIC();
}
} else {
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c21(s1);
}
s0 = s1;
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsequoted_key() {
var s0, s1;
var key = peg$currPos * 49 + 11,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parsedouble_quoted_single_line_string();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c22(s1);
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsesingle_quoted_single_line_string();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c22(s1);
}
s0 = s1;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsevalue() {
var s0;
var key = peg$currPos * 49 + 12,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$parsestring();
if (s0 === peg$FAILED) {
s0 = peg$parsedatetime();
if (s0 === peg$FAILED) {
s0 = peg$parsefloat();
if (s0 === peg$FAILED) {
s0 = peg$parseinteger();
if (s0 === peg$FAILED) {
s0 = peg$parseboolean();
if (s0 === peg$FAILED) {
s0 = peg$parsearray();
if (s0 === peg$FAILED) {
s0 = peg$parseinline_table();
}
}
}
}
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsestring() {
var s0;
var key = peg$currPos * 49 + 13,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$parsedouble_quoted_multiline_string();
if (s0 === peg$FAILED) {
s0 = peg$parsedouble_quoted_single_line_string();
if (s0 === peg$FAILED) {
s0 = peg$parsesingle_quoted_multiline_string();
if (s0 === peg$FAILED) {
s0 = peg$parsesingle_quoted_single_line_string();
}
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsedouble_quoted_multiline_string() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 49 + 14,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 3) === peg$c23) {
s1 = peg$c23;
peg$currPos += 3;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c24); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseNL();
if (s2 === peg$FAILED) {
s2 = peg$c25;
}
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parsemultiline_string_char();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parsemultiline_string_char();
}
if (s3 !== peg$FAILED) {
if (input.substr(peg$currPos, 3) === peg$c23) {
s4 = peg$c23;
peg$currPos += 3;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c24); }
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c26(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsedouble_quoted_single_line_string() {
var s0, s1, s2, s3;
var key = peg$currPos * 49 + 15,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 34) {
s1 = peg$c27;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c28); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsestring_char();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsestring_char();
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 34) {
s3 = peg$c27;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c28); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c26(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsesingle_quoted_multiline_string() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 49 + 16,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 3) === peg$c29) {
s1 = peg$c29;
peg$currPos += 3;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c30); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseNL();
if (s2 === peg$FAILED) {
s2 = peg$c25;
}
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parsemultiline_literal_char();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parsemultiline_literal_char();
}
if (s3 !== peg$FAILED) {
if (input.substr(peg$currPos, 3) === peg$c29) {
s4 = peg$c29;
peg$currPos += 3;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c30); }
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c26(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsesingle_quoted_single_line_string() {
var s0, s1, s2, s3;
var key = peg$currPos * 49 + 17,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 39) {
s1 = peg$c31;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c32); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseliteral_char();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseliteral_char();
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 39) {
s3 = peg$c31;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c32); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c26(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsestring_char() {
var s0, s1, s2;
var key = peg$currPos * 49 + 18,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$parseESCAPED();
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 34) {
s2 = peg$c27;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c28); }
}
peg$silentFails--;
if (s2 === peg$FAILED) {
s1 = peg$c5;
} else {
peg$currPos = s1;
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
if (input.length > peg$currPos) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c6); }
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c33(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseliteral_char() {
var s0, s1, s2;
var key = peg$currPos * 49 + 19,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 39) {
s2 = peg$c31;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c32); }
}
peg$silentFails--;
if (s2 === peg$FAILED) {
s1 = peg$c5;
} else {
peg$currPos = s1;
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
if (input.length > peg$currPos) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c6); }
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c33(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsemultiline_string_char() {
var s0, s1, s2;
var key = peg$currPos * 49 + 20,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$parseESCAPED();
if (s0 === peg$FAILED) {
s0 = peg$parsemultiline_string_delim();
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$currPos;
peg$silentFails++;
if (input.substr(peg$currPos, 3) === peg$c23) {
s2 = peg$c23;
peg$currPos += 3;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c24); }
}
peg$silentFails--;
if (s2 === peg$FAILED) {
s1 = peg$c5;
} else {
peg$currPos = s1;
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
if (input.length > peg$currPos) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c6); }
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c34(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsemultiline_string_delim() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 49 + 21,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 92) {
s1 = peg$c35;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c36); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseNL();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseNLS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseNLS();
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c37();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsemultiline_literal_char() {
var s0, s1, s2;
var key = peg$currPos * 49 + 22,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$currPos;
peg$silentFails++;
if (input.substr(peg$currPos, 3) === peg$c29) {
s2 = peg$c29;
peg$currPos += 3;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c30); }
}
peg$silentFails--;
if (s2 === peg$FAILED) {
s1 = peg$c5;
} else {
peg$currPos = s1;
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
if (input.length > peg$currPos) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c6); }
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c33(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsefloat() {
var s0, s1, s2, s3;
var key = peg$currPos * 49 + 23,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parsefloat_text();
if (s1 === peg$FAILED) {
s1 = peg$parseinteger_text();
}
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 101) {
s2 = peg$c38;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c39); }
}
if (s2 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 69) {
s2 = peg$c40;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c41); }
}
}
if (s2 !== peg$FAILED) {
s3 = peg$parseinteger_text();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c42(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsefloat_text();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c43(s1);
}
s0 = s1;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsefloat_text() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 49 + 24,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 43) {
s1 = peg$c44;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c45); }
}
if (s1 === peg$FAILED) {
s1 = peg$c25;
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
s3 = peg$parseDIGITS();
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c16;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
if (s4 !== peg$FAILED) {
s5 = peg$parseDIGITS();
if (s5 !== peg$FAILED) {
s3 = [s3, s4, s5];
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c46(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 45) {
s1 = peg$c47;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c48); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
s3 = peg$parseDIGITS();
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c16;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
if (s4 !== peg$FAILED) {
s5 = peg$parseDIGITS();
if (s5 !== peg$FAILED) {
s3 = [s3, s4, s5];
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c49(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseinteger() {
var s0, s1;
var key = peg$currPos * 49 + 25,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parseinteger_text();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c50(s1);
}
s0 = s1;
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseinteger_text() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 49 + 26,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 43) {
s1 = peg$c44;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c45); }
}
if (s1 === peg$FAILED) {
s1 = peg$c25;
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseDIGIT_OR_UNDER();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseDIGIT_OR_UNDER();
}
} else {
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
s3 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c16;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
peg$silentFails--;
if (s4 === peg$FAILED) {
s3 = peg$c5;
} else {
peg$currPos = s3;
s3 = peg$c2;
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c46(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 45) {
s1 = peg$c47;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c48); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseDIGIT_OR_UNDER();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseDIGIT_OR_UNDER();
}
} else {
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
s3 = peg$currPos;
peg$silentFails++;
if (input.charCodeAt(peg$currPos) === 46) {
s4 = peg$c16;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
peg$silentFails--;
if (s4 === peg$FAILED) {
s3 = peg$c5;
} else {
peg$currPos = s3;
s3 = peg$c2;
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c49(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseboolean() {
var s0, s1;
var key = peg$currPos * 49 + 27,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 4) === peg$c51) {
s1 = peg$c51;
peg$currPos += 4;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c52); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c53();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.substr(peg$currPos, 5) === peg$c54) {
s1 = peg$c54;
peg$currPos += 5;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c55); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c56();
}
s0 = s1;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsearray() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 49 + 28,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 91) {
s1 = peg$c7;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsearray_sep();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsearray_sep();
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s3 = peg$c9;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c10); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c57();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 91) {
s1 = peg$c7;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parsearray_value();
if (s2 === peg$FAILED) {
s2 = peg$c25;
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s3 = peg$c9;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c10); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c58(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 91) {
s1 = peg$c7;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsearray_value_list();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsearray_value_list();
}
} else {
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s3 = peg$c9;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c10); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c59(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 91) {
s1 = peg$c7;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsearray_value_list();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsearray_value_list();
}
} else {
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
s3 = peg$parsearray_value();
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 93) {
s4 = peg$c9;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c10); }
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c60(s2, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
}
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsearray_value() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 49 + 29,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parsearray_sep();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parsearray_sep();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsevalue();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parsearray_sep();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parsearray_sep();
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c61(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsearray_value_list() {
var s0, s1, s2, s3, s4, s5, s6;
var key = peg$currPos * 49 + 30,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parsearray_sep();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parsearray_sep();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsevalue();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parsearray_sep();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parsearray_sep();
}
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s4 = peg$c62;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c63); }
}
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$parsearray_sep();
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$parsearray_sep();
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c61(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsearray_sep() {
var s0;
var key = peg$currPos * 49 + 31,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$parseS();
if (s0 === peg$FAILED) {
s0 = peg$parseNL();
if (s0 === peg$FAILED) {
s0 = peg$parsecomment();
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseinline_table() {
var s0, s1, s2, s3, s4, s5;
var key = peg$currPos * 49 + 32,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 123) {
s1 = peg$c64;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c65); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseS();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseS();
}
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseinline_table_assignment();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseinline_table_assignment();
}
if (s3 !== peg$FAILED) {
s4 = [];
s5 = peg$parseS();
while (s5 !== peg$FAILED) {
s4.push(s5);
s5 = peg$parseS();
}
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 125) {
s5 = peg$c66;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c67); }
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c68(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseinline_table_assignment() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10;
var key = peg$currPos * 49 + 33,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parseS();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseS();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsekey();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseS();
}
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s4 = peg$c18;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c19); }
}
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$parseS();
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$parseS();
}
if (s5 !== peg$FAILED) {
s6 = peg$parsevalue();
if (s6 !== peg$FAILED) {
s7 = [];
s8 = peg$parseS();
while (s8 !== peg$FAILED) {
s7.push(s8);
s8 = peg$parseS();
}
if (s7 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 44) {
s8 = peg$c62;
peg$currPos++;
} else {
s8 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c63); }
}
if (s8 !== peg$FAILED) {
s9 = [];
s10 = peg$parseS();
while (s10 !== peg$FAILED) {
s9.push(s10);
s10 = peg$parseS();
}
if (s9 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c69(s2, s6);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = [];
s2 = peg$parseS();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseS();
}
if (s1 !== peg$FAILED) {
s2 = peg$parsekey();
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseS();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseS();
}
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s4 = peg$c18;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c19); }
}
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$parseS();
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$parseS();
}
if (s5 !== peg$FAILED) {
s6 = peg$parsevalue();
if (s6 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c69(s2, s6);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsesecfragment() {
var s0, s1, s2;
var key = peg$currPos * 49 + 34,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s1 = peg$c16;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseDIGITS();
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c70(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsedate() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11;
var key = peg$currPos * 49 + 35,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$currPos;
s2 = peg$parseDIGIT_OR_UNDER();
if (s2 !== peg$FAILED) {
s3 = peg$parseDIGIT_OR_UNDER();
if (s3 !== peg$FAILED) {
s4 = peg$parseDIGIT_OR_UNDER();
if (s4 !== peg$FAILED) {
s5 = peg$parseDIGIT_OR_UNDER();
if (s5 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 45) {
s6 = peg$c47;
peg$currPos++;
} else {
s6 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c48); }
}
if (s6 !== peg$FAILED) {
s7 = peg$parseDIGIT_OR_UNDER();
if (s7 !== peg$FAILED) {
s8 = peg$parseDIGIT_OR_UNDER();
if (s8 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 45) {
s9 = peg$c47;
peg$currPos++;
} else {
s9 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c48); }
}
if (s9 !== peg$FAILED) {
s10 = peg$parseDIGIT_OR_UNDER();
if (s10 !== peg$FAILED) {
s11 = peg$parseDIGIT_OR_UNDER();
if (s11 !== peg$FAILED) {
s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11];
s1 = s2;
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c71(s1);
}
s0 = s1;
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsetime() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10;
var key = peg$currPos * 49 + 36,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$currPos;
s2 = peg$parseDIGIT_OR_UNDER();
if (s2 !== peg$FAILED) {
s3 = peg$parseDIGIT_OR_UNDER();
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s4 = peg$c72;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c73); }
}
if (s4 !== peg$FAILED) {
s5 = peg$parseDIGIT_OR_UNDER();
if (s5 !== peg$FAILED) {
s6 = peg$parseDIGIT_OR_UNDER();
if (s6 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s7 = peg$c72;
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c73); }
}
if (s7 !== peg$FAILED) {
s8 = peg$parseDIGIT_OR_UNDER();
if (s8 !== peg$FAILED) {
s9 = peg$parseDIGIT_OR_UNDER();
if (s9 !== peg$FAILED) {
s10 = peg$parsesecfragment();
if (s10 === peg$FAILED) {
s10 = peg$c25;
}
if (s10 !== peg$FAILED) {
s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10];
s1 = s2;
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c74(s1);
}
s0 = s1;
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsetime_with_offset() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16;
var key = peg$currPos * 49 + 37,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$currPos;
s2 = peg$parseDIGIT_OR_UNDER();
if (s2 !== peg$FAILED) {
s3 = peg$parseDIGIT_OR_UNDER();
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s4 = peg$c72;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c73); }
}
if (s4 !== peg$FAILED) {
s5 = peg$parseDIGIT_OR_UNDER();
if (s5 !== peg$FAILED) {
s6 = peg$parseDIGIT_OR_UNDER();
if (s6 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s7 = peg$c72;
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c73); }
}
if (s7 !== peg$FAILED) {
s8 = peg$parseDIGIT_OR_UNDER();
if (s8 !== peg$FAILED) {
s9 = peg$parseDIGIT_OR_UNDER();
if (s9 !== peg$FAILED) {
s10 = peg$parsesecfragment();
if (s10 === peg$FAILED) {
s10 = peg$c25;
}
if (s10 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 45) {
s11 = peg$c47;
peg$currPos++;
} else {
s11 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c48); }
}
if (s11 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 43) {
s11 = peg$c44;
peg$currPos++;
} else {
s11 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c45); }
}
}
if (s11 !== peg$FAILED) {
s12 = peg$parseDIGIT_OR_UNDER();
if (s12 !== peg$FAILED) {
s13 = peg$parseDIGIT_OR_UNDER();
if (s13 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s14 = peg$c72;
peg$currPos++;
} else {
s14 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c73); }
}
if (s14 !== peg$FAILED) {
s15 = peg$parseDIGIT_OR_UNDER();
if (s15 !== peg$FAILED) {
s16 = peg$parseDIGIT_OR_UNDER();
if (s16 !== peg$FAILED) {
s2 = [s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16];
s1 = s2;
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
} else {
peg$currPos = s1;
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c74(s1);
}
s0 = s1;
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parsedatetime() {
var s0, s1, s2, s3, s4;
var key = peg$currPos * 49 + 38,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = peg$parsedate();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 84) {
s2 = peg$c75;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c76); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parsetime();
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 90) {
s4 = peg$c77;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c78); }
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c79(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsedate();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 84) {
s2 = peg$c75;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c76); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parsetime_with_offset();
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c80(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseS() {
var s0;
var key = peg$currPos * 49 + 39,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
if (peg$c81.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c82); }
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseNL() {
var s0, s1, s2;
var key = peg$currPos * 49 + 40,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
if (input.charCodeAt(peg$currPos) === 10) {
s0 = peg$c83;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c84); }
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 13) {
s1 = peg$c85;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c86); }
}
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 10) {
s2 = peg$c83;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c84); }
}
if (s2 !== peg$FAILED) {
s1 = [s1, s2];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseNLS() {
var s0;
var key = peg$currPos * 49 + 41,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$parseNL();
if (s0 === peg$FAILED) {
s0 = peg$parseS();
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseEOF() {
var s0, s1;
var key = peg$currPos * 49 + 42,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
peg$silentFails++;
if (input.length > peg$currPos) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c6); }
}
peg$silentFails--;
if (s1 === peg$FAILED) {
s0 = peg$c5;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseHEX() {
var s0;
var key = peg$currPos * 49 + 43,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
if (peg$c87.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c88); }
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseDIGIT_OR_UNDER() {
var s0, s1;
var key = peg$currPos * 49 + 44,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
if (peg$c89.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c90); }
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 95) {
s1 = peg$c91;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c92); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c93();
}
s0 = s1;
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseASCII_BASIC() {
var s0;
var key = peg$currPos * 49 + 45,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
if (peg$c94.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c95); }
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseDIGITS() {
var s0, s1, s2;
var key = peg$currPos * 49 + 46,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
s1 = [];
s2 = peg$parseDIGIT_OR_UNDER();
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parseDIGIT_OR_UNDER();
}
} else {
s1 = peg$c2;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c96(s1);
}
s0 = s1;
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseESCAPED() {
var s0, s1;
var key = peg$currPos * 49 + 47,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c97) {
s1 = peg$c97;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c98); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c99();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c100) {
s1 = peg$c100;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c101); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c102();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c103) {
s1 = peg$c103;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c104); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c105();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c106) {
s1 = peg$c106;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c107); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c108();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c109) {
s1 = peg$c109;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c110); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c111();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c112) {
s1 = peg$c112;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c113); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c114();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c115) {
s1 = peg$c115;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c116); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c117();
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$parseESCAPED_UNICODE();
}
}
}
}
}
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
function peg$parseESCAPED_UNICODE() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10;
var key = peg$currPos * 49 + 48,
cached = peg$cache[key];
if (cached) {
peg$currPos = cached.nextPos;
return cached.result;
}
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c118) {
s1 = peg$c118;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c119); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
s3 = peg$parseHEX();
if (s3 !== peg$FAILED) {
s4 = peg$parseHEX();
if (s4 !== peg$FAILED) {
s5 = peg$parseHEX();
if (s5 !== peg$FAILED) {
s6 = peg$parseHEX();
if (s6 !== peg$FAILED) {
s7 = peg$parseHEX();
if (s7 !== peg$FAILED) {
s8 = peg$parseHEX();
if (s8 !== peg$FAILED) {
s9 = peg$parseHEX();
if (s9 !== peg$FAILED) {
s10 = peg$parseHEX();
if (s10 !== peg$FAILED) {
s3 = [s3, s4, s5, s6, s7, s8, s9, s10];
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c120(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c121) {
s1 = peg$c121;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c122); }
}
if (s1 !== peg$FAILED) {
s2 = peg$currPos;
s3 = peg$parseHEX();
if (s3 !== peg$FAILED) {
s4 = peg$parseHEX();
if (s4 !== peg$FAILED) {
s5 = peg$parseHEX();
if (s5 !== peg$FAILED) {
s6 = peg$parseHEX();
if (s6 !== peg$FAILED) {
s3 = [s3, s4, s5, s6];
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
} else {
peg$currPos = s2;
s2 = peg$c2;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c120(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c2;
}
} else {
peg$currPos = s0;
s0 = peg$c2;
}
}
peg$cache[key] = { nextPos: peg$currPos, result: s0 };
return s0;
}
var nodes = [];
function genError(err, line, col) {
var ex = new Error(err);
ex.line = line;
ex.column = col;
throw ex;
}
function addNode(node) {
nodes.push(node);
}
function node(type, value, line, column, key) {
var obj = { type: type, value: value, line: line(), column: column() };
if (key) obj.key = key;
return obj;
}
function convertCodePoint(str, line, col) {
var num = parseInt("0x" + str);
if (
!isFinite(num) ||
Math.floor(num) != num ||
num < 0 ||
num > 0x10FFFF ||
(num > 0xD7FF && num < 0xE000)
) {
genError("Invalid Unicode escape code: " + str, line, col);
} else {
return fromCodePoint(num);
}
}
function fromCodePoint() {
var MAX_SIZE = 0x4000;
var codeUnits = [];
var highSurrogate;
var lowSurrogate;
var index = -1;
var length = arguments.length;
if (!length) {
return '';
}
var result = '';
while (++index < length) {
var codePoint = Number(arguments[index]);
if (codePoint <= 0xFFFF) { // BMP code point
codeUnits.push(codePoint);
} else { // Astral code point; split in surrogate halves
// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000;
highSurrogate = (codePoint >> 10) + 0xD800;
lowSurrogate = (codePoint % 0x400) + 0xDC00;
codeUnits.push(highSurrogate, lowSurrogate);
}
if (index + 1 == length || codeUnits.length > MAX_SIZE) {
result += String.fromCharCode.apply(null, codeUnits);
codeUnits.length = 0;
}
}
return result;
}
peg$result = peg$startRuleFunction();
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
return peg$result;
} else {
if (peg$result !== peg$FAILED && peg$currPos < input.length) {
peg$fail({ type: "end", description: "end of input" });
}
throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos);
}
}
return {
SyntaxError: SyntaxError,
parse: parse
};
})();
/***/ }),
/* 434 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function compile(nodes) {
var assignedPaths = [];
var valueAssignments = [];
var currentPath = "";
var data = {};
var context = data;
var arrayMode = false;
return reduce(nodes);
function reduce(nodes) {
var node;
for (var i = 0; i < nodes.length; i++) {
node = nodes[i];
switch (node.type) {
case "Assign":
assign(node);
break;
case "ObjectPath":
setPath(node);
break;
case "ArrayPath":
addTableArray(node);
break;
}
}
return data;
}
function genError(err, line, col) {
var ex = new Error(err);
ex.line = line;
ex.column = col;
throw ex;
}
function assign(node) {
var key = node.key;
var value = node.value;
var line = node.line;
var column = node.column;
var fullPath;
if (currentPath) {
fullPath = currentPath + "." + key;
} else {
fullPath = key;
}
if (typeof context[key] !== "undefined") {
genError("Cannot redefine existing key '" + fullPath + "'.", line, column);
}
context[key] = reduceValueNode(value);
if (!pathAssigned(fullPath)) {
assignedPaths.push(fullPath);
valueAssignments.push(fullPath);
}
}
function pathAssigned(path) {
return assignedPaths.indexOf(path) !== -1;
}
function reduceValueNode(node) {
if (node.type === "Array") {
return reduceArrayWithTypeChecking(node.value);
} else if (node.type === "InlineTable") {
return reduceInlineTableNode(node.value);
} else {
return node.value;
}
}
function reduceInlineTableNode(values) {
var obj = {};
for (var i = 0; i < values.length; i++) {
var val = values[i];
if (val.value.type === "InlineTable") {
obj[val.key] = reduceInlineTableNode(val.value.value);
} else if (val.type === "InlineTableValue") {
obj[val.key] = reduceValueNode(val.value);
}
}
return obj;
}
function setPath(node) {
var path = node.value;
var quotedPath = path.map(quoteDottedString).join(".");
var line = node.line;
var column = node.column;
if (pathAssigned(quotedPath)) {
genError("Cannot redefine existing key '" + path + "'.", line, column);
}
assignedPaths.push(quotedPath);
context = deepRef(data, path, {}, line, column);
currentPath = path;
}
function addTableArray(node) {
var path = node.value;
var quotedPath = path.map(quoteDottedString).join(".");
var line = node.line;
var column = node.column;
if (!pathAssigned(quotedPath)) {
assignedPaths.push(quotedPath);
}
assignedPaths = assignedPaths.filter(function(p) {
return p.indexOf(quotedPath) !== 0;
});
assignedPaths.push(quotedPath);
context = deepRef(data, path, [], line, column);
currentPath = quotedPath;
if (context instanceof Array) {
var newObj = {};
context.push(newObj);
context = newObj;
} else {
genError("Cannot redefine existing key '" + path + "'.", line, column);
}
}
// Given a path 'a.b.c', create (as necessary) `start.a`,
// `start.a.b`, and `start.a.b.c`, assigning `value` to `start.a.b.c`.
// If `a` or `b` are arrays and have items in them, the last item in the
// array is used as the context for the next sub-path.
function deepRef(start, keys, value, line, column) {
var traversed = [];
var traversedPath = "";
var path = keys.join(".");
var ctx = start;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
traversed.push(key);
traversedPath = traversed.join(".");
if (typeof ctx[key] === "undefined") {
if (i === keys.length - 1) {
ctx[key] = value;
} else {
ctx[key] = {};
}
} else if (i !== keys.length - 1 && valueAssignments.indexOf(traversedPath) > -1) {
// already a non-object value at key, can't be used as part of a new path
genError("Cannot redefine existing key '" + traversedPath + "'.", line, column);
}
ctx = ctx[key];
if (ctx instanceof Array && ctx.length && i < keys.length - 1) {
ctx = ctx[ctx.length - 1];
}
}
return ctx;
}
function reduceArrayWithTypeChecking(array) {
// Ensure that all items in the array are of the same type
var firstType = null;
for (var i = 0; i < array.length; i++) {
var node = array[i];
if (firstType === null) {
firstType = node.type;
} else {
if (node.type !== firstType) {
genError("Cannot add value of type " + node.type + " to array of type " +
firstType + ".", node.line, node.column);
}
}
}
// Recursively reduce array of nodes into array of the nodes' values
return array.map(reduceValueNode);
}
function quoteDottedString(str) {
if (str.indexOf(".") > -1) {
return "\"" + str + "\"";
} else {
return str;
}
}
}
module.exports = {
compile: compile
};
/***/ }),
/* 435 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Utils = void 0;
var tslib_1 = __webpack_require__(2);
var clone_1 = tslib_1.__importDefault(__webpack_require__(28));
var randombytes_1 = tslib_1.__importDefault(__webpack_require__(436));
var stellar_base_1 = __webpack_require__(29);
var errors_1 = __webpack_require__(36);
var Utils;
(function (Utils) {
function buildChallengeTx(serverKeypair, clientAccountID, homeDomain, timeout, networkPassphrase, webAuthDomain, memo, clientDomain, clientSigningKey) {
if (timeout === void 0) { timeout = 300; }
if (memo === void 0) { memo = null; }
if (clientDomain === void 0) { clientDomain = null; }
if (clientSigningKey === void 0) { clientSigningKey = null; }
if (clientAccountID.startsWith("M") && memo) {
throw Error("memo cannot be used if clientAccountID is a muxed account");
}
var account = new stellar_base_1.Account(serverKeypair.publicKey(), "-1");
var now = Math.floor(Date.now() / 1000);
var value = randombytes_1.default(48).toString("base64");
var builder = new stellar_base_1.TransactionBuilder(account, {
fee: stellar_base_1.BASE_FEE,
networkPassphrase: networkPassphrase,
timebounds: {
minTime: now,
maxTime: now + timeout,
},
})
.addOperation(stellar_base_1.Operation.manageData({
name: homeDomain + " auth",
value: value,
source: clientAccountID,
}))
.addOperation(stellar_base_1.Operation.manageData({
name: "web_auth_domain",
value: webAuthDomain,
source: account.accountId(),
}));
if (clientDomain) {
if (!clientSigningKey) {
throw Error("clientSigningKey is required if clientDomain is provided");
}
builder.addOperation(stellar_base_1.Operation.manageData({
name: "client_domain",
value: clientDomain,
source: clientSigningKey,
}));
}
if (memo) {
builder.addMemo(stellar_base_1.Memo.id(memo));
}
var transaction = builder.build();
transaction.sign(serverKeypair);
return transaction
.toEnvelope()
.toXDR("base64")
.toString();
}
Utils.buildChallengeTx = buildChallengeTx;
function readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain) {
var _a;
if (serverAccountID.startsWith("M")) {
throw Error("Invalid serverAccountID: multiplexed accounts are not supported.");
}
var transaction;
try {
transaction = new stellar_base_1.Transaction(challengeTx, networkPassphrase);
}
catch (_b) {
try {
transaction = new stellar_base_1.FeeBumpTransaction(challengeTx, networkPassphrase);
}
catch (_c) {
throw new errors_1.InvalidSep10ChallengeError("Invalid challenge: unable to deserialize challengeTx transaction string");
}
throw new errors_1.InvalidSep10ChallengeError("Invalid challenge: expected a Transaction but received a FeeBumpTransaction");
}
var sequence = Number.parseInt(transaction.sequence, 10);
if (sequence !== 0) {
throw new errors_1.InvalidSep10ChallengeError("The transaction sequence number should be zero");
}
if (transaction.source !== serverAccountID) {
throw new errors_1.InvalidSep10ChallengeError("The transaction source account is not equal to the server's account");
}
if (transaction.operations.length < 1) {
throw new errors_1.InvalidSep10ChallengeError("The transaction should contain at least one operation");
}
var _d = transaction.operations, operation = _d[0], subsequentOperations = _d.slice(1);
if (!operation.source) {
throw new errors_1.InvalidSep10ChallengeError("The transaction's operation should contain a source account");
}
var clientAccountID = operation.source;
var memo = null;
if (transaction.memo.type !== stellar_base_1.MemoNone) {
if (clientAccountID.startsWith("M")) {
throw new errors_1.InvalidSep10ChallengeError("The transaction has a memo but the client account ID is a muxed account");
}
if (transaction.memo.type !== stellar_base_1.MemoID) {
throw new errors_1.InvalidSep10ChallengeError("The transaction's memo must be of type `id`");
}
memo = transaction.memo.value;
}
if (operation.type !== "manageData") {
throw new errors_1.InvalidSep10ChallengeError("The transaction's operation type should be 'manageData'");
}
if (transaction.timeBounds &&
Number.parseInt((_a = transaction.timeBounds) === null || _a === void 0 ? void 0 : _a.maxTime, 10) === stellar_base_1.TimeoutInfinite) {
throw new errors_1.InvalidSep10ChallengeError("The transaction requires non-infinite timebounds");
}
if (!validateTimebounds(transaction, 60 * 5)) {
throw new errors_1.InvalidSep10ChallengeError("The transaction has expired");
}
if (operation.value === undefined) {
throw new errors_1.InvalidSep10ChallengeError("The transaction's operation values should not be null");
}
if (!operation.value) {
throw new errors_1.InvalidSep10ChallengeError("The transaction's operation value should not be null");
}
if (Buffer.from(operation.value.toString(), "base64").length !== 48) {
throw new errors_1.InvalidSep10ChallengeError("The transaction's operation value should be a 64 bytes base64 random string");
}
if (!homeDomains) {
throw new errors_1.InvalidSep10ChallengeError("Invalid homeDomains: a home domain must be provided for verification");
}
var matchedHomeDomain;
if (typeof homeDomains === "string") {
if (homeDomains + " auth" === operation.name) {
matchedHomeDomain = homeDomains;
}
}
else if (Array.isArray(homeDomains)) {
matchedHomeDomain = homeDomains.find(function (domain) { return domain + " auth" === operation.name; });
}
else {
throw new errors_1.InvalidSep10ChallengeError("Invalid homeDomains: homeDomains type is " + typeof homeDomains + " but should be a string or an array");
}
if (!matchedHomeDomain) {
throw new errors_1.InvalidSep10ChallengeError("Invalid homeDomains: the transaction's operation key name does not match the expected home domain");
}
for (var _i = 0, subsequentOperations_1 = subsequentOperations; _i < subsequentOperations_1.length; _i++) {
var op = subsequentOperations_1[_i];
if (op.type !== "manageData") {
throw new errors_1.InvalidSep10ChallengeError("The transaction has operations that are not of type 'manageData'");
}
if (op.source !== serverAccountID && op.name !== "client_domain") {
throw new errors_1.InvalidSep10ChallengeError("The transaction has operations that are unrecognized");
}
if (op.name === "web_auth_domain") {
if (op.value === undefined) {
throw new errors_1.InvalidSep10ChallengeError("'web_auth_domain' operation value should not be null");
}
if (op.value.compare(Buffer.from(webAuthDomain))) {
throw new errors_1.InvalidSep10ChallengeError("'web_auth_domain' operation value does not match " + webAuthDomain);
}
}
}
if (!verifyTxSignedBy(transaction, serverAccountID)) {
throw new errors_1.InvalidSep10ChallengeError("Transaction not signed by server: '" + serverAccountID + "'");
}
return { tx: transaction, clientAccountID: clientAccountID, matchedHomeDomain: matchedHomeDomain, memo: memo };
}
Utils.readChallengeTx = readChallengeTx;
function verifyChallengeTxThreshold(challengeTx, serverAccountID, networkPassphrase, threshold, signerSummary, homeDomains, webAuthDomain) {
var _a;
var signers = signerSummary.map(function (signer) { return signer.key; });
var signersFound = verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain);
var weight = 0;
var _loop_1 = function (signer) {
var sigWeight = ((_a = signerSummary.find(function (s) { return s.key === signer; })) === null || _a === void 0 ? void 0 : _a.weight) || 0;
weight += sigWeight;
};
for (var _i = 0, signersFound_1 = signersFound; _i < signersFound_1.length; _i++) {
var signer = signersFound_1[_i];
_loop_1(signer);
}
if (weight < threshold) {
throw new errors_1.InvalidSep10ChallengeError("signers with weight " + weight + " do not meet threshold " + threshold + "\"");
}
return signersFound;
}
Utils.verifyChallengeTxThreshold = verifyChallengeTxThreshold;
function verifyChallengeTxSigners(challengeTx, serverAccountID, networkPassphrase, signers, homeDomains, webAuthDomain) {
var tx = readChallengeTx(challengeTx, serverAccountID, networkPassphrase, homeDomains, webAuthDomain).tx;
var serverKP;
try {
serverKP = stellar_base_1.Keypair.fromPublicKey(serverAccountID);
}
catch (err) {
throw new Error("Couldn't infer keypair from the provided 'serverAccountID': " +
err.message);
}
var clientSigners = new Set();
for (var _i = 0, signers_1 = signers; _i < signers_1.length; _i++) {
var signer = signers_1[_i];
if (signer === serverKP.publicKey()) {
continue;
}
if (signer.charAt(0) !== "G") {
continue;
}
clientSigners.add(signer);
}
if (clientSigners.size === 0) {
throw new errors_1.InvalidSep10ChallengeError("No verifiable client signers provided, at least one G... address must be provided");
}
var clientSigningKey;
for (var _a = 0, _b = tx.operations; _a < _b.length; _a++) {
var op = _b[_a];
if (op.type === "manageData" && op.name === "client_domain") {
if (clientSigningKey) {
throw new errors_1.InvalidSep10ChallengeError("Found more than one client_domain operation");
}
clientSigningKey = op.source;
}
}
var allSigners = tslib_1.__spreadArrays([
serverKP.publicKey()
], Array.from(clientSigners));
if (clientSigningKey) {
allSigners.push(clientSigningKey);
}
var signersFound = gatherTxSigners(tx, allSigners);
var serverSignatureFound = false;
var clientSigningKeySignatureFound = false;
for (var _c = 0, signersFound_2 = signersFound; _c < signersFound_2.length; _c++) {
var signer = signersFound_2[_c];
if (signer === serverKP.publicKey()) {
serverSignatureFound = true;
}
if (signer === clientSigningKey) {
clientSigningKeySignatureFound = true;
}
}
if (!serverSignatureFound) {
throw new errors_1.InvalidSep10ChallengeError("Transaction not signed by server: '" + serverKP.publicKey() + "'");
}
if (clientSigningKey && !clientSigningKeySignatureFound) {
throw new errors_1.InvalidSep10ChallengeError("Transaction not signed by the source account of the 'client_domain' " +
"ManageData operation");
}
if (signersFound.length === 1) {
throw new errors_1.InvalidSep10ChallengeError("None of the given signers match the transaction signatures");
}
if (signersFound.length !== tx.signatures.length) {
throw new errors_1.InvalidSep10ChallengeError("Transaction has unrecognized signatures");
}
signersFound.splice(signersFound.indexOf(serverKP.publicKey()), 1);
if (clientSigningKey) {
signersFound.splice(signersFound.indexOf(clientSigningKey), 1);
}
return signersFound;
}
Utils.verifyChallengeTxSigners = verifyChallengeTxSigners;
function verifyTxSignedBy(transaction, accountID) {
return gatherTxSigners(transaction, [accountID]).length !== 0;
}
Utils.verifyTxSignedBy = verifyTxSignedBy;
function gatherTxSigners(transaction, signers) {
var hashedSignatureBase = transaction.hash();
var txSignatures = clone_1.default(transaction.signatures);
var signersFound = new Set();
for (var _i = 0, signers_2 = signers; _i < signers_2.length; _i++) {
var signer = signers_2[_i];
if (txSignatures.length === 0) {
break;
}
var keypair = void 0;
try {
keypair = stellar_base_1.Keypair.fromPublicKey(signer);
}
catch (err) {
throw new errors_1.InvalidSep10ChallengeError("Signer is not a valid address: " + err.message);
}
for (var i = 0; i < txSignatures.length; i++) {
var decSig = txSignatures[i];
if (!decSig.hint().equals(keypair.signatureHint())) {
continue;
}
if (keypair.verify(hashedSignatureBase, decSig.signature())) {
signersFound.add(signer);
txSignatures.splice(i, 1);
break;
}
}
}
return Array.from(signersFound);
}
Utils.gatherTxSigners = gatherTxSigners;
function validateTimebounds(transaction, gracePeriod) {
if (gracePeriod === void 0) { gracePeriod = 0; }
if (!transaction.timeBounds) {
return false;
}
var now = Math.floor(Date.now() / 1000);
var _a = transaction.timeBounds, minTime = _a.minTime, maxTime = _a.maxTime;
return (now >= Number.parseInt(minTime, 10) - gracePeriod &&
now <= Number.parseInt(maxTime, 10) + gracePeriod);
}
})(Utils = exports.Utils || (exports.Utils = {}));
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1).Buffer))
/***/ }),
/* 436 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global, process) {
// limit of Crypto.getRandomValues()
// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
var MAX_BYTES = 65536
// Node supports requesting up to this number of bytes
// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48
var MAX_UINT32 = 4294967295
function oldBrowser () {
throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
}
var Buffer = __webpack_require__(21).Buffer
var crypto = global.crypto || global.msCrypto
if (crypto && crypto.getRandomValues) {
module.exports = randomBytes
} else {
module.exports = oldBrowser
}
function randomBytes (size, cb) {
// phantomjs needs to throw
if (size > MAX_UINT32) throw new RangeError('requested too many random bytes')
var bytes = Buffer.allocUnsafe(size)
if (size > 0) { // getRandomValues fails on IE if size == 0
if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues
// can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
for (var generated = 0; generated < size; generated += MAX_BYTES) {
// buffer.slice automatically checks if the end is past the end of
// the buffer so we don't have to here
crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES))
}
} else {
crypto.getRandomValues(bytes)
}
}
if (typeof cb === 'function') {
return process.nextTick(function () {
cb(null, bytes)
})
}
return bytes
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(5), __webpack_require__(13)))
/***/ })
/******/ ]);Выполнить команду
Для локальной разработки. Не используйте в интернете!